问:
Trying to sort 2 pandas dataframe and then copy from one to another
I have two csv files I want to manipulate and then combine into one file. I first converted them to pandas. One pandas dataframe looks like this:

```<code>      Number  Quiz
0  111111145     0
1  111111108     1
2  111111123     1
3  111111114     0
4  111111132     0
</code>```

the other like this:

```<code>Last Name First Name       Number   Quiz
0  Student1      Student1  111111123
1  Student2      Student2  111111114
2  Student3      Student3  111111132
3  Student4      Student4  111111145
4  Student5      Student5  111111108
</code>```

I want to end up with something like this:

```<code>Last Name First Name       Number       Quiz
    0  Student1      Student1  111111108  1
    1  Student2      Student2  111111114  0
    2  Student3      Student3  111111123  1
    3  Student4      Student4  111111132  0
    4  Student5      Student5  111111145  0
</code>```

but when I run my code I end up getting:

```<code>Last Name First Name       Number       Quiz
    0  Student1      Student1  111111108  0
    1  Student2      Student2  111111114  1
    2  Student3      Student3  111111123  0
    3  Student4      Student4  111111132  1
    4  Student5      Student5  111111145  0
</code>```

And I am not sure why. My code is as follows:

```<code>import argparse
import sys, re
import numpy as np
import smtplib
from random import randint
import csv
import math
import pandas as pd

parser = argparse.ArgumentParser()
parser.add_argument('-cname', '--c', help = 'column name to copy')
parser.add_argument('-source', '--s', help = 'source file with the column to copy')
parser.add_argument('-target', '--t', help = 'the target file with the names and UINS')
parser.add_argument('-out', '--f', help = 'output file with column copied')

if len(sys.argv)==1:
    parser.print_help()
    sys.exit(1)
args = parser.parse_args()

sourceFile = pd.read_csv(args.s)
targetFile = pd.read_csv(args.t)
print sourceFile
print targetFile
del targetFile[args.c]
sourceFile.sort_values('UIN', ascending = True, inplace = True)
targetFile.sort_values('UIN', ascending = True, inplace = True)
print sourceFile
print targetFile
targetFile[args.c]= sourceFile[args.c]
targetFile.to_csv(args.f, index = False)
print targetFile
</code>```

答:
you should use a merge to get your output :

```<code>merged = df1.merge(df2, on="Number")
</code>```

Should work, but you might have a problem of duplicated "Quiz" column if it appears in df1.

you can use the following to remove this problem (removes the quiz column from your first dataframe before it computes:

```<code>merged = df1[df1.columns[:-1]].merge(df2, on="Number")
</code>```

Body:
I have two csv files I want to manipulate and then combine into one file. I first converted them to pandas. One pandas dataframe looks like this:

      Number  Quiz
0  111111145     0
1  111111108     1
2  111111123     1
3  111111114     0
4  111111132     0

the other like this:

Last Name First Name       Number   Quiz
0  Student1      Student1  111111123
1  Student2      Student2  111111114
2  Student3      Student3  111111132
3  Student4      Student4  111111145
4  Student5      Student5  111111108

I want to end up with something like this:

Last Name First Name       Number       Quiz
    0  Student1      Student1  111111108  1
    1  Student2      Student2  111111114  0
    2  Student3      Student3  111111123  1
    3  Student4      Student4  111111132  0
    4  Student5      Student5  111111145  0

but when I run my code I end up getting:

Last Name First Name       Number       Quiz
    0  Student1      Student1  111111108  0
    1  Student2      Student2  111111114  1
    2  Student3      Student3  111111123  0
    3  Student4      Student4  111111132  1
    4  Student5      Student5  111111145  0

And I am not sure why. My code is as follows:

import argparse
import sys, re
import numpy as np
import smtplib
from random import randint
import csv
import math
import pandas as pd

parser = argparse.ArgumentParser()
parser.add_argument('-cname', '--c', help = 'column name to copy')
parser.add_argument('-source', '--s', help = 'source file with the column to copy')
parser.add_argument('-target', '--t', help = 'the target file with the names and UINS')
parser.add_argument('-out', '--f', help = 'output file with column copied')

if len(sys.argv)==1:
    parser.print_help()
    sys.exit(1)
args = parser.parse_args()

sourceFile = pd.read_csv(args.s)
targetFile = pd.read_csv(args.t)
print sourceFile
print targetFile
del targetFile[args.c]
sourceFile.sort_values('UIN', ascending = True, inplace = True)
targetFile.sort_values('UIN', ascending = True, inplace = True)
print sourceFile
print targetFile
targetFile[args.c]= sourceFile[args.c]
targetFile.to_csv(args.f, index = False)
print targetFile

Body:
you should use a merge to get your output :

merged = df1.merge(df2, on="Number")

Should work, but you might have a problem of duplicated "Quiz" column if it appears in df1.

you can use the following to remove this problem (removes the quiz column from your first dataframe before it computes:

merged = df1[df1.columns[:-1]].merge(df2, on="Number")


来源: stackexchange

问:
Explain better the steps of officebackgroundtaskhandler.exe fast appear and dissapear issue?
I do have the steps, my Windows is in french but I can deduce what to click. It's just that I need more exact steps to guess better the translation and the idea:

Open Search Windows

What program to type ?

What to click in the program to see and change users ?

There are two scheduled tasks un Task Scheduler
  Quoted from Costas2 in April 2017,
  Library/Microsoft/Office:

OfficeBackgroundTaskHandlerLogon that runs when a user logs on and
  OfficeBackgroundTaskHandlerRegistration that runs every hour

Both were set to run under the "Users" account group. Since I didn't
  notice any popup at logon, I set
  OfficeBackgroundTaskHandlerRegistration to run under the "System"
  account and the hourly popups are now hidden. (Select the task, right
  click, Properties, click on 'Change User Or Group', type 'System', OK
  twice and voila.)

This is not the best solution from a security point of view, but until
  MS fixes it, it works for me.

It's mostly for me to understand how to fix the Windows bugs without saying nonesense all the time, and in case there are other terminal windows types that opens all the time later. Windows said it already sent the fix to the bug: " The fix is now available in mainstream builds 16.8210.2075 released on 6/6/17 " So we don't need to do nothing, just wait. It's just that I was beginning to understand informatics and now I'm totally lost, I have no idea where to begin, neither how to follow the steps quoted.

Quote is from here:
OfficeBackgroundTaskHandlerRegistration flashes a window every hour (Microsoft Answers, 2017)

答:
Update Microsoft Office. Open any Office 2016 app and choose:

File > Account > Update Options > Update

Source

ContentLicense: CC BY-SA 3.0


问:
Serialize .Net object to json, controlled using xml attributes
I have a .Net object which I've been serializing to Xml and is decorated with Xml attributes.  I would now like to serialize the same object to Json, preferably using the Newtonsoft Json.Net library.

I'd like to go directly from the .Net object in memory to a Json string (without serializing to Xml first).  I do not wish to add any Json attributes to the class, but instead would like for the Json serializer to use the existing Xml attributes.

```<code>public class world{
  [XmlIgnore]
  public int ignoreMe{ get; }

  [XmlElement("foo")]
  public int bar{ get; }

  [XmlElement("marco")]
  public int polo{ get; }
}
</code>```

becomes

```<code>{
  "foo":0,
  "marco":0
}
</code>```

答:
The class below can be used to serialize (and deserialize) parts of the object tree to XML and then to JSON.

Usage

```<code>[JsonObject]
public class ClassToSerializeWithJson
{
    [JsonProperty]
    public TypeThatIsJsonSerializable PropertySerializedWithJsonSerializer {get; set; }

    [JsonProperty]
    [JsonConverter(typeof(JsonXmlConverter<TypeThatIsXmlSerializable>))]
    public TypeThatIsXmlSerializable PropertySerializedWithCustomSerializer {get; set; }
}
</code>```

JsonXmlConverter class

```<code>public class JsonXmlConverter<TType> : JsonConverter where TType : class
{
    private static readonly XmlSerializer xmlSerializer = new XmlSerializer(typeof(TType));

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var xml = ToXml(value as TType);
        using (var stream = new StringReader(xml))
        {
            var xDoc = XDocument.Load(stream);
            var json = JsonConvert.SerializeXNode(xDoc);
            writer.WriteRawValue(json);
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            // consume the 'null' token to set the reader in the correct state
            JToken.Load(reader);
            return null;
        }
        var jObj = JObject.Load(reader);
        var json = jObj.ToString();
        var xDoc = JsonConvert.DeserializeXNode(json);
        var xml = xDoc.ToString();
        return FromXml(xml);
    }

    public override bool CanRead => true;

    public override bool CanConvert(Type objectType) => objectType == typeof(TType);

    private static TType FromXml(string xmlString)
    {
        using (StringReader reader = new StringReader(xmlString))
            return (TType)xmlSerializer.Deserialize(reader);
    }

    private static string ToXml(TType obj)
    {
        using (StringWriter writer = new StringWriter())
        using (XmlWriter xmlWriter = XmlWriter.Create(writer))
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add(String.Empty, String.Empty);

            xmlSerializer.Serialize(xmlWriter, obj, ns);
            return writer.ToString();
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a .Net object which I've been serializing to Xml and is decorated with Xml attributes.  I would now like to serialize the same object to Json, preferably using the Newtonsoft Json.Net library.

I'd like to go directly from the .Net object in memory to a Json string (without serializing to Xml first).  I do not wish to add any Json attributes to the class, but instead would like for the Json serializer to use the existing Xml attributes.

public class world{
  [XmlIgnore]
  public int ignoreMe{ get; }

  [XmlElement("foo")]
  public int bar{ get; }

  [XmlElement("marco")]
  public int polo{ get; }
}

becomes

{
  "foo":0,
  "marco":0
}

Body:
The class below can be used to serialize (and deserialize) parts of the object tree to XML and then to JSON.

Usage

[JsonObject]
public class ClassToSerializeWithJson
{
    [JsonProperty]
    public TypeThatIsJsonSerializable PropertySerializedWithJsonSerializer {get; set; }

    [JsonProperty]
    [JsonConverter(typeof(JsonXmlConverter<TypeThatIsXmlSerializable>))]
    public TypeThatIsXmlSerializable PropertySerializedWithCustomSerializer {get; set; }
}

JsonXmlConverter class

public class JsonXmlConverter<TType> : JsonConverter where TType : class
{
    private static readonly XmlSerializer xmlSerializer = new XmlSerializer(typeof(TType));

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var xml = ToXml(value as TType);
        using (var stream = new StringReader(xml))
        {
            var xDoc = XDocument.Load(stream);
            var json = JsonConvert.SerializeXNode(xDoc);
            writer.WriteRawValue(json);
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            // consume the 'null' token to set the reader in the correct state
            JToken.Load(reader);
            return null;
        }
        var jObj = JObject.Load(reader);
        var json = jObj.ToString();
        var xDoc = JsonConvert.DeserializeXNode(json);
        var xml = xDoc.ToString();
        return FromXml(xml);
    }

    public override bool CanRead => true;

    public override bool CanConvert(Type objectType) => objectType == typeof(TType);

    private static TType FromXml(string xmlString)
    {
        using (StringReader reader = new StringReader(xmlString))
            return (TType)xmlSerializer.Deserialize(reader);
    }

    private static string ToXml(TType obj)
    {
        using (StringWriter writer = new StringWriter())
        using (XmlWriter xmlWriter = XmlWriter.Create(writer))
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add(String.Empty, String.Empty);

            xmlSerializer.Serialize(xmlWriter, obj, ns);
            return writer.ToString();
        }
    }
}


问:
Angular 2 How to selectively save state while routing
I am creating a search page that allows users to navigate to the specific record and when they return to the search page, their search criteria are still populated.  I tried using this https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx and it worked great.

The issue is, there are other pages I navigate to that have filters based on request params, that are also saving the previous state, not the new one, for example, say i navigate to /page?type=foo and it displays 10 results, then I navigate to /page?type=bar, it should show 5 results, but is still showing the 10 results from foo...ie: it's also remembering it's previous state.

So my question is, How can I selectively control when state is saved. Ideally, I want to save state on the search screen only when coming from the details page, not when navigating to search from the main page.

Thanks

-Todd

答:
When comming from detail page and main page

```<code>this.route.params.subscribe(params => {
                    let detailPage = params[ 'detailPage' ];
                    if (detailPage) {
                          // do something
                     }
            });
</code>```

and in detail component

```<code>let link = ['pathScreen',{ detailPage : true }];
this.router.navigate(link)
</code>```

and in main Page

```<code> let link = ['pathScreen'];
 this.router.navigate(link)
</code>```

Body:
When comming from detail page and main page

this.route.params.subscribe(params => {
                    let detailPage = params[ 'detailPage' ];
                    if (detailPage) {
                          // do something
                     }
            });

and in detail component

let link = ['pathScreen',{ detailPage : true }];
this.router.navigate(link)

and in main Page

 let link = ['pathScreen'];
 this.router.navigate(link)


问:
Mysql lock read a single row for innodb
Need help to lock reading(select) row

At second 1 : Terminal A

```<code>START TRANSACTION;
SELECT * FROM tbl_processor WHERE id=1 FOR UPDATE; /*Or using this statement : SELECT * FROM tbl_processor WHERE id=1 LOCK IN READ MODE; */
UPDATE tbl_processor SET content='Updated content';  #Original content was content='Original content'
SELECT SLEEP(10); #Just to sleep for testing purpose
COMMIT;
</code>```

At second 2 : Terminal B;

```<code>SELECT * FROM tbl_processor WHERE id=1;
#This will return result immediately with content='Original content'
-----> This is my problem... I do not want this statement getting not updated content. It should wait until the Terminal A process completed
</code>```

答:
Change the second transaction (terminal B) to obtain a share lock:

```<code>SELECT * FROM tbl_processor WHERE id=1 LOCK IN SHARE MODE;
</code>```

I suggest you review the relevant information in the MySQL Reference Manual here:

https://dev.mysql.com/doc/refman/5.7/en/innodb-locking-reads.html

Title: Mysql lock read a single row for innodb

Body:
Need help to lock reading(select) row

At second 1 : Terminal A

START TRANSACTION;
SELECT * FROM tbl_processor WHERE id=1 FOR UPDATE; /*Or using this statement : SELECT * FROM tbl_processor WHERE id=1 LOCK IN READ MODE; */
UPDATE tbl_processor SET content='Updated content';  #Original content was content='Original content'
SELECT SLEEP(10); #Just to sleep for testing purpose
COMMIT;

At second 2 : Terminal B;

SELECT * FROM tbl_processor WHERE id=1;
#This will return result immediately with content='Original content'
-----> This is my problem... I do not want this statement getting not updated content. It should wait until the Terminal A process completed

Body:
Change the second transaction (terminal B) to obtain a share lock:

SELECT * FROM tbl_processor WHERE id=1 LOCK IN SHARE MODE;

I suggest you review the relevant information in the MySQL Reference Manual here:

https://dev.mysql.com/doc/refman/5.7/en/innodb-locking-reads.html


问:
push notification to predefined group in database using signalR
I am trying to send notification to specific groups created in database (not signalR groups to which users join using signalR) using signalR.

For example, a user has created an event and invited 2 people, all notifications related to that event must be brodcasted to only users invited.
The same for another event.

I have looked for such a solution but i didn't find what i actually want.

答:
If you are not going to utilize signalr groups as documented here.

Then assuming you are keeping track of the userid that is in your database group you could send to that specific userid or userids.

Clients.Client(userid).sendMessage(message);


问:
Error: [$injector:unpr] Unknown provider: musicServiceProvider <- musicService <- MusicController
I have trying to add a service to fetch data from API .
But its gives an error

Error: [$injector:unpr] Unknown provider: musicServiceProvider <-
  musicService <- MusicController"

Controller

```<code>(function (app) {
var MusicListController = function ($scope, musicService) {
    $scope.message = " Jagadish K M";
    musicService.getAll().then(function (response) {
        $scope.musics = response.data;
        console.log($scope.musics);
    });
  };
app.controller("MusicController", MusicListController);
    }(angular.module("theMusic")));
</code>```

Service
(function (app) {

```<code>var musicService = function ($http, musicApiUrl) {
    var getAll = function () {
        return $http.get(musicApiUrl);
    };
    var get = function () {
        return $http.get(musicApiUrl);
    }
    var getById = function (id) {
        return $http.get(musicApiUrl + id);
    };

    var update = function (music) {
        return $http.put(musicApiUrl + music.id, music);
    };

    var create = function (music) {
        return $http.post(musicApiUrl, music);
    };

    var destroy = function (id) {
        return $http.delete(musicApiUrl + id);
    };

    return {
        getAll: getAll,
        getById: getById,
        update: update,
        create: create,
    };
};
app.factory("musicService", musicService);
}(angular.module("theMusic")));
</code>```

I am newbie in angular. Thanks in advance

答:
You didn't inject your service.

```<code>angular.module("theMusic", ["musicService"])
</code>```

You should take a look to AngularJS Dependency Injection documentation.

Body:
I have trying to add a service to fetch data from API .
But its gives an error

Error: [$injector:unpr] Unknown provider: musicServiceProvider <-
  musicService <- MusicController"

Controller

(function (app) {
var MusicListController = function ($scope, musicService) {
    $scope.message = " Jagadish K M";
    musicService.getAll().then(function (response) {
        $scope.musics = response.data;
        console.log($scope.musics);
    });
  };
app.controller("MusicController", MusicListController);
    }(angular.module("theMusic")));

Service
(function (app) {

var musicService = function ($http, musicApiUrl) {
    var getAll = function () {
        return $http.get(musicApiUrl);
    };
    var get = function () {
        return $http.get(musicApiUrl);
    }
    var getById = function (id) {
        return $http.get(musicApiUrl + id);
    };

    var update = function (music) {
        return $http.put(musicApiUrl + music.id, music);
    };

    var create = function (music) {
        return $http.post(musicApiUrl, music);
    };

    var destroy = function (id) {
        return $http.delete(musicApiUrl + id);
    };

    return {
        getAll: getAll,
        getById: getById,
        update: update,
        create: create,
    };
};
app.factory("musicService", musicService);
}(angular.module("theMusic")));

I am newbie in angular. Thanks in advance

Body:
You didn't inject your service.

angular.module("theMusic", ["musicService"])

You should take a look to AngularJS Dependency Injection documentation.


问:
Upload patch set preserving existing reviews
We use Jenkins to verify patch sets. Sometimes Jenkins needs do some changes on the patch set. So it commit --amend the changes and then uploads the new patch set.

It work nicely besides the fact, that all manual reviews made to the original patch set get erased.

How can I push a new patch set (from Jenkins) without loosing all existing reviews/votes?

答:
Be aware that, in the situation you have described, you have a new patchset and, excluding in special situations, you don't want votes of the old patchset copied forward to the new patchset. For example: if someone have approved the patchset1 and Jenkins pushes the patchset2, probably he/she doesn't want to have his/her vote automatically copied to patchset2.

Said that: you can control how votes will/won't be copied forward to new patchset setting the label.LABEL-NAME.copyXXXXX options of the project. See more info in Gerrit documentation here.


问:
Angular 4: How to correctly pass data from component to html
I have some trouble understanding a simple task, basically I have a controller like this:

app.componet.ts

```<code>import { Component, ViewEncapsulation, Input } from '@angular/core';
import { Http } from '@angular/http';
import { FlexLayoutModule } from "@angular/flex-layout";
import * as io from "socket.io-client";
var b;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent {
  freqValue = [2,3];
  myData: Array<any>;
  autoTicks = false;
  invert = false;
  max = 15;
  min = 0;
  showTicks = true;
  step = 1;
  thumbLabel = true;
  vertical = true;
  color = 'primary';
  mode = 'determinate';
  //value = 50;
  socket : any;
  prova : any;
  @Input() valueSlider: number;

  constructor(){
    this.socket = io('localhost:3000');
      this.socket.on('value', function(a){
      b = a;
      console.log(a);
      console.log(b);
      this.valueSlider = b;
    });
  }
}
</code>```

and a page like this:
app.component.html

```<code>...
  <div fxLayout="row wrap" class="nopad">
    <md-slider class="example-margin" [disabled]="disabled" [invert]="invert" [max]="max" [min]="min" [step]="step" [thumb-label]="thumbLabel"
      [tick-interval]="tickInterval" [value]="valueSlider" [vertical]="false" fxFlex="100%">
    </md-slider>
  </div>
...
</code>```

I'm triyng to pass valueSlider from my TS to the HTML as a property of <md-slider>but without success...does anyone can explain me?
Thanks

答:
app.component.html

```<code><md-slider ... [value]="valueSlider"> ... </md-slider>
</code>```

Body:
I have some trouble understanding a simple task, basically I have a controller like this:

app.componet.ts

import { Component, ViewEncapsulation, Input } from '@angular/core';
import { Http } from '@angular/http';
import { FlexLayoutModule } from "@angular/flex-layout";
import * as io from "socket.io-client";
var b;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent {
  freqValue = [2,3];
  myData: Array<any>;
  autoTicks = false;
  invert = false;
  max = 15;
  min = 0;
  showTicks = true;
  step = 1;
  thumbLabel = true;
  vertical = true;
  color = 'primary';
  mode = 'determinate';
  //value = 50;
  socket : any;
  prova : any;
  @Input() valueSlider: number;

  constructor(){
    this.socket = io('localhost:3000');
      this.socket.on('value', function(a){
      b = a;
      console.log(a);
      console.log(b);
      this.valueSlider = b;
    });
  }
}

and a page like this:
app.component.html

...

    <md-slider class="example-margin" [disabled]="disabled" [invert]="invert" [max]="max" [min]="min" [step]="step" [thumb-label]="thumbLabel"
      [tick-interval]="tickInterval" [value]="valueSlider" [vertical]="false" fxFlex="100%">
    </md-slider>

...

I'm triyng to pass valueSlider from my TS to the HTML as a property of <md-slider>but without success...does anyone can explain me?
Thanks

Body:
app.component.html

<md-slider ... [value]="valueSlider"> ... </md-slider>


问:
Website display fast in browser but Timeout in Google Speed Site
I've an issue since fews days. When I test my website, I've this error :
Timeout while fetching the main resource. Ensure that the page loads in a browser and try again.

If I test my website in a browser, it's ok and very fast.

My website : www.artdeseduire.com

And this error append on every of my web sites. ( ex : www.bluesteel.fr )

Any ideas?

答:
I've just run your site through webpagetest.org and it seems that it takes a while to load. You can see the results here:

https://www.webpagetest.org/result/170608_J0_159D/

It appears as if you are loading around 50 or so images just on the home page. The page is also about 5 MB in weight which is causing the page to load slowly. This could be the cause of the Google Pagespeed timing out!

Remember, just because it is fast on a broadband connection - doesn't mean it will be fast for real users out there!

Some things you could consider:

Reducing the number of images on the page

Lazy loading the images

There are around 15 JavaScript files on the page, you could combine and minify these - also, do you need all of them?

Those are just a few things, but hope that helps!


问:
Remove Higher level index in Python DataFrame
I have a Dataframe as given Below,

```<code>      a
   ---+--
    b | c
--+---+--
0 | 1 | 2
1 | 3 | 4
</code>```

All i wanted to do is remove the Higher level index 'a' from data frame and get the Result output as

```<code>   b | c
--+---+--
0 | 1 | 2
1 | 3 | 4
</code>```

答:
You can try reset_index: </p>

```<code>df = df.reset_index()
</code>```

Body:
I have a Dataframe as given Below,

      a
   ---+--
    b | c
--+---+--
0 | 1 | 2
1 | 3 | 4

All i wanted to do is remove the Higher level index 'a' from data frame and get the Result output as

   b | c
--+---+--
0 | 1 | 2
1 | 3 | 4

Body:
You can try reset_index:

df = df.reset_index()


问:
Partial match Excel
I have Table A which contains only strings, or strings+numbers, in general the list is very inconsistent. I also have Table B which contains a list of the names I have to retrieve from Table A where there is a match or partial match. My issue is that sometimes my formula doesn't work.

As you can see in Column C the below formula works for all except for rows 5 and 8 because I want to retrieve "toro res" which is in my list (table B) and instead I have 0.

答:
As I stated create a table with inputs in one column and output in another, then change the return of the formula to the output column:

```<code>=INDEX($I$2:$I$5,MATCH(1,COUNTIF(A2,"*" & $H$2:$H$5 & "*"),0))
</code>```

Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

Title: Partial match Excel

Body:
As I stated create a table with inputs in one column and output in another, then change the return of the formula to the output column:

=INDEX($I$2:$I$5,MATCH(1,COUNTIF(A2,"*" & $H$2:$H$5 & "*"),0))

Being an array formula it must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


问:
CAPL Multiframe handling
I am writting a CAPL for Diagnostic request and response, I can get response if the data is  up to 8 bytes, if data is multiframe I am not getting respone and the message on the trace is "Breaking connection between server and tester", how to handle this? I know about the CANTP frames but in this case it should handle by CAN/Canoe .

答:
Please read CANoe ISO-TP protocol. In case of multiframe response, the tester has to send the flow control frame which provides synchronization between Sender and Receiver, which is usually 0x30. It also has fields for Block size of continous frames and seperation time. Try the below CAPL code.</p>

```<code>variables
{
   message 0x710 msg = { dlc=8,dir = rx };
   byte check_byte0;
}
on message 0x718
{
    check_byte0 = this.byte(0) & 0x30;
    if(check_byte0 == 0x10)
    {
       msg.dword(0)=0x30;
       msg.dword(4)=0x00;
       output(msg2);
    }
}
</code>```

Title: CAPL Multiframe handling

Body:
Please read CANoe ISO-TP protocol. In case of multiframe response, the tester has to send the flow control frame which provides synchronization between Sender and Receiver, which is usually 0x30. It also has fields for Block size of continous frames and seperation time. Try the below CAPL code.

variables
{
   message 0x710 msg = { dlc=8,dir = rx };
   byte check_byte0;
}
on message 0x718
{
    check_byte0 = this.byte(0) & 0x30;
    if(check_byte0 == 0x10)
    {
       msg.dword(0)=0x30;
       msg.dword(4)=0x00;
       output(msg2);
    }
}


问:
Is it possible to create a Singleton factory class maintaining a dictionary for instances?
I have multiple classes that inherit from IPrint. I want to instantiate these classes using a factory but I want to maintain a single instance of each type.
Is this possible?

Please find my sample code below.

```<code> public interface IPrint
    {
        void DoPrint();
    }
    public class DigitalPrint : IPrint
    {
        public void DoPrint()
        {
            // logic
        }
    }
    public class InkPrint : IPrint
    {
        public void DoPrint()
        {
            // logic
        }
    }
    public class PrintFactory
    {
        private static IDictionary<IPrint, object> prints = new
   Dictionary<IPrint, object>();
        private PrintFactory()
        {

        }
        public static IPrint GetPrint(PrintType type)
        {
            // return instance depending on type. Instantiate only once
             //like singleton
            // How to write so that it returns a single instance depending
            //on type
            return null;
        }
    }

    public enum PrintType
    {
        DigitalPrint,
        InkPrint
    }
</code>```

Can someone give me some idea if this is possible?

Thanks.

答:
You can create IPrint instances when initializing Dictionary<PrintType, IPrint>:

```<code>private static IDictionary<PrintType, IPrint> prints =
  new Dictionary<PrintType, IPrint> {
      { PrintType.DigitalPrint, new DigitalPrint() },
      { PrintType.InkPrint, new InkPrint() }
  };
</code>```

Getting print (thus print is a class, the same instance will be returned for each request):

```<code>public static IPrint GetPrint(PrintType type)
{
    IPrint print;
    if (!prints.TryGetValue(type, out print))
       return null;

    return print;
}
</code>```

If you don't want to create IPrint instances until the client asks for them, you can use Dictionary<PrintType, Lazy<IPrint>>:

```<code>private static IDictionary<string, Lazy<IPrint>> prints =
    new Dictionary<string, Lazy<IPrint>> {
        { PrintType.DigitalPrint, new Lazy<IPrint>(() => new DigitalPrint()) },
        { PrintType.InkPrint, new Lazy<IPrint>(() => new InkPrint()) }
    };
</code>```

Getting print (in this case only one instance of each IPrint type will be created, but not before someone tries to get the instance of that type):

```<code>public static IPrint GetPrint(PrintType type)
{
    Lazy<IPrint> factory;
    if (!prints.TryGetValue(type, out factory))
       return null;

    return factory.Value;
}
</code>```

Though I would consider using dependency injection framework instead of implementing such functionality manually.

Further reading: Ninject or Autofac

Body:
I have multiple classes that inherit from IPrint. I want to instantiate these classes using a factory but I want to maintain a single instance of each type.
Is this possible?

Please find my sample code below.

 public interface IPrint
    {
        void DoPrint();
    }
    public class DigitalPrint : IPrint
    {
        public void DoPrint()
        {
            // logic
        }
    }
    public class InkPrint : IPrint
    {
        public void DoPrint()
        {
            // logic
        }
    }
    public class PrintFactory
    {
        private static IDictionary<IPrint, object> prints = new
   Dictionary<IPrint, object>();
        private PrintFactory()
        {

        }
        public static IPrint GetPrint(PrintType type)
        {
            // return instance depending on type. Instantiate only once
             //like singleton
            // How to write so that it returns a single instance depending
            //on type
            return null;
        }
    }

    public enum PrintType
    {
        DigitalPrint,
        InkPrint
    }

Can someone give me some idea if this is possible?

Thanks.

Body:
You can create IPrint instances when initializing Dictionary<PrintType, IPrint>:

private static IDictionary<PrintType, IPrint> prints =
  new Dictionary<PrintType, IPrint> {
      { PrintType.DigitalPrint, new DigitalPrint() },
      { PrintType.InkPrint, new InkPrint() }
  };

Getting print (thus print is a class, the same instance will be returned for each request):

public static IPrint GetPrint(PrintType type)
{
    IPrint print;
    if (!prints.TryGetValue(type, out print))
       return null;

    return print;
}

If you don't want to create IPrint instances until the client asks for them, you can use Dictionary<PrintType, Lazy<IPrint>>:

private static IDictionary<string, Lazy<IPrint>> prints =
    new Dictionary<string, Lazy<IPrint>> {
        { PrintType.DigitalPrint, new Lazy<IPrint>(() => new DigitalPrint()) },
        { PrintType.InkPrint, new Lazy<IPrint>(() => new InkPrint()) }
    };

Getting print (in this case only one instance of each IPrint type will be created, but not before someone tries to get the instance of that type):

public static IPrint GetPrint(PrintType type)
{
    Lazy<IPrint> factory;
    if (!prints.TryGetValue(type, out factory))
       return null;

    return factory.Value;
}

Though I would consider using dependency injection framework instead of implementing such functionality manually.

Further reading: Ninject or Autofac


问:
Why can you do this conversion?
Why can you do this:

```<code>class Dummy {
    double i,j;
};

class Addition {
    int x,y;
  public:
    Addition (int a, int b) { x=a; y=b; }
    int result() { return x+y;}
};

int main () {
  Dummy d;
  Addition * padd;
  padd = (Addition*) &d;
  cout << padd->result();
  return 0;
}
</code>```

Why is padd = (Addition*) &d; valid when it will generate a run-time error whenever it gets used afterwards? A quote from cplusplus.com:

Unrestricted explicit type-casting allows to convert any pointer into
  any other pointer type, independently of the types they point to.

But why can you convert any pointer into any other pointer type just if you precede the reference with a casting operator?

Talking about that casting operator, how can it convert all types to another type? Does it call a conversion constructor because if so, I do not get it, because both Dummy nor Addition do not have a conversion constructor so how does this operation work then? How many operators does it have and is it the parentheses that are the operator itself, like = is an operator.

答:
When you use:

```<code>padd = (Addition*) &d;
</code>```

the compiler assumes that you, the person in charge, know what you are doing. If you shoot yourself in the foot, that's of your own choosing. The compiler is happy to let you do that.

If you would like the compiler to prevent you from such accidental, shoot-yourself-in-the-foot, situations, use static_cast.

```<code>padd = static_cast<Addition*>(&d);
</code>```

The compiler will let you know that that is not OK.

Title: Why can you do this conversion?

Body:
Why can you do this:

class Dummy {
    double i,j;
};

class Addition {
    int x,y;
  public:
    Addition (int a, int b) { x=a; y=b; }
    int result() { return x+y;}
};

int main () {
  Dummy d;
  Addition * padd;
  padd = (Addition*) &d;
  cout << padd->result();
  return 0;
}

Why is padd = (Addition*) &d; valid when it will generate a run-time error whenever it gets used afterwards? A quote from cplusplus.com:

Unrestricted explicit type-casting allows to convert any pointer into
  any other pointer type, independently of the types they point to.

But why can you convert any pointer into any other pointer type just if you precede the reference with a casting operator?

Talking about that casting operator, how can it convert all types to another type? Does it call a conversion constructor because if so, I do not get it, because both Dummy nor Addition do not have a conversion constructor so how does this operation work then? How many operators does it have and is it the parentheses that are the operator itself, like = is an operator.

Body:
When you use:

padd = (Addition*) &d;

the compiler assumes that you, the person in charge, know what you are doing. If you shoot yourself in the foot, that's of your own choosing. The compiler is happy to let you do that.

If you would like the compiler to prevent you from such accidental, shoot-yourself-in-the-foot, situations, use static_cast.

padd = static_cast<Addition*>(&d);

The compiler will let you know that that is not OK.


问:
unconfigured table schema_columnfamilies
I am new to cassandra and I am using cassandra version 2.1.17 which supports cassandra-cli . I created a keyspace using the following command

```<code>create keyspace employee with placement_strategy='org.apache.cassandra.locator.SimpleStrategy' and strategy_options = {replication_factor:1};
</code>```

However when I use the command

use employee;

I get the following error

```<code>unconfigured table schema_columnfamilies
</code>```

I am unable to understand what is the issue. Can someone help me resolve this issue. Thanks in advance.

答: Figured out the solution. The issue was that I had previously installed another version of cassandra and uninstalled it. It turned out that even though i uninstalled the application , some processes of previous version were still running. I killed those processes manually and restarted the cassandra server. </p>

Body:
I am new to cassandra and I am using cassandra version 2.1.17 which supports cassandra-cli . I created a keyspace using the following command

create keyspace employee with placement_strategy='org.apache.cassandra.locator.SimpleStrategy' and strategy_options = {replication_factor:1};

However when I use the command

use employee;

I get the following error

unconfigured table schema_columnfamilies

I am unable to understand what is the issue. Can someone help me resolve this issue. Thanks in advance.


问:
How to draw a "speech bubble" on an iPhone?
I'm trying to get a "speech bubble" effect similar to the one in Mac OS X when you right click on something in the dock.  Here's what I have now:

I need to get the "triangle" part of the lower portion.  Is there any way I can draw something like that and get a border around it?  This will be for an iPhone app.

Thanks in advance!

EDIT:  Many thanks to Brad Larson, here's what it looks like now:

答:
I've actually drawn this exact shape before (rounded rectangle with a pointing triangle at the bottom).  The Quartz drawing code that I used is as follows:

```<code>CGRect currentFrame = self.bounds;

CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineWidth(context, strokeWidth);
CGContextSetStrokeColorWithColor(context, [MyPopupLayer popupBorderColor]);
CGContextSetFillColorWithColor(context, [MyPopupLayer popupBackgroundColor]);

// Draw and fill the bubble
CGContextBeginPath(context);
CGContextMoveToPoint(context, borderRadius + strokeWidth + 0.5f, strokeWidth + HEIGHTOFPOPUPTRIANGLE + 0.5f);
CGContextAddLineToPoint(context, round(currentFrame.size.width / 2.0f - WIDTHOFPOPUPTRIANGLE / 2.0f) + 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f);
CGContextAddLineToPoint(context, round(currentFrame.size.width / 2.0f) + 0.5f, strokeWidth + 0.5f);
CGContextAddLineToPoint(context, round(currentFrame.size.width / 2.0f + WIDTHOFPOPUPTRIANGLE / 2.0f) + 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f);
CGContextAddArcToPoint(context, currentFrame.size.width - strokeWidth - 0.5f, strokeWidth + HEIGHTOFPOPUPTRIANGLE + 0.5f, currentFrame.size.width - strokeWidth - 0.5f, currentFrame.size.height - strokeWidth - 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, currentFrame.size.width - strokeWidth - 0.5f, currentFrame.size.height - strokeWidth - 0.5f, round(currentFrame.size.width / 2.0f + WIDTHOFPOPUPTRIANGLE / 2.0f) - strokeWidth + 0.5f, currentFrame.size.height - strokeWidth - 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, strokeWidth + 0.5f, currentFrame.size.height - strokeWidth - 0.5f, strokeWidth + 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, strokeWidth + 0.5f, strokeWidth + HEIGHTOFPOPUPTRIANGLE + 0.5f, currentFrame.size.width - strokeWidth - 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f, borderRadius - strokeWidth);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);

// Draw a clipping path for the fill
CGContextBeginPath(context);
CGContextMoveToPoint(context, borderRadius + strokeWidth + 0.5f, round((currentFrame.size.height + HEIGHTOFPOPUPTRIANGLE) * 0.50f) + 0.5f);
CGContextAddArcToPoint(context, currentFrame.size.width - strokeWidth - 0.5f, round((currentFrame.size.height + HEIGHTOFPOPUPTRIANGLE) * 0.50f) + 0.5f, currentFrame.size.width - strokeWidth - 0.5f, currentFrame.size.height - strokeWidth - 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, currentFrame.size.width - strokeWidth - 0.5f, currentFrame.size.height - strokeWidth - 0.5f, round(currentFrame.size.width / 2.0f + WIDTHOFPOPUPTRIANGLE / 2.0f) - strokeWidth + 0.5f, currentFrame.size.height - strokeWidth - 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, strokeWidth + 0.5f, currentFrame.size.height - strokeWidth - 0.5f, strokeWidth + 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, strokeWidth + 0.5f, round((currentFrame.size.height + HEIGHTOFPOPUPTRIANGLE) * 0.50f) + 0.5f, currentFrame.size.width - strokeWidth - 0.5f, round((currentFrame.size.height + HEIGHTOFPOPUPTRIANGLE) * 0.50f) + 0.5f, borderRadius - strokeWidth);
CGContextClosePath(context);
CGContextClip(context);
</code>```

The clipping path at the end can be left out if you're not going to use a gradient or some other more fill that's more complex than a simple color.

Body:
I've actually drawn this exact shape before (rounded rectangle with a pointing triangle at the bottom).  The Quartz drawing code that I used is as follows:

CGRect currentFrame = self.bounds;

CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineWidth(context, strokeWidth);
CGContextSetStrokeColorWithColor(context, [MyPopupLayer popupBorderColor]);
CGContextSetFillColorWithColor(context, [MyPopupLayer popupBackgroundColor]);

// Draw and fill the bubble
CGContextBeginPath(context);
CGContextMoveToPoint(context, borderRadius + strokeWidth + 0.5f, strokeWidth + HEIGHTOFPOPUPTRIANGLE + 0.5f);
CGContextAddLineToPoint(context, round(currentFrame.size.width / 2.0f - WIDTHOFPOPUPTRIANGLE / 2.0f) + 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f);
CGContextAddLineToPoint(context, round(currentFrame.size.width / 2.0f) + 0.5f, strokeWidth + 0.5f);
CGContextAddLineToPoint(context, round(currentFrame.size.width / 2.0f + WIDTHOFPOPUPTRIANGLE / 2.0f) + 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f);
CGContextAddArcToPoint(context, currentFrame.size.width - strokeWidth - 0.5f, strokeWidth + HEIGHTOFPOPUPTRIANGLE + 0.5f, currentFrame.size.width - strokeWidth - 0.5f, currentFrame.size.height - strokeWidth - 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, currentFrame.size.width - strokeWidth - 0.5f, currentFrame.size.height - strokeWidth - 0.5f, round(currentFrame.size.width / 2.0f + WIDTHOFPOPUPTRIANGLE / 2.0f) - strokeWidth + 0.5f, currentFrame.size.height - strokeWidth - 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, strokeWidth + 0.5f, currentFrame.size.height - strokeWidth - 0.5f, strokeWidth + 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, strokeWidth + 0.5f, strokeWidth + HEIGHTOFPOPUPTRIANGLE + 0.5f, currentFrame.size.width - strokeWidth - 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f, borderRadius - strokeWidth);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);

// Draw a clipping path for the fill
CGContextBeginPath(context);
CGContextMoveToPoint(context, borderRadius + strokeWidth + 0.5f, round((currentFrame.size.height + HEIGHTOFPOPUPTRIANGLE) * 0.50f) + 0.5f);
CGContextAddArcToPoint(context, currentFrame.size.width - strokeWidth - 0.5f, round((currentFrame.size.height + HEIGHTOFPOPUPTRIANGLE) * 0.50f) + 0.5f, currentFrame.size.width - strokeWidth - 0.5f, currentFrame.size.height - strokeWidth - 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, currentFrame.size.width - strokeWidth - 0.5f, currentFrame.size.height - strokeWidth - 0.5f, round(currentFrame.size.width / 2.0f + WIDTHOFPOPUPTRIANGLE / 2.0f) - strokeWidth + 0.5f, currentFrame.size.height - strokeWidth - 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, strokeWidth + 0.5f, currentFrame.size.height - strokeWidth - 0.5f, strokeWidth + 0.5f, HEIGHTOFPOPUPTRIANGLE + strokeWidth + 0.5f, borderRadius - strokeWidth);
CGContextAddArcToPoint(context, strokeWidth + 0.5f, round((currentFrame.size.height + HEIGHTOFPOPUPTRIANGLE) * 0.50f) + 0.5f, currentFrame.size.width - strokeWidth - 0.5f, round((currentFrame.size.height + HEIGHTOFPOPUPTRIANGLE) * 0.50f) + 0.5f, borderRadius - strokeWidth);
CGContextClosePath(context);
CGContextClip(context);

The clipping path at the end can be left out if you're not going to use a gradient or some other more fill that's more complex than a simple color.


答:
I would get rid of the enum and make a generic method:</p>

```<code>public static IPrint GetPrint<T>() where T : IPrint, new ()
{
    foreach (var key in prints.Keys) {
        if (key is T)
            return null;
    }
           return new T();
}
</code>```

Title: Is it possible to create a Singleton factory class maintaining a dictionary for instances?

Body:
I would get rid of the enum and make a generic method:

public static IPrint GetPrint<T>() where T : IPrint, new ()
{
    foreach (var key in prints.Keys) {
        if (key is T)
            return null;
    }
           return new T();
}


问:
Android:java.util.concurrent.ThreadPoolExecutor
In my app there is RecyclerView with tons of images in it.Images are loaded as user scrolls RecyclerView with this code:

```<code>    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,url);
    else
        loader.execute(url);
</code>```

Unfortunately sometimes when user scrolls fast this error occurs:

```<code>Task android.os.AsyncTask$3@73f1d84 rejected from
java.util.concurrent.ThreadPoolExecutor@8f5f96d[Running, pool size = 9,
active threads = 9, queued tasks = 128, completed tasks = 279]
</code>```

Is there way to detect if poolExecutor is full and skip image loading?

Whole Image class:

```<code>public class Image extends ImageView {
private AsyncTask<String,Integer,Bitmap> loader;

public Image(Context context) {
    super(context);
    this.setScaleType(ScaleType.FIT_XY);
}

public Image(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setScaleType(ScaleType.FIT_XY);
}

public void loadURL(String url) {
    if(loader!=null)
        loader.cancel(true);
    loader=new AsyncTask<String, Integer, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            URL url = null;
            byte[] bytes = null;
            HttpURLConnection connection=null;
            try {
                url = new URL(params[0]);
                connection=(HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Connection", "close");
                connection.setRequestMethod("GET");
                connection.setUseCaches(true);
                InputStream is = null;
                is=connection.getInputStream();
                bytes = IOUtils.toByteArray(is);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection!=null)
                connection.disconnect();
            Bitmap res=null;
            if(!isCancelled() && bytes!=null)
                res=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
            return res;
        }
        @Override
        protected void onPostExecute(Bitmap res) {
            if(res!=null) {
                setImageBitmap(res);
                _animate();
            }
        }
    };
    if (this.getDrawable()!=null) {
        Bitmap bmp=((BitmapDrawable) this.getDrawable()).getBitmap();
        this.setAnimation(null);
        if (bmp!=null) {
            bmp.recycle();
            //Log.d("image","recycled");
        }
        this.setImageBitmap(null);
    }
    /*
    ThreadPoolExecutor e =(ThreadPoolExecutor) Executors.newFixedThreadPool(9);
    Log.d("pool size",e.getActiveCount()+"/"+e.getMaximumPoolSize());
    if (e.getActiveCount() == e.getMaximumPoolSize()) {
    }
    */
    //start loading
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
    else
        loader.execute(url);
}
private void _animate() {
    ValueAnimator bgAnim= ValueAnimator.ofObject(new IntEvaluator(),0,255);
    bgAnim.setDuration(500);
    bgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            Image.this.getDrawable().setAlpha((int) (animation.getAnimatedValue()));
        }
    });
    bgAnim.start();
}
</code>```

}

答:
To detect if user scrolls fast you can use onFlingListener()

```<code>recyclerView.setOnFlingListener(new RecyclerView.OnFlingListener() {

    @Override
    public boolean onFling(int velocityX, int velocityY) {
        isFlinging = checkFlinging(velocityY);

        if (isFlinging) {
            //Stop image loading here
        }

        return false;
    }
});

private boolean checkFlinging(int velocityY) {
    return (velocityY < 0 && velocityY < -RECYCLER_VIEW_FLING_VELOCITY)
            || (velocityY > 0 && velocityY > RECYCLER_VIEW_FLING_VELOCITY);
}
</code>```

Let me explain a bit, velocityY because I use recyclerView with vertical scrolling (for horizontal scrolling just change this parameter to velocityX), RECYCLER_VIEW_FLING_VELOCITY - your fling velocity, for me RECYCLER_VIEW_FLING_VELOCITY = 7000.

Body:
In my app there is RecyclerView with tons of images in it.Images are loaded as user scrolls RecyclerView with this code:

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,url);
    else
        loader.execute(url);

Unfortunately sometimes when user scrolls fast this error occurs:

Task android.os.AsyncTask$3@73f1d84 rejected from
java.util.concurrent.ThreadPoolExecutor@8f5f96d[Running, pool size = 9,
active threads = 9, queued tasks = 128, completed tasks = 279]

Is there way to detect if poolExecutor is full and skip image loading?

Whole Image class:

public class Image extends ImageView {
private AsyncTask<String,Integer,Bitmap> loader;

public Image(Context context) {
    super(context);
    this.setScaleType(ScaleType.FIT_XY);
}

public Image(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setScaleType(ScaleType.FIT_XY);
}

public void loadURL(String url) {
    if(loader!=null)
        loader.cancel(true);
    loader=new AsyncTask<String, Integer, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            URL url = null;
            byte[] bytes = null;
            HttpURLConnection connection=null;
            try {
                url = new URL(params[0]);
                connection=(HttpURLConnection) url.openConnection();
                connection.setRequestProperty("Connection", "close");
                connection.setRequestMethod("GET");
                connection.setUseCaches(true);
                InputStream is = null;
                is=connection.getInputStream();
                bytes = IOUtils.toByteArray(is);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection!=null)
                connection.disconnect();
            Bitmap res=null;
            if(!isCancelled() && bytes!=null)
                res=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
            return res;
        }
        @Override
        protected void onPostExecute(Bitmap res) {
            if(res!=null) {
                setImageBitmap(res);
                _animate();
            }
        }
    };
    if (this.getDrawable()!=null) {
        Bitmap bmp=((BitmapDrawable) this.getDrawable()).getBitmap();
        this.setAnimation(null);
        if (bmp!=null) {
            bmp.recycle();
            //Log.d("image","recycled");
        }
        this.setImageBitmap(null);
    }
    /*
    ThreadPoolExecutor e =(ThreadPoolExecutor) Executors.newFixedThreadPool(9);
    Log.d("pool size",e.getActiveCount()+"/"+e.getMaximumPoolSize());
    if (e.getActiveCount() == e.getMaximumPoolSize()) {
    }
    */
    //start loading
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
    else
        loader.execute(url);
}
private void _animate() {
    ValueAnimator bgAnim= ValueAnimator.ofObject(new IntEvaluator(),0,255);
    bgAnim.setDuration(500);
    bgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            Image.this.getDrawable().setAlpha((int) (animation.getAnimatedValue()));
        }
    });
    bgAnim.start();
}

}

Body:
To detect if user scrolls fast you can use onFlingListener()

recyclerView.setOnFlingListener(new RecyclerView.OnFlingListener() {

    @Override
    public boolean onFling(int velocityX, int velocityY) {
        isFlinging = checkFlinging(velocityY);

        if (isFlinging) {
            //Stop image loading here
        }

        return false;
    }
});

private boolean checkFlinging(int velocityY) {
    return (velocityY < 0 && velocityY < -RECYCLER_VIEW_FLING_VELOCITY)
            || (velocityY > 0 && velocityY > RECYCLER_VIEW_FLING_VELOCITY);
}

Let me explain a bit, velocityY because I use recyclerView with vertical scrolling (for horizontal scrolling just change this parameter to velocityX), RECYCLER_VIEW_FLING_VELOCITY - your fling velocity, for me RECYCLER_VIEW_FLING_VELOCITY = 7000.


问:
How do I send emails outside my domain with Exchange 2007 and c#
I am able to send emails using the typical C# SMTP code across Exchange 2007 as long as both the from and to addresses are within my domain.

As soon as I try to send emails outside the domain I get:

Exception Details: System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.7.1 Unable to relay

How can I get exchange to accept my email and send it out to the internet?

答:
Try #2... How about using a Exchange Pickup Folder instead? They are a faster way to send emails through Exchange because it just creates the email and drops it in the folder, no waiting to connect to the server or waiting for a reply. Plus I think it skips the whole relay issue.

Configure youur SmtpClient like so:

```<code>SmtpClient srv = new SmtpClient("exchsrv2007", 25) {
    DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
    PickupDirectoryLocation = "\\exchsrv2007\PickupFolder"
}
...
</code>```

OwnerDisplayName: jmcd

Body:
Try #2... How about using a Exchange Pickup Folder instead? They are a faster way to send emails through Exchange because it just creates the email and drops it in the folder, no waiting to connect to the server or waiting for a reply. Plus I think it skips the whole relay issue.

Configure youur SmtpClient like so:

SmtpClient srv = new SmtpClient("exchsrv2007", 25) {
    DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
    PickupDirectoryLocation = "\\exchsrv2007\PickupFolder"
}
...

OwnerDisplayName: David Thomas Garcia


问:
Unable to obtain moments using tensorflow
I want to calculate the moments of a vector x = np.random.normal(0,1,[1,500]). When I do mean, std = tf.nn.moments(x,axes=[0]), it throws this error:

```<code>File "/tmp/venv/local/lib/python2.7/site-packages/tensorflow/python/ops/nn.py", line 830, in moments
y = math_ops.cast(x, dtypes.float32) if x.dtype == dtypes.float16 else x
TypeError: data type not understood
</code>```

I am using tensorflow==0.11.0. What is the correct syntax?

答:
As shown in the documentation for tf.nn.moments, the input x must be a Tensor.

You should use something like the following:

```<code>x = tf.placeholder("float", [None,500])
mean, std = tf.nn.moments(x, axes=[0])

sess = tf.Session()
sess.run(tf.global_variables_initializer())
sample_mean, sample_std = sess.run([mean, std],
    feed_dict={x: np.random.normal(0,1,[1,500])})
</code>```

Note: This particular calculation does not make much sense, since there is only one data value. You may want to either increase the shape to something like [32, 500], or more likely change the axes from [0] to [1].

Regardless, the calculation will complete without errors, despite the calculated standard deviation being equal to 0, because the moments are calculated along an axis with one dimension.

Body:
I want to calculate the moments of a vector x = np.random.normal(0,1,[1,500]). When I do mean, std = tf.nn.moments(x,axes=[0]), it throws this error:

File "/tmp/venv/local/lib/python2.7/site-packages/tensorflow/python/ops/nn.py", line 830, in moments
y = math_ops.cast(x, dtypes.float32) if x.dtype == dtypes.float16 else x
TypeError: data type not understood

I am using tensorflow==0.11.0. What is the correct syntax?

Body:
As shown in the documentation for tf.nn.moments, the input x must be a Tensor.

You should use something like the following:

x = tf.placeholder("float", [None,500])
mean, std = tf.nn.moments(x, axes=[0])

sess = tf.Session()
sess.run(tf.global_variables_initializer())
sample_mean, sample_std = sess.run([mean, std],
    feed_dict={x: np.random.normal(0,1,[1,500])})

Note: This particular calculation does not make much sense, since there is only one data value. You may want to either increase the shape to something like [32, 500], or more likely change the axes from [0] to [1].

Regardless, the calculation will complete without errors, despite the calculated standard deviation being equal to 0, because the moments are calculated along an axis with one dimension.


问:
c++ two functions do the same except one line
I dont want to duplicate my code, but I have 2 functions which do the same except 1 line.
I do want separate functions that will call a private function, that might be a template and will solve my duplicate code problem.

```<code>double EuclideanDistance::calculateDistance(const Point &p1, const Point &p2) const
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;
    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        sum += pow( p1[i] - p2[i], 2.0);
    }
    return sqrt(sum);
}

double EuclideanDistance::calculateWeightedDistance(const Point &p1, const Point &p2, const double *weights) const
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;
    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        sum += pow( ((p1[i] - p2[i])*weights[i]), 2.0);//here is the difference
    }
    return sqrt(sum);
}
</code>```

what do you suggest?

答:
You may factorize this way:</p>

```<code>template <typename F, typename Ts...>
double calculateDistanceImpl(F&& f, const Point &p1, const Point &p2, Ts&&... args)
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;

    double sum = 0.0;
    for( size_t i = 0; i != p1.getDimension(); i++)
    {
        sum += f(p1[i], p2[i], args[i]...);
    }
    return sqrt(sum);
}

double EuclideanDistance::calculateDistance(const Point &p1, const Point &p2) const
{
    return calculateDistanceImpl(
        [](auto&& p1, auto&& p2){ return pow(p1 - p2, 2.0);},
        p1, p2);
}

double EuclideanDistance::calculateWeightedDistance(const Point &p1,
                                                    const Point &p2,
                                                    const double *weights) const
{
    return calculateDistanceImpl(
        [](auto&& p1, auto&& p2, double weight){ return pow((p1 - p2) * weight, 2);},
        p1, p2, weights);
}
</code>```

Body:
I dont want to duplicate my code, but I have 2 functions which do the same except 1 line.
I do want separate functions that will call a private function, that might be a template and will solve my duplicate code problem.

double EuclideanDistance::calculateDistance(const Point &p1, const Point &p2) const
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;
    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        sum += pow( p1[i] - p2[i], 2.0);
    }
    return sqrt(sum);
}

double EuclideanDistance::calculateWeightedDistance(const Point &p1, const Point &p2, const double *weights) const
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;
    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        sum += pow( ((p1[i] - p2[i])*weights[i]), 2.0);//here is the difference
    }
    return sqrt(sum);
}

what do you suggest?

Body:
You may factorize this way:

template <typename F, typename Ts...>
double calculateDistanceImpl(F&& f, const Point &p1, const Point &p2, Ts&&... args)
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;

    double sum = 0.0;
    for( size_t i = 0; i != p1.getDimension(); i++)
    {
        sum += f(p1[i], p2[i], args[i]...);
    }
    return sqrt(sum);
}

double EuclideanDistance::calculateDistance(const Point &p1, const Point &p2) const
{
    return calculateDistanceImpl(
        [](auto&& p1, auto&& p2){ return pow(p1 - p2, 2.0);},
        p1, p2);
}

double EuclideanDistance::calculateWeightedDistance(const Point &p1,
                                                    const Point &p2,
                                                    const double *weights) const
{
    return calculateDistanceImpl(
        [](auto&& p1, auto&& p2, double weight){ return pow((p1 - p2) * weight, 2);},
        p1, p2, weights);
}


问:
calling an array index with a variable
I am trying to test a specific element from a list, and compare it to a string the user inputs. It is inside an if statement:

    if (textboxinput.Text.ToString() == main.steps[current])

In this context, current is an integer equal to 0, and after the if statement is done current++.
 this is a new wpf form window that is opened by clicking a button on the MainWindow wpf form. main is instantiated from the MainWindow1 class containing our list:
public List<string> steps = new List<string>();
 Whenever I run this code, I receive the argument out of range exception.

In short: I am trying substitute the index of the list with a variable, and it is saying it is out of range.
Still learning c#, and this is probably an easy fix, and it's probably a super obvious rule I'm forgetting, but any help would be appreciated, as the same exception happens on arrays as well.
      Here is the event for the button being clicked

```<code>int current = 0;
private void buttonanswer_Click(object sender, RoutedEventArgs e)
    {

        if (textboxinput.Text.ToString() == main.steps[current])
        {
            textboxoutput.Foreground = Brushes.Green;
            textboxoutput.AppendText(textboxinput + Environment.NewLine);
            textboxinput.Clear();

        }
        else
        {
            textboxoutput.Foreground = Brushes.Red;
            textboxoutput.AppendText(textboxinput + Environment.NewLine);
            textboxinput.Clear();
        }
        current++;
    }
</code>```

答: Make sure that when you're looping current, it is always less than the length of the main.steps array. Remember, if an array contains 5 elements, they are numbered 0, 1, 2, 3, and 4 for example. Most likely you are allowing current to reach the number 5 (or whatever is the size of your array in your particular case). This type of mistake would be what causes an out of bounds exception when working with an array.</p>

Title: calling an array index with a variable

Body:
I am trying to test a specific element from a list, and compare it to a string the user inputs. It is inside an if statement:

    if (textboxinput.Text.ToString() == main.steps[current])

In this context, current is an integer equal to 0, and after the if statement is done current++.
 this is a new wpf form window that is opened by clicking a button on the MainWindow wpf form. main is instantiated from the MainWindow1 class containing our list:
public List<string> steps = new List<string>();
 Whenever I run this code, I receive the argument out of range exception.

In short: I am trying substitute the index of the list with a variable, and it is saying it is out of range.
Still learning c#, and this is probably an easy fix, and it's probably a super obvious rule I'm forgetting, but any help would be appreciated, as the same exception happens on arrays as well.
      Here is the event for the button being clicked

int current = 0;
private void buttonanswer_Click(object sender, RoutedEventArgs e)
    {

        if (textboxinput.Text.ToString() == main.steps[current])
        {
            textboxoutput.Foreground = Brushes.Green;
            textboxoutput.AppendText(textboxinput + Environment.NewLine);
            textboxinput.Clear();

        }
        else
        {
            textboxoutput.Foreground = Brushes.Red;
            textboxoutput.AppendText(textboxinput + Environment.NewLine);
            textboxinput.Clear();
        }
        current++;
    }


答:
If you use a C style cast, there is no check for errors or compatibility between the pointers. Also, I think you misunderstand the purpose of the unary operator &, in this case it gives the address of d and is not related to references.

Objects in memory are just bits that the program knows to be some type, if you tell it that it is another type it will not affect anything in the variable.

Title: Why can you do this conversion?


问:
Retrieving data from Firebase and storing as annotations on a map
I've successfully managed to store data to my Firebase database from a form I created in a view controller but now need to retrieve the data to display as annotations on a map on a second view controller but do not know how I should go about doing this task after searching and finding nothing online.

Here is my working code that saves my data successfully to the Firebase database:

```<code>import UIKit
import CoreLocation
import Firebase

class AddSightingViewController: UIViewController {

    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var latitudeLabel: UILabel!
    @IBOutlet weak var longitudeLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UITextView!

    var locManager = CLLocationManager()
    var currentLocation: CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set Date & Time

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium

        dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMM d, yyyy") // // set template after setting locale

        let dateString = "\(dateFormatter.string(from: Date() as Date))"
        dateLabel.text = String(dateString)

        let timeFormatter = DateFormatter()
        timeFormatter.timeStyle = .medium

        timeFormatter.setLocalizedDateFormatFromTemplate("hhmm")

        let timeString = "\(timeFormatter.string(from: Date() as Date))"

        timeLabel.text = String(timeString)

        // Set Latitude & Longitude

        locManager.requestWhenInUseAuthorization()

        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
            CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
            currentLocation = locManager.location
            self.latitudeLabel.text = String("\(currentLocation.coordinate.latitude)")
            self.longitudeLabel.text = String("\(currentLocation.coordinate.longitude)")
        }
    }

    func post() {

        let date = dateLabel.text
        let time = timeLabel.text
        let latitude = latitudeLabel.text
        let longitude = longitudeLabel.text
        let sightingDescription = descriptionLabel.text

        let post: [String : AnyObject] = ["Date" : date as AnyObject,
                                          "Time" : time as AnyObject,
                                          "Latitude" : latitude as AnyObject,
                                          "Longitude" : longitude as AnyObject,
                                          "Description" : sightingDescription as AnyObject]

        var ref: DatabaseReference!
        ref = Database.database().reference()
        ref.child("Sightings").childByAutoId().setValue(post)

    }

    @IBAction func saveButton(_ sender: Any) {

        post()

        // Create the alert controller
        let alertController = UIAlertController(title: "Sighting Logged Successfully", message: "Your logged entry will now show up on the map for others to see. Thank You!", preferredStyle: .alert)

        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
            UIAlertAction in
            NSLog("OK Pressed")

        }

        // Add the actions
        alertController.addAction(okAction)

        // Present the controller
        self.present(alertController, animated: true, completion: nil)

    }

}
</code>```

答:
After working on this I've eventually got it to work by using the following function and calling it in viewDidLoad()</p>

```<code>func displayAnnotations() {

        let ref = Database.database().reference()
        ref.child("Sightings").observe(.childAdded, with: { (snapshot) in

            let date = (snapshot.value as AnyObject!)!["Date"] as! String!
            let time = (snapshot.value as AnyObject!)!["Time"] as! String!
            let latitude = (snapshot.value as AnyObject!)!["Latitude"] as! String!
            let longitude = (snapshot.value as AnyObject!)!["Longitude"] as! String!
            let desc = (snapshot.value as AnyObject!)!["Description"] as! String!

            let annotation = MKPointAnnotation()

            annotation.coordinate = CLLocationCoordinate2D(latitude: (Double(latitude!))!, longitude: (Double(longitude!))!)
            annotation.title = date
            annotation.subtitle = time
            self.map.addAnnotation(annotation)

        })}
</code>```

Body:
I've successfully managed to store data to my Firebase database from a form I created in a view controller but now need to retrieve the data to display as annotations on a map on a second view controller but do not know how I should go about doing this task after searching and finding nothing online.

Here is my working code that saves my data successfully to the Firebase database:

import UIKit
import CoreLocation
import Firebase

class AddSightingViewController: UIViewController {

    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var latitudeLabel: UILabel!
    @IBOutlet weak var longitudeLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UITextView!

    var locManager = CLLocationManager()
    var currentLocation: CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set Date & Time

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium

        dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMM d, yyyy") // // set template after setting locale

        let dateString = "\(dateFormatter.string(from: Date() as Date))"
        dateLabel.text = String(dateString)

        let timeFormatter = DateFormatter()
        timeFormatter.timeStyle = .medium

        timeFormatter.setLocalizedDateFormatFromTemplate("hhmm")

        let timeString = "\(timeFormatter.string(from: Date() as Date))"

        timeLabel.text = String(timeString)

        // Set Latitude & Longitude

        locManager.requestWhenInUseAuthorization()

        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
            CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
            currentLocation = locManager.location
            self.latitudeLabel.text = String("\(currentLocation.coordinate.latitude)")
            self.longitudeLabel.text = String("\(currentLocation.coordinate.longitude)")
        }
    }

    func post() {

        let date = dateLabel.text
        let time = timeLabel.text
        let latitude = latitudeLabel.text
        let longitude = longitudeLabel.text
        let sightingDescription = descriptionLabel.text

        let post: [String : AnyObject] = ["Date" : date as AnyObject,
                                          "Time" : time as AnyObject,
                                          "Latitude" : latitude as AnyObject,
                                          "Longitude" : longitude as AnyObject,
                                          "Description" : sightingDescription as AnyObject]

        var ref: DatabaseReference!
        ref = Database.database().reference()
        ref.child("Sightings").childByAutoId().setValue(post)

    }

    @IBAction func saveButton(_ sender: Any) {

        post()

        // Create the alert controller
        let alertController = UIAlertController(title: "Sighting Logged Successfully", message: "Your logged entry will now show up on the map for others to see. Thank You!", preferredStyle: .alert)

        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
            UIAlertAction in
            NSLog("OK Pressed")

        }

        // Add the actions
        alertController.addAction(okAction)

        // Present the controller
        self.present(alertController, animated: true, completion: nil)

    }

}

Body:
After working on this I've eventually got it to work by using the following function and calling it in viewDidLoad()

func displayAnnotations() {

        let ref = Database.database().reference()
        ref.child("Sightings").observe(.childAdded, with: { (snapshot) in

            let date = (snapshot.value as AnyObject!)!["Date"] as! String!
            let time = (snapshot.value as AnyObject!)!["Time"] as! String!
            let latitude = (snapshot.value as AnyObject!)!["Latitude"] as! String!
            let longitude = (snapshot.value as AnyObject!)!["Longitude"] as! String!
            let desc = (snapshot.value as AnyObject!)!["Description"] as! String!

            let annotation = MKPointAnnotation()

            annotation.coordinate = CLLocationCoordinate2D(latitude: (Double(latitude!))!, longitude: (Double(longitude!))!)
            annotation.title = date
            annotation.subtitle = time
            self.map.addAnnotation(annotation)

        })}


问:
arr.splice() is timing out in loop - better way to replace arr[i]?
So I am having an issue with my solution, and I may be entirely off on what needs to be done. I keep timing out which makes me believe I have the .splice() in an incorrect location.

The problem:

You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.

Example

For inputArray = [1, 1, 1], the output should be
  arrayChange(inputArray) = 3.

My Pseudo code

First check and see if the current index is greater than the next index. If not, continue check through the entire loop. If so, add one to the next index and test again until true. If you increment the next index by one, add one to a variable "moves". Return moves

function arrayChange(inputArray) {

    for( var i = 0; i < inputArray.length; i++){
        var addition = (inputArray[i+1]+1)
        if(inputArray[i] >= inputArray[i+1]){
           inputArray.splice(i,0, addition);
        }
    }
    return inputArray;
}```

My Error:

Execution time limit exceeded on test 1: Program exceeded the execution time limit. Make sure that it completes execution in a few seconds for any possible input.

答:
Why your code fails:

```<code>for( var i = 0; i < inputArray.length; i++){//iterate until reaching end of array
    var addition =(inputArray[i+1]+1);
    if(inputArray[i] >= inputArray[i+1]){  //if its not increasing
       inputArray.splice(i,0, addition);
    }
}
</code>```

Lets examine a sample input:

```<code>arrayChange([1,1]);
</code>```

So inputArray[i] is 1, and inputArray[i+1] is 1.
Therefore it will go into the if, as 1>=1. So it will add 1+1 into the array,but not at the end but at i, so at position 0. It will look like this:

```<code>[2,1,1]
</code>```

The loop will go on:

```<code>[2,2,2....,1,1]
</code>```

It will never end.

To make it work, you must stop at array.length-1 :

```<code>for( var i = 0; i < inputArray.length-1; i++){
</code>```

and you must insert at the right index,and also remove one:

```<code>inputArray.splice(i+1,1,addition);
</code>```

Non array changing approach:

```<code>function numchanges(array){
  var before=array[0],counter=0;
  for(var i=1;i<array.length;i++){
    if(before>=array[i]){
      //we need to change array[i] to before+1, so:
      counter+=(++before)-array[i];
    }else{
     before=array[i];
   }
  }
return counter;
}

console.log(numchanges([1,1,1]));//should return 3
</code>```

How it works:
A proper strictly monotonically increasing function would have values like this:

```<code>[1,2,3,4,5,10]
</code>```

So it might at least go one up, or it jumps up. So lets take one random array, and its valid counterpart:

```<code>[1,1,3,4,5,-1]
[1,2,3,4,5,6]
</code>```

So the changes needed:

```<code>[0,1,0,0,0,7] => 8
</code>```

So the upper code keeps the valid number ( before ) and the needed change while iterating from left to right. current starts with the first array item:

```<code>arrayChange([1,1]);
</code>```0

But we dont need to change the first array element, so we start at i=1.If this number is valid, so

```<code>arrayChange([1,1]);
</code>```1

we just go on:

```<code>arrayChange([1,1]);
</code>```2

If not, its not valid and we need a correction.

```<code>result+=before+1-array[i];
</code>```

So if the last was 5 (=before) and now weve got -10 (=array[i]), we need to correct it to 6 (=before+1);

```<code>result+=6--10//==16
</code>```

So we need another 16 corrections...

Body:
So I am having an issue with my solution, and I may be entirely off on what needs to be done. I keep timing out which makes me believe I have the .splice() in an incorrect location.

The problem:

You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.

Example

For inputArray = [1, 1, 1], the output should be
  arrayChange(inputArray) = 3.

My Pseudo code

First check and see if the current index is greater than the next index. If not, continue check through the entire loop. If so, add one to the next index and test again until true. If you increment the next index by one, add one to a variable "moves". Return moves

function arrayChange(inputArray) {

    for( var i = 0; i < inputArray.length; i++){
        var addition = (inputArray[i+1]+1)
        if(inputArray[i] >= inputArray[i+1]){
           inputArray.splice(i,0, addition);
        }
    }
    return inputArray;
}

My Error:

Execution time limit exceeded on test 1: Program exceeded the execution time limit. Make sure that it completes execution in a few seconds for any possible input.

Body:
Why your code fails:

for( var i = 0; i < inputArray.length; i++){//iterate until reaching end of array
    var addition =(inputArray[i+1]+1);
    if(inputArray[i] >= inputArray[i+1]){  //if its not increasing
       inputArray.splice(i,0, addition);
    }
}

Lets examine a sample input:

arrayChange([1,1]);

So inputArray[i] is 1, and inputArray[i+1] is 1.
Therefore it will go into the if, as 1>=1. So it will add 1+1 into the array,but not at the end but at i, so at position 0. It will look like this:

[2,1,1]

The loop will go on:

[2,2,2....,1,1]

It will never end.

To make it work, you must stop at array.length-1 :

for( var i = 0; i < inputArray.length-1; i++){

and you must insert at the right index,and also remove one:

inputArray.splice(i+1,1,addition);

Non array changing approach:

function numchanges(array){
  var before=array[0],counter=0;
  for(var i=1;i<array.length;i++){
    if(before>=array[i]){
      //we need to change array[i] to before+1, so:
      counter+=(++before)-array[i];
    }else{
     before=array[i];
   }
  }
return counter;
}

console.log(numchanges([1,1,1]));//should return 3

How it works:
A proper strictly monotonically increasing function would have values like this:

[1,2,3,4,5,10]

So it might at least go one up, or it jumps up. So lets take one random array, and its valid counterpart:

[1,1,3,4,5,-1]
[1,2,3,4,5,6]

So the changes needed:

[0,1,0,0,0,7] => 8

So the upper code keeps the valid number ( before ) and the needed change while iterating from left to right. current starts with the first array item:

before=array[0];//1

But we dont need to change the first array element, so we start at i=1.If this number is valid, so

before<array[i]

we just go on:

before=array[i];
i++;//due the for loop

If not, its not valid and we need a correction.

result+=before+1-array[i];

So if the last was 5 (=before) and now weve got -10 (=array[i]), we need to correct it to 6 (=before+1);

result+=6--10//==16

So we need another 16 corrections...


问:
I am trying to create a steam tax calculator, but it is failing horribly
Whatever i try, it always comes up with this error:

```<code>line 8, in <module>
    print(Bprice * Tax)
TypeError: can't multiply sequence by non-int of type 'float'
</code>```

Code:

```<code>print ("Steam market calculator")

Tax = 0.8789

buysell = input("Are you buying or selling an item? (buy/sell)")
if buysell == ("buy"):
   Bprice = input("What is the buyprice?")
   print(Bprice * Tax)
</code>```

It never works. Any ideas?

答:
When you use input in python it will return a string. You try to multiply that string to a float.

try

```<code>Bprice = float(input("What is the buyprice?"))
</code>```

Also, dont use capitalized variables, it's not good practice

Body:
Whatever i try, it always comes up with this error:

line 8, in <module>
    print(Bprice * Tax)
TypeError: can't multiply sequence by non-int of type 'float'

Code:

print ("Steam market calculator")

Tax = 0.8789

buysell = input("Are you buying or selling an item? (buy/sell)")
if buysell == ("buy"):
   Bprice = input("What is the buyprice?")
   print(Bprice * Tax)

It never works. Any ideas?

Body:
When you use input in python it will return a string. You try to multiply that string to a float.

try

Bprice = float(input("What is the buyprice?"))

Also, dont use capitalized variables, it's not good practice


答:
These kinds of casts are C style casts, and will let you cast just about anything to anything else. A cast is a statement to the compiler to disregard it's type safety rules and trust that you know best. This is sometimes necessary when the type system can't have all the information it needs to reach the right conclusions. However, if you are lying to the compiler about something's type, then you are producing undefined behavior.

In c++, you should avoid preforming C style casts and prefer the safer c++ alternatives (listed here. Theses casts can't completely protect you from yourself, but they do allow you to communicate the kind of cast you want to preform. Using this extra information, the compiler can warn you if your casts would do something other than what you expect them to do.

Title: Why can you do this conversion?

Body:
Why can you do this:

class Dummy {
    double i,j;
};

class Addition {
    int x,y;
  public:
    Addition (int a, int b) { x=a; y=b; }
    int result() { return x+y;}
};

int main () {
  Dummy d;
  Addition * padd;
  padd = (Addition*) &d;
  cout << padd->result();
  return 0;
}

Why is padd = (Addition*) &d; valid when it will generate a run-time error whenever it gets used afterwards? A quote from cplusplus.com:

Unrestricted explicit type-casting allows to convert any pointer into
  any other pointer type, independently of the types they point to.

But why can you convert any pointer into any other pointer type just if you precede the reference with a casting operator?

Talking about that casting operator, how can it convert all types to another type? Does it call a conversion constructor because if so, I do not get it, because both Dummy nor Addition do not have a conversion constructor so how does this operation work then? How many operators does it have and is it the parentheses that are the operator itself, like = is an operator.


问:
SWFAddress: adding "/" char at the end of an URL via JavaScript
how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.

So something like this:

```<code>http://mysite.com/section

// and after click to a specific <a ="#">button</a> get
http://mysite.com/section/#/sub-content

// instead of
http://mysite.com/section#/sub-content
</code>```

I've started with this code to do it:

```<code>$(".time_dot, .time_year").click (function () {
    onClickEvent (this);
});

function onClickEvent (dom) {
    var timer = setTimeout (function () {
        SWFAddress.setValue($(dom).parent().attr("id"));
    }, 200);
    // do something else
}
</code>```

The setTimeout method is used to avoid the  button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....

How can I do that?

答: You can't change the "path" part of the URL without reloading the page. So, if you're at http://mysite.com/section, you can not navigate to http://mysite.com/section/#/sub-content without reloading the page.</p>

Body:
how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.

So something like this:

http://mysite.com/section

// and after click to a specific button get
http://mysite.com/section/#/sub-content

// instead of
http://mysite.com/section#/sub-content

I've started with this code to do it:

$(".time_dot, .time_year").click (function () {
    onClickEvent (this);
});

function onClickEvent (dom) {
    var timer = setTimeout (function () {
        SWFAddress.setValue($(dom).parent().attr("id"));
    }, 200);
    // do something else
}

The setTimeout method is used to avoid the  button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....

How can I do that?


问:
Numbers bigger than 8 bytes in C
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

```<code>unsigned char n[16];
</code>```

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

```<code>//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}
</code>```

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

```<code>//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)
</code>```

答: You may want to use arbitrary-precision arithmetic, a.k.a. as bigint or bignum. You should use a library for that (because bignum algorithms are very clever and use some assembler code). I recommend GMPlib. See also this.

Title: Numbers bigger than 8 bytes in C

Body:
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

unsigned char n[16];

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)


问:
Panda dataframe element comparisson against a list of values
I have a pd dataframe with a column of 15000 values. I have another text file (so array or dataframe) with 400 values. My task is to check how many values out of those 400 are bigger than the element of the column in my data frame.

I.e. I need as an output a column len=15000 with values 0-400.

Any nice way to do this? For-looping defeats the purpose of using dataframes ;/

Thanks

答:
With 'col' as the column header and arr400 as the array of 400 elements, one approach would be to use NumPy broadcasting -

```<code>(df.col.values[:,None] < arr400).sum(axis=1)
</code>```

Possibly faster would be use np.count_nonzero -

```<code>np.count_nonzero(df.col.values[:,None] < arr400, axis=1)
</code>```

Sample run -

```<code>In [246]: df
Out[246]:
   col
0    7
1    2
2    6
3    0
4    8
5    1
6    6
7    3
8    1
9    1

In [247]: arr400
Out[247]: array([2, 2, 8, 7])

In [248]: (df.col.values[:,None] < arr400).sum(axis=1)
Out[248]: array([1, 2, 2, 4, 0, 4, 2, 2, 4, 4])

In [249]: np.count_nonzero(df.col.values[:,None] < arr400, axis=1)
Out[249]: array([1, 2, 2, 4, 0, 4, 2, 2, 4, 4])
</code>```

Body:
With 'col' as the column header and arr400 as the array of 400 elements, one approach would be to use NumPy broadcasting -

(df.col.values[:,None] < arr400).sum(axis=1)

Possibly faster would be use np.count_nonzero -

np.count_nonzero(df.col.values[:,None] < arr400, axis=1)

Sample run -

In [246]: df
Out[246]:
   col
0    7
1    2
2    6
3    0
4    8
5    1
6    6
7    3
8    1
9    1

In [247]: arr400
Out[247]: array([2, 2, 8, 7])

In [248]: (df.col.values[:,None] < arr400).sum(axis=1)
Out[248]: array([1, 2, 2, 4, 0, 4, 2, 2, 4, 4])

In [249]: np.count_nonzero(df.col.values[:,None] < arr400, axis=1)
Out[249]: array([1, 2, 2, 4, 0, 4, 2, 2, 4, 4])


问:
Refresh an UltraWinGrid from a separate form
I've got a form with a list of customers and another form where customers can be added. When I open the fAddCustomer form, from fCustomerList, I'm calling it using this code:

```<code>Dim f As New Form
f = New fAddCustomer(con, False)
f.MdiParent = Me.MdiParent
f.Show()
</code>```

On fCustomerAdd, I've got a ToolStripButton to add the customer. When the form is closed, I need to refresh the UltraWinGrid that I have on fCustomerList to view the new data on the list automatically.

Because I'm using a ToolStripButton and the form uses f.MdiParent = Me.MdiParent, I can't use the same solution that was used in this answer here, as there is no DialogResult on a ToolStripButton, and you can't use ShowDialog when using MdiParents.

Is there any other way I can achieve this at all?

答:
One that you could achieve this without changing the DataSource passing as @Plutonix suggested is to do something like this:

```<code>Private Sub fAddCustomer_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

Try
    If Application.OpenForms.OfType(Of fCustomerList).Any Then
       Application.OpenForms("fCustomerList").Close()
            Dim f As New fCustomerList()
            f.MdiParent = Me.MdiParent
            f.Show()
        End If

    Catch ex As Exception
        Debug.WriteLine(ex.Message)

    End Try
End Sub
</code>```

Body:
I've got a form with a list of customers and another form where customers can be added. When I open the fAddCustomer form, from fCustomerList, I'm calling it using this code:

Dim f As New Form
f = New fAddCustomer(con, False)
f.MdiParent = Me.MdiParent
f.Show()

On fCustomerAdd, I've got a ToolStripButton to add the customer. When the form is closed, I need to refresh the UltraWinGrid that I have on fCustomerList to view the new data on the list automatically.

Because I'm using a ToolStripButton and the form uses f.MdiParent = Me.MdiParent, I can't use the same solution that was used in this answer here, as there is no DialogResult on a ToolStripButton, and you can't use ShowDialog when using MdiParents.

Is there any other way I can achieve this at all?

Body:
One that you could achieve this without changing the DataSource passing as @Plutonix suggested is to do something like this:

Private Sub fAddCustomer_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

Try
    If Application.OpenForms.OfType(Of fCustomerList).Any Then
       Application.OpenForms("fCustomerList").Close()
            Dim f As New fCustomerList()
            f.MdiParent = Me.MdiParent
            f.Show()
        End If

    Catch ex As Exception
        Debug.WriteLine(ex.Message)

    End Try
End Sub


问:
Generic parsing of Expressiontree to SQL
So, im having this very simple linq provider that does stuff with objects in a small constrained domain. No need for a full blown Linq2Sql implementation, but some of the stuff i need to do involves sql queries. My thougt was that, if you look away from table and column names, most expression tree => sql must be very (very) generic.

```<code>Expression<Func<DateTime, bool>> expr = d => d.DateTime.Month == 1
</code>```

will always translate to

```<code>DATEPART({0}, m) = 1
</code>```

or

```<code>Expression<Func<DateTime?, bool>> expr = d => d.HasValue || d ==  DateTime.Now
</code>```

into

```<code>{0} IS NOT NULL OR {0} = NOW()
</code>```

hope you get the point. Is there any generic sql generators like this out there?

答: You should take a look at the IQueryable Toolkit and its related articles by Matt Warren http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx.</p>

Body:
So, im having this very simple linq provider that does stuff with objects in a small constrained domain. No need for a full blown Linq2Sql implementation, but some of the stuff i need to do involves sql queries. My thougt was that, if you look away from table and column names, most expression tree => sql must be very (very) generic.

Expression<Func<DateTime, bool>> expr = d => d.DateTime.Month == 1

will always translate to

DATEPART({0}, m) = 1

or

Expression<Func<DateTime?, bool>> expr = d => d.HasValue || d ==  DateTime.Now

into

{0} IS NOT NULL OR {0} = NOW()

hope you get the point. Is there any generic sql generators like this out there?


答:
Bprice is a String, not a number. You need to convert it to a number first:

```<code>print(float(Bprice) * Tax)
#      ^ float() converts it to a decimal number
</code>```

Be careful though, as if Bprice isn't convertible to a number, you'll get an error.

Title: I am trying to create a steam tax calculator, but it is failing horribly

Body:
Bprice is a String, not a number. You need to convert it to a number first:

print(float(Bprice) * Tax)
#      ^ float() converts it to a decimal number

Be careful though, as if Bprice isn't convertible to a number, you'll get an error.