问:
Unittest tests order
How can I be sure of the unittest methods' order? Is the alphabetical or numeric prefixes the proper way?

```<code>class TestFoo(TestCase):
    def test_1(self):
        ...
    def test_2(self):
        ...
</code>```

or

```<code>class TestFoo(TestCase):
    def test_a(self):
        ...
    def test_b(self):
        ...
</code>```

答:
A simple method for ordering "unittest" tests is to follow the init.d mechanism of giving them numeric names:

```<code>def test_00_createEmptyObject(self):
    obj = MyObject()
    self.assertIsEqual(obj.property1, 0)
    self.assertIsEqual(obj.dict1, {})

def test_01_createObject(self):
    obj = MyObject(property1="hello", dict1={"pizza":"pepperoni"})
    self.assertIsEqual(obj.property1, "hello")
    self.assertIsDictEqual(obj.dict1, {"pizza":"pepperoni"})

def test_10_reverseProperty(self):
    obj = MyObject(property1="world")
    obj.reverseProperty1()
    self.assertIsEqual(obj.property1, "dlrow")
</code>```

However, in such cases, you might want to consider structuring your tests differently so that you can build on previous construction cases. For instance, in the above, it might make sense to have a "construct and verify" function that constructs the object and validates its assignment of parameters.

```<code>def make_myobject(self, property1, dict1):  # Must be specified by caller
    obj = MyObject(property1=property1, dict1=dict1)
    if property1:
        self.assertEqual(obj.property1, property1)
    else:
        self.assertEqual(obj.property1, 0)
    if dict1:
        self.assertDictEqual(obj.dict1, dict1)
    else:
        self.assertEqual(obj.dict1, {})
    return obj

def test_00_createEmptyObject(self):
    obj = self.make_object(None, None)

def test_01_createObject(self):
    obj = self.make_object("hello", {"pizza":"pepperoni"})

def test_10_reverseProperty(self):
    obj = self.make_object("world", None)
    obj.reverseProperty()
    self.assertEqual(obj.property1, "dlrow")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Unittest tests order

Body:
How can I be sure of the unittest methods' order? Is the alphabetical or numeric prefixes the proper way?

class TestFoo(TestCase):
    def test_1(self):
        ...
    def test_2(self):
        ...

or

class TestFoo(TestCase):
    def test_a(self):
        ...
    def test_b(self):
        ...

Body:
A simple method for ordering "unittest" tests is to follow the init.d mechanism of giving them numeric names:

def test_00_createEmptyObject(self):
    obj = MyObject()
    self.assertIsEqual(obj.property1, 0)
    self.assertIsEqual(obj.dict1, {})

def test_01_createObject(self):
    obj = MyObject(property1="hello", dict1={"pizza":"pepperoni"})
    self.assertIsEqual(obj.property1, "hello")
    self.assertIsDictEqual(obj.dict1, {"pizza":"pepperoni"})

def test_10_reverseProperty(self):
    obj = MyObject(property1="world")
    obj.reverseProperty1()
    self.assertIsEqual(obj.property1, "dlrow")

However, in such cases, you might want to consider structuring your tests differently so that you can build on previous construction cases. For instance, in the above, it might make sense to have a "construct and verify" function that constructs the object and validates its assignment of parameters.

def make_myobject(self, property1, dict1):  # Must be specified by caller
    obj = MyObject(property1=property1, dict1=dict1)
    if property1:
        self.assertEqual(obj.property1, property1)
    else:
        self.assertEqual(obj.property1, 0)
    if dict1:
        self.assertDictEqual(obj.dict1, dict1)
    else:
        self.assertEqual(obj.dict1, {})
    return obj

def test_00_createEmptyObject(self):
    obj = self.make_object(None, None)

def test_01_createObject(self):
    obj = self.make_object("hello", {"pizza":"pepperoni"})

def test_10_reverseProperty(self):
    obj = self.make_object("world", None)
    obj.reverseProperty()
    self.assertEqual(obj.property1, "dlrow")


来源: stackexchange

问:
Get location for Kivy Garden MapView
I need get current location in GPS and pass for mapview.
My code not working, return error:
Code working, if in kv langue in MapView add lat: and lon: numeric value.
Any ideas for get values lat and lon from function on_locations ?

```<code>ValueError: None is not allowed for MapView.lat
</code>```

Code:

```<code>#-*- coding: utf-8 -*-
from kivy.lang import Builder
from plyer import gps
from kivy.app import App
from kivy.properties import StringProperty
from kivy.clock import Clock, mainthread
from kivy.uix.popup import Popup
from kivy.network.urlrequest import UrlRequest
from kivy.uix.label import Label
import json
import kivy.garden.mapview

kv = '''
#:import C kivy.utils.get_color_from_hex
#:import sys sys
#:import MapSource mapview.MapSource

BoxLayout:
    canvas:
        Color:
            rgb: C('#ffffff')
        Rectangle:
            pos: self.pos
            size: self.size
    orientation: 'vertical'
    BoxLayout:
        orientation: 'vertical'
        MapView:
            lat: app.on_location(self.lat)
            lon: app.on_location(self.long)
            zoom: 13
            map_source: MapSource(sys.argv[1], attribution="") if len(sys.argv) > 1 else "osm"
            MapMarkerPopup:
                lat: app.on_location(self.lat)
                lon: app.on_location(self.long)
                popup_size: dp(230), dp(130)
                Bubble:
                    BoxLayout:
                        orientation: "horizontal"
                        padding: "5dp"
                        Label:
                            text: "[b]Você está aqui![/b]"
                            markup: True
                            halign: "center"
    BoxLayout:
        assunto: assunto
        orientation: 'vertical'
        padding: [30, 30, 30, 100]
        spacing: 10
        Spinner:
            id: assunto
            text: 'Selecionar Assunto'
            background_color: C('#1180c4')
            background_normal: ''
            values: ('Buraco e Pavimentação', 'Calçadas guias e Postes', 'Ciclovias, Faixas e outros', 'Semáforos, sinalização e outros.', 'Iluminação Pública')
            size_hint_y: None
            height: '40dp'

        BoxLayout:
            orientation: 'horizontal'
            height: '40dp'
            size_hint_y: None
            ToggleButton:
                text: 'Ler Localizacao' if self.state == 'normal' else 'Parar Leitura'
                on_state:
                    app.start(1000, 0) if self.state == 'down' else \
                    app.stop()
            Button:
                text: 'Salvar'
                on_press: app.salvarLocalizacao()
'''

class GpsTest(App):
    gps_get = StringProperty()
    gps_location = StringProperty()
    gps_status = StringProperty()
    detail_text = StringProperty()

    def build(self):
        try:
            gps.configure(on_location=self.on_location,
                          on_status=self.on_status)

        except NotImplementedError:
            import traceback
            traceback.print_exc()
            self.gps_status = 'Por favor, ative o GPS'
        return Builder.load_string(kv)

    def start(self, minTime, minDistance):
        gps.start(minTime, minDistance)

    def stop(self):
        gps.stop()

    @mainthread
    def on_location(self, **kwargs):
        self.lat = kwargs.get('lat')
        self.long = kwargs.get('lon')

    @mainthread
    def on_status(self, stype, status):
        self.gps_status = 'type={}\n{}'.format(stype, status)

    def on_pause(self):
        gps.stop()
        return True

    def on_resume(self):
        gps.start(1000, 0)
        pass

    def salvarLocalizacao(self):

        if self.root.ids.assunto.text == "Buraco e Pavimentação":
            self.assunto = "pavimentacao"
        elif self.root.ids.assunto.text == "Calçadas guias e Postes":
            self.assunto = "calcadasguias"
        elif self.root.ids.assunto.text == "Ciclovias, Faixas e outros":
            self.assunto = "cicliovia"
        elif self.root.ids.assunto.text == "Semáforos, sinalização e outros.":
            self.assunto = "semaforos"
        else:
            self.assunto = "iluminacao"

        self.localizacao = "POINT(" + self.gps_location + ")"
        self.params = json.dumps({"assunto": self.assunto, "localizacao": self.localizacao})
        self.headers = {'Content-type': 'application/json',
                        'Accept': 'application/json; charset=UTF-8',
                        'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'}
        self.req = UrlRequest('http://aaa.aaa.com:9000/api/add/', req_body=self.params, req_headers=self.headers, on_success=self.postSucess, on_error=self.postFail)

    def postSucess(self, req, result):
        text = Label(text="Enviado com sucesso!".format())
        pop_up = Popup(title="Sucesso", content=text, size_hint=(.7, .7))
        pop_up.open()

    def postFail(self, req, result):
        text = Label(text="Erro de conexão, verifique sua internet!".format())
        pop_up = Popup(title="Erro de conexão", content=text, size_hint=(.7, .7))
        pop_up.open()

if __name__ == '__main__':
    GpsTest().run()
</code>```

答:
i really hate coding answers here, follow this working code
i just added some variables in the app class and that of the on_location function and changed the values in the Mapview to that of the variables created in the app class. hope it works</p>

ContentLicense: CC BY-SA 3.0

Title: Get location for Kivy Garden MapView

Body:
I need get current location in GPS and pass for mapview.
My code not working, return error:
Code working, if in kv langue in MapView add lat: and lon: numeric value.
Any ideas for get values lat and lon from function on_locations ?

ValueError: None is not allowed for MapView.lat

Code:

#-*- coding: utf-8 -*-
from kivy.lang import Builder
from plyer import gps
from kivy.app import App
from kivy.properties import StringProperty
from kivy.clock import Clock, mainthread
from kivy.uix.popup import Popup
from kivy.network.urlrequest import UrlRequest
from kivy.uix.label import Label
import json
import kivy.garden.mapview

kv = '''
#:import C kivy.utils.get_color_from_hex
#:import sys sys
#:import MapSource mapview.MapSource

BoxLayout:
    canvas:
        Color:
            rgb: C('#ffffff')
        Rectangle:
            pos: self.pos
            size: self.size
    orientation: 'vertical'
    BoxLayout:
        orientation: 'vertical'
        MapView:
            lat: app.on_location(self.lat)
            lon: app.on_location(self.long)
            zoom: 13
            map_source: MapSource(sys.argv[1], attribution="") if len(sys.argv) > 1 else "osm"
            MapMarkerPopup:
                lat: app.on_location(self.lat)
                lon: app.on_location(self.long)
                popup_size: dp(230), dp(130)
                Bubble:
                    BoxLayout:
                        orientation: "horizontal"
                        padding: "5dp"
                        Label:
                            text: "[b]Você está aqui![/b]"
                            markup: True
                            halign: "center"
    BoxLayout:
        assunto: assunto
        orientation: 'vertical'
        padding: [30, 30, 30, 100]
        spacing: 10
        Spinner:
            id: assunto
            text: 'Selecionar Assunto'
            background_color: C('#1180c4')
            background_normal: ''
            values: ('Buraco e Pavimentação', 'Calçadas guias e Postes', 'Ciclovias, Faixas e outros', 'Semáforos, sinalização e outros.', 'Iluminação Pública')
            size_hint_y: None
            height: '40dp'

        BoxLayout:
            orientation: 'horizontal'
            height: '40dp'
            size_hint_y: None
            ToggleButton:
                text: 'Ler Localizacao' if self.state == 'normal' else 'Parar Leitura'
                on_state:
                    app.start(1000, 0) if self.state == 'down' else \
                    app.stop()
            Button:
                text: 'Salvar'
                on_press: app.salvarLocalizacao()
'''

class GpsTest(App):
    gps_get = StringProperty()
    gps_location = StringProperty()
    gps_status = StringProperty()
    detail_text = StringProperty()

    def build(self):
        try:
            gps.configure(on_location=self.on_location,
                          on_status=self.on_status)

        except NotImplementedError:
            import traceback
            traceback.print_exc()
            self.gps_status = 'Por favor, ative o GPS'
        return Builder.load_string(kv)

    def start(self, minTime, minDistance):
        gps.start(minTime, minDistance)

    def stop(self):
        gps.stop()

    @mainthread
    def on_location(self, **kwargs):
        self.lat = kwargs.get('lat')
        self.long = kwargs.get('lon')

    @mainthread
    def on_status(self, stype, status):
        self.gps_status = 'type={}\n{}'.format(stype, status)

    def on_pause(self):
        gps.stop()
        return True

    def on_resume(self):
        gps.start(1000, 0)
        pass

    def salvarLocalizacao(self):

        if self.root.ids.assunto.text == "Buraco e Pavimentação":
            self.assunto = "pavimentacao"
        elif self.root.ids.assunto.text == "Calçadas guias e Postes":
            self.assunto = "calcadasguias"
        elif self.root.ids.assunto.text == "Ciclovias, Faixas e outros":
            self.assunto = "cicliovia"
        elif self.root.ids.assunto.text == "Semáforos, sinalização e outros.":
            self.assunto = "semaforos"
        else:
            self.assunto = "iluminacao"

        self.localizacao = "POINT(" + self.gps_location + ")"
        self.params = json.dumps({"assunto": self.assunto, "localizacao": self.localizacao})
        self.headers = {'Content-type': 'application/json',
                        'Accept': 'application/json; charset=UTF-8',
                        'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'}
        self.req = UrlRequest('http://aaa.aaa.com:9000/api/add/', req_body=self.params, req_headers=self.headers, on_success=self.postSucess, on_error=self.postFail)

    def postSucess(self, req, result):
        text = Label(text="Enviado com sucesso!".format())
        pop_up = Popup(title="Sucesso", content=text, size_hint=(.7, .7))
        pop_up.open()

    def postFail(self, req, result):
        text = Label(text="Erro de conexão, verifique sua internet!".format())
        pop_up = Popup(title="Erro de conexão", content=text, size_hint=(.7, .7))
        pop_up.open()

if __name__ == '__main__':
    GpsTest().run()


问:
How to access the docker VM (MobyLinux) filesystem from windows shell?
Is there away to log into host VM's shell, similarly to how can we easily enter into running containers bash?

docker exec -it  bash

I accidentally broke one container's crucial file, so that it couldn't start. Unfortunately, that container stored it's data inside. The result was that whenever I tried to run it, it couldn't start. The only solutions I saw were about navigating to host docker daemon's files. However, I'm running docker VM on windows, and I cannot access the files inside VM (MobyLinuxVM).

I'm using Docker for Windows, version 1.12.3-beta30.1 (8711)

答:
Hack your way in

run a container with full root access to MobyLinuxVM and no seccomp profile (so you can mount stuff)

```<code>docker run --net=host --ipc=host --uts=host --pid=host -it --security-opt=seccomp=unconfined --privileged --rm -v /:/host alpine /bin/sh
</code>```

https://forums.docker.com/t/how-can-i-ssh-into-the-betas-mobylinuxvm/10991/6

Body:
Hack your way in

run a container with full root access to MobyLinuxVM and no seccomp profile (so you can mount stuff)

docker run --net=host --ipc=host --uts=host --pid=host -it --security-opt=seccomp=unconfined --privileged --rm -v /:/host alpine /bin/sh

https://forums.docker.com/t/how-can-i-ssh-into-the-betas-mobylinuxvm/10991/6


问:
.Net pass a list of objects to JQuery as parameter
Hi I tried to pass a list of self-defined objects to JQuery as parameter and expect jQuery recognise it as the specific object and loop through it.
The class is:

```<code>public class PriceSummary{
        public string ItemName { get; set; }
        public string ItemPrice { get; set; } }
</code>```

The backend method is:

```<code>public void updatePriceSummary(List<PriceSummary> PriceSummaryList){
        ScriptManager.RegisterStartupScript(Page, GetType(), "changePriceList",
           "updatePriceList('" + PriceSummaryList + "');", true);}
</code>```

JQuery Method

```<code>function updatePriceList(PriceSummaryList) {
    PriceSummaryList.each(function ()
      {$('#ControlSummaryTitle').append('<tr id = "xxx"> <td class="SummaryItem">' +
      this['ItemName'] + '</td> <td class="SummaryPrice">' + this['ItemPrice'] +
      '</td></tr>');   })
;}
</code>```

However, the JQuery function couldn't recognise the parameter as a list and couldn't loop through it. The error message is:

0x800a01b6 - JavaScript runtime error: Object doesn't support property
  or method 'each'

Could anybody advise how to fix it?

答:
Problem 1: if you're just composing a List<> into a string it will get turned into a string by the simplest method .Net knows, which is .ToString(), resulting in "System.Collections.Generic.List`1[someclass]". You need to transform it into something that Javascript understands, let's say by serializing it into JSON. You can easily inspect the value in the browser to see if you're getting closer to something that works.

Problem 2: you're surrounding the value with single quotes (updatePriceList('...')) so it would still be interpreted as a string; remove the single quotes.

Body:
Hi I tried to pass a list of self-defined objects to JQuery as parameter and expect jQuery recognise it as the specific object and loop through it.
The class is:

public class PriceSummary{
        public string ItemName { get; set; }
        public string ItemPrice { get; set; } }

The backend method is:

public void updatePriceSummary(List<PriceSummary> PriceSummaryList){
        ScriptManager.RegisterStartupScript(Page, GetType(), "changePriceList",
           "updatePriceList('" + PriceSummaryList + "');", true);}

JQuery Method

function updatePriceList(PriceSummaryList) {
    PriceSummaryList.each(function ()
      {$('#ControlSummaryTitle').append('
 ' +
      this['ItemName'] + '	 ' + this['ItemPrice'] +
      '
');   })
;}

However, the JQuery function couldn't recognise the parameter as a list and couldn't loop through it. The error message is:

0x800a01b6 - JavaScript runtime error: Object doesn't support property
  or method 'each'

Could anybody advise how to fix it?


问:
IOS/Objective-C: NSArray randomization issue
I have this array with strings and I want to randomize it and display the output in a label. But with this code I'm having always the same strange output which is "2"...Any ideas what I'm doing wrong?

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    self.quoteInput.delegate=self;
    self.quoteLabel=_quotationLabel;
    self.correctLabel.alpha=0;
    self.wrongLabel.alpha=0;

    _quoteInput.delegate=self;

   _levelOne = @[
                   [words Quotes:@"First Quote."],
                   [words Quotes:@"Second Quote."],
                 [words Quotes:@"And so on."]];

}

-(void)randomQuotes{

    for (NSInteger x = 0; x < [_levelOne count]; x++) {

        NSInteger randInt = arc4random() % ([_levelOne count] - x) + x;
        [_levelOne objectAtIndex:randInt];

        NSString *one = [NSString stringWithFormat:@"%d", randInt];
        self.quoteLabel.text = one;
    }
}
- (IBAction)generateQuote:(UIButton *)sender {
    [self randomQuotes];
}
</code>```

EDIT
The words class:

```<code> + (instancetype)Quotes:(NSString *)quotes
                       {

return [[words alloc] initWithQuotes:quotes];
}
</code>```

答:
Unless you can explain what [word Quotes:] method does, it should be much simpler than what you are trying to do.

```<code>_levelOne = @[@"First Quote.", "Second Quote.", @"And so on."];

-(void) randomQuotes{
    NSInteger randInt = arc4random_uniform( [_levelOne count] );
    self.quoteLabel.text = [_levelOne objectAtIndex:randInt];
}
</code>```

Body:
I have this array with strings and I want to randomize it and display the output in a label. But with this code I'm having always the same strange output which is "2"...Any ideas what I'm doing wrong?

- (void)viewDidLoad {
    [super viewDidLoad];
    self.quoteInput.delegate=self;
    self.quoteLabel=_quotationLabel;
    self.correctLabel.alpha=0;
    self.wrongLabel.alpha=0;

    _quoteInput.delegate=self;

   _levelOne = @[
                   [words Quotes:@"First Quote."],
                   [words Quotes:@"Second Quote."],
                 [words Quotes:@"And so on."]];

}

-(void)randomQuotes{

    for (NSInteger x = 0; x < [_levelOne count]; x++) {

        NSInteger randInt = arc4random() % ([_levelOne count] - x) + x;
        [_levelOne objectAtIndex:randInt];

        NSString *one = [NSString stringWithFormat:@"%d", randInt];
        self.quoteLabel.text = one;
    }
}
- (IBAction)generateQuote:(UIButton *)sender {
    [self randomQuotes];
}

EDIT
The words class:

 + (instancetype)Quotes:(NSString *)quotes
                       {

return [[words alloc] initWithQuotes:quotes];
}

Body:
Unless you can explain what [word Quotes:] method does, it should be much simpler than what you are trying to do.

_levelOne = @[@"First Quote.", "Second Quote.", @"And so on."];

-(void) randomQuotes{
    NSInteger randInt = arc4random_uniform( [_levelOne count] );
    self.quoteLabel.text = [_levelOne objectAtIndex:randInt];
}


问:
ArtifactTransferException in Eclipse project when importing the Examples
I'm trying to run some of the Netty example projects. After importing the Maven project, Eclipse reports the following problem:

```<code>ArtifactTransferException: Could not transfer artifact io.netty:netty-tcnative:jar:${os.detected.classifier}:1.1.33.Fork2 from/to central (http://repo1.maven.org/maven2): Illegal character in path at index 96: http://repo1.maven.org/maven2/io/netty/netty-tcnative/1.1.33.Fork2/netty-tcnative-1.1.33.Fork2-${os.detected.classifier}.jar
</code>```

Things I've tried after researching related questions:

Deleting the lastupdated files (seems to be a common cause of ArtifactTransferExceptions)

Manually adding the os-maven-plugin to the eclipse plugins folder as described here

Cleaning the project

Deleting the eclipse project and re-importing

What should I try next (or am I even going down the right path for running the Netty examples)?

答:
I got the same issue. It was solved by adding:

```<code><extensions>
    <extension>
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>1.4.0.Final</version>
    </extension>
</extensions>
</code>```

inside the  tag. Questions see here: https://github.com/trustin/os-maven-plugin

Body:
I'm trying to run some of the Netty example projects. After importing the Maven project, Eclipse reports the following problem:

ArtifactTransferException: Could not transfer artifact io.netty:netty-tcnative:jar:${os.detected.classifier}:1.1.33.Fork2 from/to central (http://repo1.maven.org/maven2): Illegal character in path at index 96: http://repo1.maven.org/maven2/io/netty/netty-tcnative/1.1.33.Fork2/netty-tcnative-1.1.33.Fork2-${os.detected.classifier}.jar

Things I've tried after researching related questions:

Deleting the lastupdated files (seems to be a common cause of ArtifactTransferExceptions)

Manually adding the os-maven-plugin to the eclipse plugins folder as described here

Cleaning the project

Deleting the eclipse project and re-importing

What should I try next (or am I even going down the right path for running the Netty examples)?

Body:
I got the same issue. It was solved by adding:

<extensions>
    <extension>
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>1.4.0.Final</version>
    </extension>
</extensions>

inside the  tag. Questions see here: https://github.com/trustin/os-maven-plugin


问:
Windows service installing in Windows server 2012
I'm facing a strange problem after installing the Windows service.

This Windows service will call a method to send mail every 5 minutes.

I have developed the windows service using C# visual Studio 2010.

After the development I have taken the release build version and Installed in my system (that is windows 7 OS) and it works without any problem.

Once the same thing is done in the Windows server 2012 then the service will be installed but the nothing happens there after.

I have used System.Threading.Timer at present. Even I tried using System.Timers.Timer.
Both of these will work in my system but wont work in the Server.

I can post the code if required.

```<code>private Timer IntervalTimer;
protected override void OnStart(string[] args)
{
        Server.WriteToLogFile("Windows Service started");
        int loopTime = 5; //Every 5 Minutes
        Server.WriteToLogFile("Loop Time : " + loopTime.ToString());

        TimeSpan tsInterval = new TimeSpan(0, loopTime, 0);
        IntervalTimer = new Timer(new TimerCallback(IntervalTimer_Elapsed), null, tsInterval, tsInterval);
 }
private void IntervalTimer_Elapsed(object state)
{
     Server.WriteToLogFile("Event Fired");
     Library library = new Library();
     library.Start();
}
</code>```

答:
In my case I have to delete the old windows service using command prompt in admin mode using:

```<code>SC DELETE <service name>
</code>```

then rebuild the application as mentioned by > >Nuthan Gowda and it worked .

Body:
I'm facing a strange problem after installing the Windows service.

This Windows service will call a method to send mail every 5 minutes.

I have developed the windows service using C# visual Studio 2010.

After the development I have taken the release build version and Installed in my system (that is windows 7 OS) and it works without any problem.

Once the same thing is done in the Windows server 2012 then the service will be installed but the nothing happens there after.

I have used System.Threading.Timer at present. Even I tried using System.Timers.Timer.
Both of these will work in my system but wont work in the Server.

I can post the code if required.

private Timer IntervalTimer;
protected override void OnStart(string[] args)
{
        Server.WriteToLogFile("Windows Service started");
        int loopTime = 5; //Every 5 Minutes
        Server.WriteToLogFile("Loop Time : " + loopTime.ToString());

        TimeSpan tsInterval = new TimeSpan(0, loopTime, 0);
        IntervalTimer = new Timer(new TimerCallback(IntervalTimer_Elapsed), null, tsInterval, tsInterval);
 }
private void IntervalTimer_Elapsed(object state)
{
     Server.WriteToLogFile("Event Fired");
     Library library = new Library();
     library.Start();
}

Body:
In my case I have to delete the old windows service using command prompt in admin mode using:

SC DELETE <service name>

then rebuild the application as mentioned by > >Nuthan Gowda and it worked .


问:
Bit Shift Operator '<<' creates Extra 0xffff?
I am currently stuck with this simple bit-shifting problem. The problem is that when I assign a short variable any values, and shift them with << 8, I get 0xffff(2 extra bytes) when I save the result to the 'short' variables. However, for 'long', it is OK. So I am wondering why this would anyhow happen ??

I mean, short isn't supposed to read more than 2 bytes but... it clearly shows that my short values are containing Extra 2 bytes with the value 0xffff.

I'm seeking for your wisdom.. :)

This image describes the problem. Clearly, when the 'sign' bit(15) of 'short' is set to 1 AFTER the bit shift operation, the whole 2 byte ahead turns into 0xffff. This is demonstrated by showing 127(0x7f) passing the test but 0x81 NOT passing the test because when it is shifted, Due to it's upper 8. That causes to set Bit15(sign bit) to '1'. Also, Because 257(0x101) doesn't set the bit 15 after shifting, it turns out to be OK.

答:
There are several problems with your code.

First, you are doing bit shift operations with signed variables, this may have unexpected results. Use unsigned short instead of short to do bit shifting, unless you are sure of what you are doing.

You are explicitly casting a short to unsigned short and then storing the result back to a variable of type short. Not sure what you are expecting to happen here, this is pointless and will prevent nothing.

The issue is related to that. 129 << 8 is 33024, a value too big to fit in a signed short. You are accidently lighting the sign bit, causing the number to become negative. You would see that if you printed it as %d instead of %x.

Because short is implicitly promoted to int when passed as parameter to printf(), you see the 32-bit version of this negative number, which has its 16 most relevant bits lit in accordance. This is where the leading ffff come from.

You don't have this problem with long because even though its signed long its still large enough to store 33024 without overloading the sign bit.


问:
Ruby-on-Rails: Devise custom failure app problem
I am trying to set up Devise to return 401 to unauthorized API requests instead of redirects but I'm running into a boulder. This is how I am overriding it's custom failure behavior:

```<code>class CustomFailure < Devise::FailureApp
    include ActionController::Head
    include ActionController::MimeResponds

    def respond
        respond_to do |format|
            format.html {
                super
            }
            format.any { head :status => 401}
        end
    end
end
</code>```

However, I am getting this error:

```<code>undefined local variable or method `lookup_context' for #<CustomFailure:0x000001031f6220>
</code>```

and it points to the respond_to do |format| line

What am I doing wrong?

答:
```<code>def respond
  unless request.format.to_sym == :html
    http_auth
  else
    super
  end
end
</code>```

Devise::FailureApp is inherited form ActionController::Metal which is interacting with Rack on low level, so there is no respond_to view related stuff

ContentLicense: CC BY-SA 2.5

Body:
I am trying to set up Devise to return 401 to unauthorized API requests instead of redirects but I'm running into a boulder. This is how I am overriding it's custom failure behavior:

class CustomFailure < Devise::FailureApp
    include ActionController::Head
    include ActionController::MimeResponds

    def respond
        respond_to do |format|
            format.html {
                super
            }
            format.any { head :status => 401}
        end
    end
end

However, I am getting this error:

undefined local variable or method `lookup_context' for #<CustomFailure:0x000001031f6220>

and it points to the respond_to do |format| line

What am I doing wrong?

Body:
def respond
  unless request.format.to_sym == :html
    http_auth
  else
    super
  end
end

Devise::FailureApp is inherited form ActionController::Metal which is interacting with Rack on low level, so there is no respond_to view related stuff


问:
Wrap many rails attributes with custom functionality
I have a number of models that have attributes on them that I need to apply some new behavior to when they are read. I'm fairly new to Ruby/Rails so right now I'm just defining a getter for a property and applying my functionality on top of it (similar to something like profanity filtering), but I'm going to be doing this for a lot of objects/properties and would like something cleaner.

For example, this is how I'm accomplishing it now, for a Post object's body attribute:

```<code>class Post < ActiveRecord::Base
    include Replaceable

    #...

    # A key point is that we want to keep the original content in the db
    def body
        profanity_filter(self[:body])
    end
end
</code>```

... and my concern looks like this:

```<code>module Replaceable
    extend ActiveSupport::Concern

    def profanity_filter(content)
        # filter and update content...

        content
    end
end
</code>```

This works and I'm happy with it, except that now I have to apply it to many fields across the app, and I'd like something a bit more elegant than overriding getters everywhere.

I looked into delegates so that I could do something like

```<code>delegate :body, :title, :etc, :to => :profanity_filter
</code>```

... but that doesn't work because I can't pass the content that needs to be filtered.

Any help would be appreciated!

答:
This is the perfect time to implement your own class macro.

I'll reuse your Replaceable module do define this macro.

First, let's see what the macro look like.

```<code>class Post < ActiveRecord::Base
  include Replaceable

  profanity_attrs :body, :foo, :bar, ...
end
</code>```

Then we implement it

```<code>module Replaceable
  extend ActiveSupport::Concern

  def profanity_filter(content)
    # filter and update content...

    content
  end

  # This module will be `extend`ed by the model classes
  module Macro
    def profanity_attrs(attributes)
      # Note the implicit `self` here refer to the model class
      attributes.each do |attr|
        class_eval do
          define_method(attr) do
            # Note the `self` here refer to the model instance
            profanity_filter(self[attr])
          end
        end
      end
    end
  end

  included do
    extend Macro
  end
end
</code>```

P.S. I don't really know what profanity means, so feel free to change the name of the macro :)

Body:
I have a number of models that have attributes on them that I need to apply some new behavior to when they are read. I'm fairly new to Ruby/Rails so right now I'm just defining a getter for a property and applying my functionality on top of it (similar to something like profanity filtering), but I'm going to be doing this for a lot of objects/properties and would like something cleaner.

For example, this is how I'm accomplishing it now, for a Post object's body attribute:

class Post < ActiveRecord::Base
    include Replaceable

    #...

    # A key point is that we want to keep the original content in the db
    def body
        profanity_filter(self[:body])
    end
end

... and my concern looks like this:

module Replaceable
    extend ActiveSupport::Concern

    def profanity_filter(content)
        # filter and update content...

        content
    end
end

This works and I'm happy with it, except that now I have to apply it to many fields across the app, and I'd like something a bit more elegant than overriding getters everywhere.

I looked into delegates so that I could do something like

delegate :body, :title, :etc, :to => :profanity_filter

... but that doesn't work because I can't pass the content that needs to be filtered.

Any help would be appreciated!

Body:
This is the perfect time to implement your own class macro.

I'll reuse your Replaceable module do define this macro.

First, let's see what the macro look like.

class Post < ActiveRecord::Base
  include Replaceable

  profanity_attrs :body, :foo, :bar, ...
end

Then we implement it

module Replaceable
  extend ActiveSupport::Concern

  def profanity_filter(content)
    # filter and update content...

    content
  end

  # This module will be `extend`ed by the model classes
  module Macro
    def profanity_attrs(attributes)
      # Note the implicit `self` here refer to the model class
      attributes.each do |attr|
        class_eval do
          define_method(attr) do
            # Note the `self` here refer to the model instance
            profanity_filter(self[attr])
          end
        end
      end
    end
  end

  included do
    extend Macro
  end
end

P.S. I don't really know what profanity means, so feel free to change the name of the macro :)


问:
Emitting values from ktable and modifying it
I'm trying to solve the following problem with kafka.
There is a topic. let's call it src-topic. I receive records from this topic from time to time. I would like to store those values in a ktable and emit the values stored in the ktable every 10 seconds to dst-topic. When I emit a value from this ktable for the first time then I want to append 1 to the record I emit. Every subsequent time I would like to append 0 to the emitted record.

I'm looking for a correct and preferably idiomatic solution to this issue.
One of the solutions I see is to emit a record with 1 appended when I ingest from src-topic and then store in the ktable the record with 0 appended. Another thread will be reading from this ktable and emitting the records regularly. The problem with this approach is that it has a race condition.

Any advice will be appreciated.

答:
There is no straight forward way to do this. Note, a KTable is a changelog stream (it might have a table state internally -- not all KTables do have a state --, but that's an implementation detail).

Thus, a KTable is a stream and you cannot flush a stream... And because the state (if there is any) is internal, you cannot flush the state either.

You can only access the state via Interactive Queries that also allow to do a range scan. However, this will not emit anything downstream but gives the data to the "non Streams part" of you application.

I think, you will need to use low-level Processor API to get the result you want.


问:
How to get value based on input of text field
Basically, I m trying to create a money converter with web services and with this code, it gives me a value of 1 figure for example if I select From GB to USD then it will calculate as 1 GB = 1 USD. But what I want is that I want to put a value on text box somehow which then should be converted e.g. if I insert a value 20 and select from GB to USD then should give me the result of 20 GB = anything USD.
Please help me solve this problem and help is appreciated. </p>

```<code>currencyconv.CurrencyConvertor cc = new currencyconv.CurrencyConvertor();

currencyconv.Currency currenFrom =
    (currencyconv.Currency)Enum.Parse(typeof(currencyconv.Currency),
    dd1From.SelectedValue);

currencyconv.Currency currencyTo =
    (currencyconv.Currency)Enum.Parse(typeof(currencyconv.Currency),
    dd1To.SelectedValue);

double iRate = cc.ConversionRate(currenFrom, currencyTo);

lblConversion.Text = string.Format("1 {0} = {1} {2}", currenFrom, iRate, currencyTo);
</code>```

答:
Based on what you've posted, you should add a TextBox to your form called something like txtQuantity, which only allows numeric input. Then you would do something like:

```<code>double quantity = double.Parse(txtQuantity.Text);

lblConversion.Text = string.Format("{0} {1} = {2} {3}",
    quantity, currenFrom, iRate * quantity, currencyTo);
</code>```

Body:
Basically, I m trying to create a money converter with web services and with this code, it gives me a value of 1 figure for example if I select From GB to USD then it will calculate as 1 GB = 1 USD. But what I want is that I want to put a value on text box somehow which then should be converted e.g. if I insert a value 20 and select from GB to USD then should give me the result of 20 GB = anything USD.
Please help me solve this problem and help is appreciated.

currencyconv.CurrencyConvertor cc = new currencyconv.CurrencyConvertor();

currencyconv.Currency currenFrom =
    (currencyconv.Currency)Enum.Parse(typeof(currencyconv.Currency),
    dd1From.SelectedValue);

currencyconv.Currency currencyTo =
    (currencyconv.Currency)Enum.Parse(typeof(currencyconv.Currency),
    dd1To.SelectedValue);

double iRate = cc.ConversionRate(currenFrom, currencyTo);

lblConversion.Text = string.Format("1 {0} = {1} {2}", currenFrom, iRate, currencyTo);

Body:
Based on what you've posted, you should add a TextBox to your form called something like txtQuantity, which only allows numeric input. Then you would do something like:

double quantity = double.Parse(txtQuantity.Text);

lblConversion.Text = string.Format("{0} {1} = {2} {3}",
    quantity, currenFrom, iRate * quantity, currencyTo);


问:
How to converte Long-->byteArray->String-->byteArray-->Long over socket?
I want to send messages over socket that contain long values. I want to send string messages. To save bytes and make messages shorter, I want to send the byte value of a 64 bit long in 8-character string. Following is my code, but I received wrong value on the other side of the socket:

This the server:

```<code>public class ClockSkewServer {
public static void main (String args[]){
    try {
        ServerSocket s = new ServerSocket(3000);
        System.out.println("Server is listening!");
        Socket connection = s.accept();
        connection.setKeepAlive(true);
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        PrintWriter pw = new PrintWriter(connection.getOutputStream(), true);
        while (true) {

            String message = br.readLine();
            System.out.println(message);
            Long receivedTime = ByteUtil.stringToLong(message);
            System.out.println(receivedTime);

        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
    }
</code>```

And this is the client:

```<code>public class ClockSkewClient {
public static void main (String args[]) throws UnknownHostException, IOException, InterruptedException{
    Socket s1 = new Socket(args[0], 3000);
    s1.setKeepAlive(true);
    PrintWriter out1 = new PrintWriter(s1.getOutputStream(), true);
    long l = new Long("1490917469228");
    //System.out.println(l);
    while (true){
        Thread.sleep(1000);
        String message  = ByteUtil.longToString(l);
        System.out.println("Client message: " + message);
        System.out.println(ByteUtil.stringToLong(message));
        out1.println(message);
    }

}
}
</code>```

And this my byte conversion class:

```<code>public class ByteUtil {
    private static ByteBuffer longBuffer = ByteBuffer.allocate(Long.BYTES);
    private static ByteBuffer shortBuffer = ByteBuffer.allocate(Short.BYTES);
    private static ByteBuffer byteBuffer = ByteBuffer.allocate(Byte.BYTES);

    public static byte[] longToBytes(long x) {
        longBuffer.putLong(0, x);
        return longBuffer.array();
    }

    public static long bytesToLong(byte[] bytes) {
        return ByteBuffer.wrap(bytes).getLong();
    }

    public static String longToString (long x) throws UnsupportedEncodingException{
        return new String (longToBytes(x), "ISO-8859-1");
    }

    public static long stringToLong (String s) throws UnsupportedEncodingException{
        return bytesToLong(s.getBytes("ISO-8859-1"));
    }

}
</code>```

ByteUtil is working fine, as the client can retrieve the original long value correctly, but when I send over socket it get distorted.

I successfully get the long value in the client side as 1490917469228, but on the server side I get 1490911439916.

I know we can send bytes and avoid this problem, but for some reason I insist to send String over socket.

Thanks

答:
I want to send messages over socket that contain long values. I want to send string messages. To save bytes and make messages shorter, I want to send the byte value of a 64 bit long in 8-character string.

Why? Sending 64 bits as 8 chars could take 16 bytes. 128 bits. It certainly doesn't save any bytes whatsoever, and all these conversions just waste time and code space: especially development time, especially as your code doesn't work.

Just use DataOutputStream.writeLong() and DataInputStream.readLong().

Body:
I want to send messages over socket that contain long values. I want to send string messages. To save bytes and make messages shorter, I want to send the byte value of a 64 bit long in 8-character string. Following is my code, but I received wrong value on the other side of the socket:

This the server:

public class ClockSkewServer {
public static void main (String args[]){
    try {
        ServerSocket s = new ServerSocket(3000);
        System.out.println("Server is listening!");
        Socket connection = s.accept();
        connection.setKeepAlive(true);
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        PrintWriter pw = new PrintWriter(connection.getOutputStream(), true);
        while (true) {

            String message = br.readLine();
            System.out.println(message);
            Long receivedTime = ByteUtil.stringToLong(message);
            System.out.println(receivedTime);

        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
    }

And this is the client:

public class ClockSkewClient {
public static void main (String args[]) throws UnknownHostException, IOException, InterruptedException{
    Socket s1 = new Socket(args[0], 3000);
    s1.setKeepAlive(true);
    PrintWriter out1 = new PrintWriter(s1.getOutputStream(), true);
    long l = new Long("1490917469228");
    //System.out.println(l);
    while (true){
        Thread.sleep(1000);
        String message  = ByteUtil.longToString(l);
        System.out.println("Client message: " + message);
        System.out.println(ByteUtil.stringToLong(message));
        out1.println(message);
    }

}
}

And this my byte conversion class:

public class ByteUtil {
    private static ByteBuffer longBuffer = ByteBuffer.allocate(Long.BYTES);
    private static ByteBuffer shortBuffer = ByteBuffer.allocate(Short.BYTES);
    private static ByteBuffer byteBuffer = ByteBuffer.allocate(Byte.BYTES);

    public static byte[] longToBytes(long x) {
        longBuffer.putLong(0, x);
        return longBuffer.array();
    }

    public static long bytesToLong(byte[] bytes) {
        return ByteBuffer.wrap(bytes).getLong();
    }

    public static String longToString (long x) throws UnsupportedEncodingException{
        return new String (longToBytes(x), "ISO-8859-1");
    }

    public static long stringToLong (String s) throws UnsupportedEncodingException{
        return bytesToLong(s.getBytes("ISO-8859-1"));
    }

}

ByteUtil is working fine, as the client can retrieve the original long value correctly, but when I send over socket it get distorted.

I successfully get the long value in the client side as 1490917469228, but on the server side I get 1490911439916.

I know we can send bytes and avoid this problem, but for some reason I insist to send String over socket.

Thanks


问:
Close ports 1443
When I run netstat -a I see port 1443 as status Listening. I create a rule in the windows firewall to close ports and re-run netstat but I'm still seeing the ports in Listening status. What do I need to do to close these ports?

答:
Windows Firewall does not stop processes from listening on a port - instead it blocks outbound connections from attempting to connect to that port. Windows Firewall does not block localhost connections by default.

Also, for SQL Server itself, you should use the "SQL Server Configuration Manager" tool to change SQL Server's port bindings and to disable/enable specific interfaces (including TCP entirely if you want to use the Shared Memory or Named Pipes transports instead).

Title: Close ports 1443


问:
How can I test a mobile website for an Android device, if I'm using a mac?
I'm creating a website and I've been testing in different browsers, but not android devices, because I don't normally have access. Someone looked at the site on an Android phone (using the default web browser and chrome) and one of the pages is not displaying correctly.   My index page is just a full screen image, but on the Android device, the image is pushed up and the bottom half of the screen is white.  I can't figure out why this would be different on an Android phone. How can I test my site to see how it would react on an Android phone? </p>

答:
Download Android Studio and use the emulator
Or Genymotion is another emulator you could use. I have not used it myself, but it is probably the most popular emulator out side of the official one in android studio.</p>


问:
Strategy Pattern the right thing?
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

```<code>switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}
</code>```

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

```<code>abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}
</code>```

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static

答:
You should program to an interface not an implementation.

Have a separate service interface which you can use from your client side.

```<code>public interface IService
{
    string[] GetData();
}
</code>```

and code your client as -

```<code>IService srvice = ServiceFactory.GetProxy();
string[] value = service.GetData();
</code>```

This way your client code will not change when the service proxy changes.

Then you to start with you can move the conditional logic for creating the appropriate proxy to the ServiceFactory class. Later on you can change it to remove conditional logic using following techniques like -

Reading the implementation class and assembly name from the configuration file and creating it using reflection.

Creating a dictionary of proxy instances with soap version as keys.

Title: Strategy Pattern the right thing?

Body:
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static

Body:
You should program to an interface not an implementation.

Have a separate service interface which you can use from your client side.

public interface IService
{
    string[] GetData();
}

and code your client as -

IService srvice = ServiceFactory.GetProxy();
string[] value = service.GetData();

This way your client code will not change when the service proxy changes.

Then you to start with you can move the conditional logic for creating the appropriate proxy to the ServiceFactory class. Later on you can change it to remove conditional logic using following techniques like -

Reading the implementation class and assembly name from the configuration file and creating it using reflection.

Creating a dictionary of proxy instances with soap version as keys.


问:
changing text size of SCNText
I'm trying to set the size of the font using this code:

```<code>func setupText(){
     let text = SCNText(string: "textString", extrusionDepth: 4)
        textNode.geometry = text
        textNode.position = SCNVector3Make(0, -200, 5)
        scene.rootNode.addChildNode(textNode)
        text.alignmentMode = kCAAlignmentCenter
        text.font = UIFont(name: "Helvatica", size: 30)
    }
</code>```

I'm changing the size argument but my text doesn't get any bigger or smaller. What am I doing wrong?

答: It doesn't work because the font isn't being set.  The font isn't being set because you misspelled "Helvetica" as "Helvatica".</p>

Title: changing text size of SCNText

Body:
I'm trying to set the size of the font using this code:

func setupText(){
     let text = SCNText(string: "textString", extrusionDepth: 4)
        textNode.geometry = text
        textNode.position = SCNVector3Make(0, -200, 5)
        scene.rootNode.addChildNode(textNode)
        text.alignmentMode = kCAAlignmentCenter
        text.font = UIFont(name: "Helvatica", size: 30)
    }

I'm changing the size argument but my text doesn't get any bigger or smaller. What am I doing wrong?


问:
bootstrap timepicker not showing time picker option
i am making an application and using bootstrap timepicker and its only showing current time in my input field but not showing time picker to select time picker
please help me to resolve it .
and also not showing any error .

HTML

```<code><div class="col-xs-3"> <label>Invoice #</label>
   <input class="timepicker form-control " >
</div>
</code>```

CSS

```<code><!-- Bootstrap time Picker -->
<link rel="stylesheet" href="plugins/timepicker/bootstrap-timepicker.min.css">
</code>```

JS

```<code> <!-- bootstrap time picker -->
<script src="plugins/timepicker/bootstrap-timepicker.min.js"></script>

//Timepicker
$(".timepicker").timepicker({
    showInputs: false
});
</code>```

答: I added bootstrap-timepicker class to the parent and it seems like it made it show up for me.

Body:
i am making an application and using bootstrap timepicker and its only showing current time in my input field but not showing time picker to select time picker
please help me to resolve it .
and also not showing any error .

HTML

 Invoice #
   <input class="timepicker form-control " >

CSS

<link rel="stylesheet" href="plugins/timepicker/bootstrap-timepicker.min.css">

JS

//Timepicker
$(".timepicker").timepicker({
    showInputs: false
});


问:
Rails Sort Array By Two Columns
Let's say I have an array called surveys that's made up of Survey.all

Each survey model has a length and cost columns.

What's the best way to sort an array first on length, and then on cost.

I basically want to do something similar to Survey.all.order(length: :desc, cost: :asc) but on the array after it's created.

答:
Use sort_by:

```<code>surveys.sort_by { |survey| [survey.length, survey.cost] }
</code>```

If you want to control asc vs desc, just multiply by -1:

```<code>surveys.sort_by { |survey| [-1 * survey.length, survey.cost] }
</code>```

This should work for both regular array of objects or ActiveRecord::Relation

Title: Rails Sort Array By Two Columns

Body:
Use sort_by:

surveys.sort_by { |survey| [survey.length, survey.cost] }

If you want to control asc vs desc, just multiply by -1:

surveys.sort_by { |survey| [-1 * survey.length, survey.cost] }

This should work for both regular array of objects or ActiveRecord::Relation


问:
How to go about SELECT 1 FROM
This is my query

This is another try:

Instead of selecting the MAX, is there anyway I can get hold of the Book details ???

I have tried changing to Book.* but it's erroring. Please can someone tell me how to go about doing so I can retrieve the Book information ??

What i am trying to do is to get the highest amount from one table and get the records associated to it

Thanks in advance

答:
Without knowing your schema best I can help with (based on your current query) is:</p>

```<code>SELECT bk.*, a.maxDonations
  FROM Book bk
        INNER JOIN (SELECT b.bookID, MAX(lre.donationsCollected) as maxDonations
                      FROM Book b
                            INNER JOIN MemberBorrowsBook mbb
                                    ON b.bookID = mbb.bookID
                            INNER JOIN LibraryRepairEvent lre
                                    ON mbb.memberID = lre.organiserID
                     GROUP BY b.bookID
                    ) a
               ON bk.bookID = a.bookID
</code>```

Title: How to go about SELECT 1 FROM

Body:
Without knowing your schema best I can help with (based on your current query) is:

SELECT bk.*, a.maxDonations
  FROM Book bk
        INNER JOIN (SELECT b.bookID, MAX(lre.donationsCollected) as maxDonations
                      FROM Book b
                            INNER JOIN MemberBorrowsBook mbb
                                    ON b.bookID = mbb.bookID
                            INNER JOIN LibraryRepairEvent lre
                                    ON mbb.memberID = lre.organiserID
                     GROUP BY b.bookID
                    ) a
               ON bk.bookID = a.bookID


答:
This is giving you an error because you're trying to return every row from a query which is trying to give you an aggregate result.

The "max" operation is an aggregate function which means it says "give me a whole lot of rows, and I'll return you one result.

Whereas just saying "select *" isn't an aggregate operation, it just says "give me a result for each row that I select"

The easiest way to solve your problem and get all of the details for the row with max(donationsCollected) would be to do a select like:

```<code>select * from LibraryRepairEvent where donationsCollected =
SELECT MAX(LibraryRepairEvent.donationsCollected)
FROM LibraryRepairEvent
WHERE EXISTS (
    SELECT 1 FROM MemberBorrowsBook
    JOIN Book ON Book.bookID = MemberBorrowsBook.bookID
    WHERE LibraryRepairEvent.organiserID = MemberBorrowsBook.memberID
)
</code>```

I can't remember if you need to say "where donationsCollected = " or "where donationsCollected in" so give them both a try

Title: How to go about SELECT 1 FROM

Body:
This is my query

This is another try:

Instead of selecting the MAX, is there anyway I can get hold of the Book details ???

I have tried changing to Book.* but it's erroring. Please can someone tell me how to go about doing so I can retrieve the Book information ??

What i am trying to do is to get the highest amount from one table and get the records associated to it

Thanks in advance

Body:
This is giving you an error because you're trying to return every row from a query which is trying to give you an aggregate result.

The "max" operation is an aggregate function which means it says "give me a whole lot of rows, and I'll return you one result.

Whereas just saying "select *" isn't an aggregate operation, it just says "give me a result for each row that I select"

The easiest way to solve your problem and get all of the details for the row with max(donationsCollected) would be to do a select like:

select * from LibraryRepairEvent where donationsCollected =
SELECT MAX(LibraryRepairEvent.donationsCollected)
FROM LibraryRepairEvent
WHERE EXISTS (
    SELECT 1 FROM MemberBorrowsBook
    JOIN Book ON Book.bookID = MemberBorrowsBook.bookID
    WHERE LibraryRepairEvent.organiserID = MemberBorrowsBook.memberID
)

I can't remember if you need to say "where donationsCollected = " or "where donationsCollected in" so give them both a try


问:
It is possible to run multiple instance of foundation-emails?
I am working on an web app to build newsletters email, I wanna use foundation-emails but I dont know if is possible to run multiple instances for build multiple email.

For example, two user use the web app and build emails at the same time.

The output must be an html file and its assets (images and files), all this in a zip.

答:
You could run multiple instances. However, you should be able to accomplish multiple emails that are radically different and use only one install.

I have created several different emails in the same instance that use different fonts, colors and use the same sass file, which is my only modification. I use a  different classes to match individual styles.

```<code><body class="alfa">
<body class="beta">
<body class="charlie">
<body class="delta">
</code>```

By changing the class, the entire email changes on the fly.

I created custom layouts because it's a lot easier to have specific logos and links attached to the layout and create pages for the content.

Body:
You could run multiple instances. However, you should be able to accomplish multiple emails that are radically different and use only one install.

I have created several different emails in the same instance that use different fonts, colors and use the same sass file, which is my only modification. I use a  different classes to match individual styles.

<body class="alfa">
<body class="beta">
<body class="charlie">
<body class="delta">

By changing the class, the entire email changes on the fly.

I created custom layouts because it's a lot easier to have specific logos and links attached to the layout and create pages for the content.


问:
Trying to use brace expansion in EOF heredoc
I am trying to use brace expansion in an EOF heredoc. Having a lot of trouble doing so. I am trying to create a script which will tell the person their chinese zodiac, and it's based on year/month/day
example: Feb 2 1984 - Feb 19 1985 = RAT

```<code>awk -v year="${1}${2}${3}" '
$0 ~ year {
    print $1
    found = 1
    exit
}
END {
    if (!found)
        exit 1
}
' <<EOF
Rat 1984 1985 1996 2008 2020 2034
Ox  1985 1997 2009 2021
Tiger 1986 1998 2010 2022
Rabbit 1987 1999 2011 2023
Dragon 1988 2000 2012 2024
Snake 1989 2001 2013 2025
Horse 1990 2002 2014 2026
Goat 1991 2003 2015 2027
Monkey 1992 2004 2016 2028
Rooster 1993 2005 2017 2029
Dog 1994 2006 2018 2030
Pig 1995 2007 2019 2031
EOF
</code>```

I would like to use Rat 1984{02..12}{0..31} 1985{01,02}{0..31} in order to expand my awk to search through the range of numbers provided in the brace. Is this possible?
Thanks.

答:
The Bash manual on here documents says:

If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and ‘\’ must be used to quote the characters ‘\’, ‘$’, and ‘`’.

The word in your sample is the unquoted EOF.

The list of expansions does not include brace expansion; I think you are out of luck.

Is there a workaround?

It may depend in part on your version of Bash — on macOS Sierra 10.12.4, the default is 3.2.57, which gives different output from Bash 4.3.

Brace expansion is a somewhat limited affair — there are many things you can't do with it because variables are not expanded until after brace expansion occurs.

This might be a hint; I'm not quite sure how you'd include it in your script, though.

```<code>$ printf 'Rat %s\n' 1984{02..12}{0..31} 1985{01,02}{0..31}
Rat 198420
Rat 198421
Rat 198422
Rat 198423
Rat 198424
…
Rat 19850227
Rat 19850228
Rat 19850229
Rat 19850230
Rat 19850231
$ bash-4.3 -c "printf 'Rat %s\n' 1984{02..12}{0..31} 1985{01,02}{0..31}"
Rat 1984020
Rat 1984021
Rat 1984022
Rat 1984023
Rat 1984024
Rat 1984025
…
Rat 19850226
Rat 19850227
Rat 19850228
Rat 19850229
Rat 19850230
Rat 19850231
$
</code>```

Note that the leading zeros are gone in 198420, etc. with Bash 3.x.  I'm curious about day 0, not to mention 31st February, but I assume those will be dealt with.

Now you have to decide how you might incorporate that into your script to generate the data.  You might find that a script that generates a script, and then runs the generated script, is easier to manage than scripting directly.

Body:
I am trying to use brace expansion in an EOF heredoc. Having a lot of trouble doing so. I am trying to create a script which will tell the person their chinese zodiac, and it's based on year/month/day
example: Feb 2 1984 - Feb 19 1985 = RAT

awk -v year="${1}${2}${3}" '
$0 ~ year {
    print $1
    found = 1
    exit
}
END {
    if (!found)
        exit 1
}
' <<EOF
Rat 1984 1985 1996 2008 2020 2034
Ox  1985 1997 2009 2021
Tiger 1986 1998 2010 2022
Rabbit 1987 1999 2011 2023
Dragon 1988 2000 2012 2024
Snake 1989 2001 2013 2025
Horse 1990 2002 2014 2026
Goat 1991 2003 2015 2027
Monkey 1992 2004 2016 2028
Rooster 1993 2005 2017 2029
Dog 1994 2006 2018 2030
Pig 1995 2007 2019 2031
EOF

I would like to use Rat 1984{02..12}{0..31} 1985{01,02}{0..31} in order to expand my awk to search through the range of numbers provided in the brace. Is this possible?
Thanks.

Body:
The Bash manual on here documents says:

If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and ‘\’ must be used to quote the characters ‘\’, ‘$’, and ‘`’.

The word in your sample is the unquoted EOF.

The list of expansions does not include brace expansion; I think you are out of luck.

Is there a workaround?

It may depend in part on your version of Bash — on macOS Sierra 10.12.4, the default is 3.2.57, which gives different output from Bash 4.3.

Brace expansion is a somewhat limited affair — there are many things you can't do with it because variables are not expanded until after brace expansion occurs.

This might be a hint; I'm not quite sure how you'd include it in your script, though.

$ printf 'Rat %s\n' 1984{02..12}{0..31} 1985{01,02}{0..31}
Rat 198420
Rat 198421
Rat 198422
Rat 198423
Rat 198424
…
Rat 19850227
Rat 19850228
Rat 19850229
Rat 19850230
Rat 19850231
$ bash-4.3 -c "printf 'Rat %s\n' 1984{02..12}{0..31} 1985{01,02}{0..31}"
Rat 1984020
Rat 1984021
Rat 1984022
Rat 1984023
Rat 1984024
Rat 1984025
…
Rat 19850226
Rat 19850227
Rat 19850228
Rat 19850229
Rat 19850230
Rat 19850231
$

Note that the leading zeros are gone in 198420, etc. with Bash 3.x.  I'm curious about day 0, not to mention 31st February, but I assume those will be dealt with.

Now you have to decide how you might incorporate that into your script to generate the data.  You might find that a script that generates a script, and then runs the generated script, is easier to manage than scripting directly.


问:
Cannot make getJson function to work
I have three separate files: a php webpage, a js script and a php webserver. a js script has to pass information from the website to the server.
The php file has a form with a submit button:

```<code><script>
$(document).ready(function(){
    $("#form1").submit(getfunction1);
});
</script>
<form id = "form1" method="GET"  action="search.php">
    <div class="form">
       <input type="text" id ="coursestex" value="course name"/>
       <input type="submit" id ="submitbut" value="submit"/>
    </div>
    </form>
</fieldset>
</code>```

This is a js file that suppose to pass the information to the webserver.

```<code>function getfunction1(event){
    event.preventDefault();
    $.getJSON("exams.php", [{name: "course", value: "csc"}], function() {
        alert("correct");
    });
};
</code>```

What is the problem here? I dont get the pop-up message so its not working right?

答:
The second argument to $.getJSON should be an object, not an array of objects.

```<code>$.getJSON("exams.php", {name: "course", value: "csc"}, function() {
    alert("correct");
});
</code>```

In the PHP script you'll get these parameters with $_GET['name'] and $_GET['value']. If it's supposed to be $_GET['course'] == "csc" then the object should be:

```<code>{ course: "csc" }
</code>```

Title: Cannot make getJson function to work

Body:
I have three separate files: a php webpage, a js script and a php webserver. a js script has to pass information from the website to the server.
The php file has a form with a submit button:

<form id = "form1" method="GET"  action="search.php">

       <input type="text" id ="coursestex" value="course name"/>
       <input type="submit" id ="submitbut" value="submit"/>

    </form>
</fieldset>

This is a js file that suppose to pass the information to the webserver.

function getfunction1(event){
    event.preventDefault();
    $.getJSON("exams.php", [{name: "course", value: "csc"}], function() {
        alert("correct");
    });
};

What is the problem here? I dont get the pop-up message so its not working right?

Body:
The second argument to $.getJSON should be an object, not an array of objects.

$.getJSON("exams.php", {name: "course", value: "csc"}, function() {
    alert("correct");
});

In the PHP script you'll get these parameters with $_GET['name'] and $_GET['value']. If it's supposed to be $_GET['course'] == "csc" then the object should be:

{ course: "csc" }


答:
You can download android studio from google

Since it just needs java, it should work on OSX also. In the studio you would be able to lauch different emulated devices, fully connected to the network.

The download is huge and the setup is relatively easy. And it's flexible, when it comes to the different android versions, devices and screen sizes.

Title: How can I test a mobile website for an Android device, if I'm using a mac?

Body: I'm creating a website and I've been testing in different browsers, but not android devices, because I don't normally have access. Someone looked at the site on an Android phone (using the default web browser and chrome) and one of the pages is not displaying correctly.   My index page is just a full screen image, but on the Android device, the image is pushed up and the bottom half of the screen is white.  I can't figure out why this would be different on an Android phone. How can I test my site to see how it would react on an Android phone?


问:
Spark DataFrame nulls to Dataset
When importing data from a MS SQL database, there is the potential for null values. In Spark, DataFrames are able to handle the null values. But when I try to convert the DataFrame to a strongly typed Dataset, I receive encoder errors.

Here's a simple example:

```<code>case class optionTest(var a: Option[Int], var b: Option[Int])

object testObject {
  def main(args: Array[String]): Unit = {
    import spark.implicits._
    val df = spark.sparkContext.parallelize(Seq(input)).toDF()

    val df2 = Seq((1, 3), (3, Option(null)))
                 .toDF("a", "b")
                 .as[optionTest]

    df2.show()
  }
}
</code>```

Here is the error for this case:

```<code>No Encoder found for Any
- field (class: "java.lang.Object", name: "_2")
- root class: "scala.Tuple2"
java.lang.UnsupportedOperationException: No Encoder found for Any
- field (class: "java.lang.Object", name: "_2")
- root class: "scala.Tuple2"
</code>```

What is the recommended approach to handle nullable values when creating a Dataset from a DataFrame?

答:
The problem is that your Dataframe doesn't match your case class.

Your first pair is an (Int, Int), and your second is an (Int, Option[Null]).

The easy thing to note is that if you want to represent an Option[Int], the value will be either Some(3), for example, or None for an absent value.

The tricky thing to note is that in Scala Int is a subclass of AnyVal while nullable references, which should be almost nonexistent in the Scala code you write, are on the AnyRef side of the Scala object hierarchy.

Because you have a bunch of objects that are all over the Scala object model, Spark has to treat your data as Any, the superclass of everything. There is no encoder that can handle that.

So with all that said, your data would have to look like this:

val df2 = Seq((Some(1), Some(3)), (Some(3), None))

As a side note, your case class should look like this:

case class OptionTest(a: Option[Int], b: Option[Int])

Title: Spark DataFrame nulls to Dataset

Body:
When importing data from a MS SQL database, there is the potential for null values. In Spark, DataFrames are able to handle the null values. But when I try to convert the DataFrame to a strongly typed Dataset, I receive encoder errors.

Here's a simple example:

case class optionTest(var a: Option[Int], var b: Option[Int])

object testObject {
  def main(args: Array[String]): Unit = {
    import spark.implicits._
    val df = spark.sparkContext.parallelize(Seq(input)).toDF()

    val df2 = Seq((1, 3), (3, Option(null)))
                 .toDF("a", "b")
                 .as[optionTest]

    df2.show()
  }
}

Here is the error for this case:

No Encoder found for Any
- field (class: "java.lang.Object", name: "_2")
- root class: "scala.Tuple2"
java.lang.UnsupportedOperationException: No Encoder found for Any
- field (class: "java.lang.Object", name: "_2")
- root class: "scala.Tuple2"

What is the recommended approach to handle nullable values when creating a Dataset from a DataFrame?


问:
Swift for Android: `ld` cannot find `-lgcc` in swift for android compilation linking step
Moving from Unix Stack Exchange to here, my bounty there failed:

I'm trying to compile Swift code on Ubuntu 16.04 LTS, following these instructions fairly closely. I was able to download the NDK r14 okay, download the libicu tools and build them, and download the swift source and build that against the libicu tools. I get all the way down to compiling actual swift code and get this:

```<code>#build.sh
#(I symlinked the androideabi ld.gold to /usr/bin/ld.armv7, based on a swift bug ticket's advice. Thats the only thing different from the instructions)

/home/mike/workspace/swift-source/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swiftc \
-use-ld=armv7 \
-tools-directory /home/mike/workspace/android-ndk-r14/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/arm-linux-androideabi/bin \
-target armv7-none-linux-androideabi \
-sdk /home/mike/workspace/android-ndk-r14/platforms/android-21/arch-arm \
-L /home/mike/workspace/android-ndk-r14/sources/cxx-stl/llvm-libc++/libs/armeabi-v7a \
-L /home/mike/workspace/android-ndk-r14/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/lib/gcc/arm-linux-androideabi/4.9 \
hello.swift

#output
mike@mike-VirtualBox:~/workspace/HelloSwift$ ./build.sh
/usr/bin/ld.armv7: error: cannot find -lgcc
/usr/bin/ld.armv7: error: cannot find -lgcc
/usr/bin/ld.armv7: error: cannot find -lgcc
/usr/bin/ld.armv7: error: cannot find -lgcc
</code>```

I don't have a ton of experience being this far down the toolchain, but I definitely have gcc installed, and gcc-multilib, and LD_LIBRARY_PATH set to help ld find gcc, and I've rebuild the ld cache with ldconfig.

When I run sudo ldconfig -p | grep gcc, I get

```<code>libgccpp.so.1 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libgccpp.so.1
libgcc_s.so.1 (libc6,x32) => /usr/libx32/libgcc_s.so.1
libgcc_s.so.1 (libc6,x86-64) => /lib/x86_64-linux-gnu/libgcc_s.so.1
libgcc_s.so.1 (libc6) => /usr/lib32/libgcc_s.so.1
</code>```

and a few other things named libuno_<something with gcc in it>

答:
In the newest version of android-ndk-r14b, the location of required gcc library is at:

/path/to/android-ndk-r14b/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/lib/gcc/arm-linux-androideabi/4.9.x

The Swift Android docs seem to be outdated, and point to:

/path/to/android-ndk-r14b/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/lib/gcc/arm-linux-androideabi/4.9.

Making sure you link against this correct path in your call to swiftc should solve the problem.

(I've submitted this pull request to ensure nobody else runs into this as well.)

Body:
Moving from Unix Stack Exchange to here, my bounty there failed:

I'm trying to compile Swift code on Ubuntu 16.04 LTS, following these instructions fairly closely. I was able to download the NDK r14 okay, download the libicu tools and build them, and download the swift source and build that against the libicu tools. I get all the way down to compiling actual swift code and get this:

#build.sh
#(I symlinked the androideabi ld.gold to /usr/bin/ld.armv7, based on a swift bug ticket's advice. Thats the only thing different from the instructions)

/home/mike/workspace/swift-source/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swiftc \
-use-ld=armv7 \
-tools-directory /home/mike/workspace/android-ndk-r14/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/arm-linux-androideabi/bin \
-target armv7-none-linux-androideabi \
-sdk /home/mike/workspace/android-ndk-r14/platforms/android-21/arch-arm \
-L /home/mike/workspace/android-ndk-r14/sources/cxx-stl/llvm-libc++/libs/armeabi-v7a \
-L /home/mike/workspace/android-ndk-r14/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/lib/gcc/arm-linux-androideabi/4.9 \
hello.swift

#output
mike@mike-VirtualBox:~/workspace/HelloSwift$ ./build.sh
/usr/bin/ld.armv7: error: cannot find -lgcc
/usr/bin/ld.armv7: error: cannot find -lgcc
/usr/bin/ld.armv7: error: cannot find -lgcc
/usr/bin/ld.armv7: error: cannot find -lgcc

I don't have a ton of experience being this far down the toolchain, but I definitely have gcc installed, and gcc-multilib, and LD_LIBRARY_PATH set to help ld find gcc, and I've rebuild the ld cache with ldconfig.

When I run sudo ldconfig -p | grep gcc, I get

libgccpp.so.1 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libgccpp.so.1
libgcc_s.so.1 (libc6,x32) => /usr/libx32/libgcc_s.so.1
libgcc_s.so.1 (libc6,x86-64) => /lib/x86_64-linux-gnu/libgcc_s.so.1
libgcc_s.so.1 (libc6) => /usr/lib32/libgcc_s.so.1

and a few other things named libuno_<something with gcc in it>


问:
How to check if less than 'n' numbers were input into an array containing of size n?
I have the following code. This will keep asking for a user's input n times until all 'n' elements in the array are full. I want to make it such that if a user doesn't enter a value (i.e. the
'n' element array doesn't have n elements in it) then it will return 0. Thanks</p>

```<code>for(i=0; i<n; i++){

    scanf("%d", &array[i]);

    if(**check condition here**) {
        return 0;
    }
}

return 1;
</code>```

答:
The documentation for scanf http://www.cplusplus.com/reference/cstdio/scanf/ states:

On success, the function returns the number of items of the argument list successfully filled

So check the return value:

```<code>int items = scanf("%d", &array[n]);
if( items == 1 ) {
    // was read
}
else {
    // no input
}
</code>```

There's a bug in your code: you're always setting array[n] without incrementing n. I think you should change it to &array[i].

Body:
I have the following code. This will keep asking for a user's input n times until all 'n' elements in the array are full. I want to make it such that if a user doesn't enter a value (i.e. the
'n' element array doesn't have n elements in it) then it will return 0. Thanks

for(i=0; i<n; i++){

    scanf("%d", &array[i]);

    if(**check condition here**) {
        return 0;
    }
}

return 1;

Body:
The documentation for scanf http://www.cplusplus.com/reference/cstdio/scanf/ states:

On success, the function returns the number of items of the argument list successfully filled

So check the return value:

int items = scanf("%d", &array[n]);
if( items == 1 ) {
    // was read
}
else {
    // no input
}

There's a bug in your code: you're always setting array[n] without incrementing n. I think you should change it to &array[i].


问:
Need help using a while statement and getting the math right
I'm still very new to coding.  My teacher is very hard to understand so I need online help.  For this, I need to find the value in a savings account after months of compounding interest. I know that my math is wrong but I don't know how to fix this, and I've never written a while statement.  Please help me out.

From my prompt:

"Suppose you save $100 each month into the savings account and the
  annual interest rate is 5%.   So, the monthly interest rate is 0.05/12
  = 0.00417.   After the first month, the value in the account becomes 100* (1 + 0.00417) = $100.417    After the second month, the value in
  the account becomes (100 + 100.417) * (1 + 0.00417) = $201.252 After
  the third month, the value in the account becomes
         (100 + 201.252) * (1 + 0.00417) = $302.507 and so on."

```<code>double initialSavings;
System.out.print("How much money would you like to save each month? $");
initialSavings = userInput.nextDouble();

double annualInterest;
System.out.print("What is the annual interest rate for your savings account? (Example, 2.5) ");
annualInterest = userInput.nextDouble();

int months;
System.out.print("How many months would you like to keep saving? ");
months = userInput.nextInt();

double monthlyInterest;
monthlyInterest = annualInterest / 12;

int count = 1;

while (count <= months) {

count++;

double result;

result = initialSavings * count * (1 + monthlyInterest);

}

System.out.println("You will have $"+ result "after "+ months "months.");
}
}
</code>```

答:
There's no need of while to calculate it.
this way you'll get the final ammount of money. You need to get the Interest/100 if you are inserting values like "10" to 10%.

```<code>result = initialSavings*(1+((monthlyInterest/100)*months))
</code>```

for the compounded interest:

```<code>result = initialSavings*Math.pow((1+(monthlyInterest/100)),months);
</code>```

Body:
I'm still very new to coding.  My teacher is very hard to understand so I need online help.  For this, I need to find the value in a savings account after months of compounding interest. I know that my math is wrong but I don't know how to fix this, and I've never written a while statement.  Please help me out.

From my prompt:

"Suppose you save $100 each month into the savings account and the
  annual interest rate is 5%.   So, the monthly interest rate is 0.05/12
  = 0.00417.   After the first month, the value in the account becomes 100* (1 + 0.00417) = $100.417    After the second month, the value in
  the account becomes (100 + 100.417) * (1 + 0.00417) = $201.252 After
  the third month, the value in the account becomes
         (100 + 201.252) * (1 + 0.00417) = $302.507 and so on."

double initialSavings;
System.out.print("How much money would you like to save each month? $");
initialSavings = userInput.nextDouble();

double annualInterest;
System.out.print("What is the annual interest rate for your savings account? (Example, 2.5) ");
annualInterest = userInput.nextDouble();

int months;
System.out.print("How many months would you like to keep saving? ");
months = userInput.nextInt();

double monthlyInterest;
monthlyInterest = annualInterest / 12;

int count = 1;

while (count <= months) {

count++;

double result;

result = initialSavings * count * (1 + monthlyInterest);

}

System.out.println("You will have $"+ result "after "+ months "months.");
}
}

Body:
There's no need of while to calculate it.
this way you'll get the final ammount of money. You need to get the Interest/100 if you are inserting values like "10" to 10%.

result = initialSavings*(1+((monthlyInterest/100)*months))

for the compounded interest:

result = initialSavings*Math.pow((1+(monthlyInterest/100)),months);


问:
understanding the lower bound/ upper bound interface
I am having trouble grasping the semantics of the lower/ upper bound interface.

Consider this test snippet I wrote:

```<code>#include <algorithm>
#include <iostream>
#include <vector>

int main() {

  // sorted vector
  std::vector<std::pair<size_t, std::vector<int>>> v = {
      std::make_pair(0, std::vector<int>()),
      std::make_pair(0, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(5, std::vector<int>()),
      std::make_pair(20, std::vector<int>())};

  auto key = 3;
  auto itr = std::lower_bound(
      v.begin(), v.end(), key,
      [](const auto &t1, const size_t d) -> bool { return t1.first < d; });

  std::cout << itr->first << "\n";
}
</code>```

Why do I not need two vector elements? Why do I need only one and a second argument (d) of the type of key? What is d anyway? The documentation sounded like it is a vector element cast to type of key. But why then not accept another vector element as the second argument? And why does no comparison against key happen?

Why does the interface not look like this:

```<code>auto itr = std::lower_bound(v.begin(), v.end(), 3, [](const auto& t1, const
  auto& t2) -> bool {return t1.first < t2.first;});
</code>```

Can you explain the semantics behind the parameters, especially d?

答:
The 4th argument of lower_bound is the definition of < between the element in the container and your key.

```<code>auto itr = std::lower_bound(v.begin(), v.end(), 3, [](const auto& t1, const
  auto& t2) -> bool {return t1.first < t2.first;});
</code>```

With this, lower_bound is only aware of the < relationship between elements (i.e. {int, vector<int>}) in the array, but know nothing about the relationship between element and the key. Thus lower_bound cannot find the key, because it just don't know the rule to compare!

d is here passed as key, i.e. 3 every time for comparison. It is equal to

```<code>auto it = std::lower_bound(
    v.begin(), v.end(), key,
    [key](const auto &t1, const size_t whatever) -> bool { return t1.first < key; }
);
</code>```

Check more on the code from cplusplus.com.

http://www.cplusplus.com/reference/algorithm/lower_bound/

Body:
I am having trouble grasping the semantics of the lower/ upper bound interface.

Consider this test snippet I wrote:

#include <algorithm>
#include <iostream>
#include <vector>

int main() {

  // sorted vector
  std::vector<std::pair<size_t, std::vector<int>>> v = {
      std::make_pair(0, std::vector<int>()),
      std::make_pair(0, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(5, std::vector<int>()),
      std::make_pair(20, std::vector<int>())};

  auto key = 3;
  auto itr = std::lower_bound(
      v.begin(), v.end(), key,
      [](const auto &t1, const size_t d) -> bool { return t1.first < d; });

  std::cout << itr->first << "\n";
}

Why do I not need two vector elements? Why do I need only one and a second argument (d) of the type of key? What is d anyway? The documentation sounded like it is a vector element cast to type of key. But why then not accept another vector element as the second argument? And why does no comparison against key happen?

Why does the interface not look like this:

auto itr = std::lower_bound(v.begin(), v.end(), 3, [](const auto& t1, const
  auto& t2) -> bool {return t1.first < t2.first;});

Can you explain the semantics behind the parameters, especially d?

Body:
The 4th argument of lower_bound is the definition of < between the element in the container and your key.

auto itr = std::lower_bound(v.begin(), v.end(), 3, [](const auto& t1, const
  auto& t2) -> bool {return t1.first < t2.first;});

With this, lower_bound is only aware of the < relationship between elements (i.e. {int, vector<int>}) in the array, but know nothing about the relationship between element and the key. Thus lower_bound cannot find the key, because it just don't know the rule to compare!

d is here passed as key, i.e. 3 every time for comparison. It is equal to

auto it = std::lower_bound(
    v.begin(), v.end(), key,
    [key](const auto &t1, const size_t whatever) -> bool { return t1.first < key; }
);

Check more on the code from cplusplus.com.

http://www.cplusplus.com/reference/algorithm/lower_bound/


问:
Is it possible to have a class extend number?
I know this is probably a no but is there some way in typescript to have a class inherit from a number? I have a bunch of cases where the class is one number value and a bunch of methods. So theoretically the class could be a number plus those methods.

Is there a way to do this?

thanks - dave

答:
Today, it is possible.</p>

```<code>/**
 * Decimal class
 *
 * Represents a decimal number with a fixed precision which can be defined in the constructor.
 *
 * @export
 * @class Decimal
 * @extends {Number}
 * @implements {Number}
 */
export class Decimal extends Number implements Number {
  public precision: number;

  /**
   * Creates an instance of Decimal.
   *
   * @param {(number | string)} value
   *
   * @memberOf Decimal
   */
  constructor(value: number | string, precision: number = 2) {
    if (typeof value === 'string') {
      value = parseFloat(value);
    }

    if (typeof value !== 'number' || isNaN(value)) {
      throw new Error('Decimal constructor requires a number or the string representation of a number.');
    }

    super(parseFloat((value || 0).toFixed(2)));
    this.precision = precision;
  }

  /**
   * Returns the value of this instance as a number
   *
   * @returns {number}
   *
   * @memberOf Decimal
   */
  public valueOf(): number {
    return parseFloat(this.toFixed(2));
  }

  /**
   * Returns the string representation for this instance.
   *
   * @returns {string}
   *
   * @memberOf Decimal
   */
  public toString(): string {
    return this.toFixed(2);
  }
}
</code>```

Body:
Today, it is possible.

/**
 * Decimal class
 *
 * Represents a decimal number with a fixed precision which can be defined in the constructor.
 *
 * @export
 * @class Decimal
 * @extends {Number}
 * @implements {Number}
 */
export class Decimal extends Number implements Number {
  public precision: number;

  /**
   * Creates an instance of Decimal.
   *
   * @param {(number | string)} value
   *
   * @memberOf Decimal
   */
  constructor(value: number | string, precision: number = 2) {
    if (typeof value === 'string') {
      value = parseFloat(value);
    }

    if (typeof value !== 'number' || isNaN(value)) {
      throw new Error('Decimal constructor requires a number or the string representation of a number.');
    }

    super(parseFloat((value || 0).toFixed(2)));
    this.precision = precision;
  }

  /**
   * Returns the value of this instance as a number
   *
   * @returns {number}
   *
   * @memberOf Decimal
   */
  public valueOf(): number {
    return parseFloat(this.toFixed(2));
  }

  /**
   * Returns the string representation for this instance.
   *
   * @returns {string}
   *
   * @memberOf Decimal
   */
  public toString(): string {
    return this.toFixed(2);
  }
}


问:
Sending html files with express
I'm making a small website that has a little subscription list that emails people using node and express. Now my issue is I send the users an unsubscribe link whenever they want to unsubscribe.

```<code>app.get('/unsubscribe',
...
...);
</code>```

Now I want to redirect them to a web page after they have unsubscribed. So it unsubscribes them correctly and emails them letting them know that they have unsubscribed, but I want it to redirect them to the HTML /#/unsubscribe after they want to /unsubscribe. I'm sorry if I'm over complicating it but I haven't been able to find an answer.

I've tried res.sendfile('./public/views/unsubscribe.html');

Also res.sendfile('./public/views/unsubscribe.html', {root: __dirname});

Every time I get redirected it tells me "Error: ENOENT: no such file or directory, stat '/public/views/unsubscribe.html'"

答:
Since you're using AngularJS routes for templating, have you tried using res.render()? If not, you can do something like:

```<code>res.render(path.join(__dirname, 'yourfile.html'));
</code>```

You'd need to install the path module as a dependency.

Title: Sending html files with express

Body:
I'm making a small website that has a little subscription list that emails people using node and express. Now my issue is I send the users an unsubscribe link whenever they want to unsubscribe.

app.get('/unsubscribe',
...
...);

Now I want to redirect them to a web page after they have unsubscribed. So it unsubscribes them correctly and emails them letting them know that they have unsubscribed, but I want it to redirect them to the HTML /#/unsubscribe after they want to /unsubscribe. I'm sorry if I'm over complicating it but I haven't been able to find an answer.

I've tried res.sendfile('./public/views/unsubscribe.html');

Also res.sendfile('./public/views/unsubscribe.html', {root: __dirname});

Every time I get redirected it tells me "Error: ENOENT: no such file or directory, stat '/public/views/unsubscribe.html'"

Body:
Since you're using AngularJS routes for templating, have you tried using res.render()? If not, you can do something like:

res.render(path.join(__dirname, 'yourfile.html'));

You'd need to install the path module as a dependency.


问:
How do create an instance of Fuel Email and use it?
Noob to Composer and packagist.

When I install, for example, Respect/Validation with Composer, it puts it into vendor/ directory, and I add the necessary 'use' statements, etc.

I keep referencing: https://fuelphp.com/docs/packages/email/usage.html

It doesn't tell me what to put at the top for the 'use' statement.
Also, when I run 'composer require fuel/email', I notice that, unlike other Composer packages, Fuel/email doesn't go into 'vendor' directory...why not?

Consequently, this crashes things:

```<code>$email = Email::forge();
</code>```

答:
Fuel/email doesn't go into 'vendor' directory...why not?

fuel/email is from same vendor of the framework, therefore library will go into fuel/packages/email directory. Just for double check, ensure that you composer.json file in root project directory includes "fuel/email": "1.8.*", in require.

it puts it into vendor/ directory, and I add the necessary 'use' statements, etc.

This is unnecessary, because all vendor classes will be autoloaded by vendor/autoload.php, which is generated by composer.

It doesn't tell me what to put at the top for the 'use' statement

Same as mentioned above you don't need to use use statement. However, you need to configure which packages to be loaded.

Therefore, you need to add email to always_load configuration of packages in fuel/app/config/config.php file, like below

```<code>/**************************************************************************/
/* Always Load                                                            */
/**************************************************************************/
'always_load'  => array(

    /**
     * These packages are loaded on Fuel's startup.
     * You can specify them in the following manner:
     *
     * array('auth'); // This will assume the packages are in PKGPATH
     *
     * // Use this format to specify the path to the package explicitly
     * array(
     *     array('auth' => PKGPATH.'auth/')
     * );
     */
    'packages'  => array(
        'email',
    ),
</code>```

Body:
Noob to Composer and packagist.

When I install, for example, Respect/Validation with Composer, it puts it into vendor/ directory, and I add the necessary 'use' statements, etc.

I keep referencing: https://fuelphp.com/docs/packages/email/usage.html

It doesn't tell me what to put at the top for the 'use' statement.
Also, when I run 'composer require fuel/email', I notice that, unlike other Composer packages, Fuel/email doesn't go into 'vendor' directory...why not?

Consequently, this crashes things:

$email = Email::forge();

Body:
Fuel/email doesn't go into 'vendor' directory...why not?

fuel/email is from same vendor of the framework, therefore library will go into fuel/packages/email directory. Just for double check, ensure that you composer.json file in root project directory includes "fuel/email": "1.8.*", in require.

it puts it into vendor/ directory, and I add the necessary 'use' statements, etc.

This is unnecessary, because all vendor classes will be autoloaded by vendor/autoload.php, which is generated by composer.

It doesn't tell me what to put at the top for the 'use' statement

Same as mentioned above you don't need to use use statement. However, you need to configure which packages to be loaded.

Therefore, you need to add email to always_load configuration of packages in fuel/app/config/config.php file, like below

/**************************************************************************/
/* Always Load                                                            */
/**************************************************************************/
'always_load'  => array(

    /**
     * These packages are loaded on Fuel's startup.
     * You can specify them in the following manner:
     *
     * array('auth'); // This will assume the packages are in PKGPATH
     *
     * // Use this format to specify the path to the package explicitly
     * array(
     *     array('auth' => PKGPATH.'auth/')
     * );
     */
    'packages'  => array(
        'email',
    ),


问:
Custom google maps infowindow using ionic 2
I am new to ionic 2, I am trying to create a custom info window, so when a user clicks on a marker they can see some basic information like a picture and the name of the location, but they can also click on a link in the infoWindow that opens a modal with details on that location. Here is how i want to add it to my marker. </p>

```<code>addMarker(lat: number, lng: number, place: any): void {
    let latLng = new google.maps.LatLng(lat, lng);

    let marker = new google.maps.Marker({
        map: this.map,
        animation: google.maps.Animation.DROP,
        position: latLng,
        title: place.name
    });

    let infoWindow = new google.maps.InfoWindow({
       content: `<>custom template here with some basic details</>`
    });

    marker.addListener('click', ()=> {
       infoWindow.open(this.map, marker);

    });

    this.markers.push(marker);
}
</code>```

答: Do you see any error in console? May be you are trying to access google.maps before its even initialized. First you need to ensure that google map library has loaded before calling any it by passing callback to script url. See https://developers.google.com/maps/documentation/javascript/adding-a-google-map for reference. Its better to use any libary like https://github.com/SebastianM/angular2-google-maps for working with maps in ionic framework.</p>

Body:
I am new to ionic 2, I am trying to create a custom info window, so when a user clicks on a marker they can see some basic information like a picture and the name of the location, but they can also click on a link in the infoWindow that opens a modal with details on that location. Here is how i want to add it to my marker.

addMarker(lat: number, lng: number, place: any): void {
    let latLng = new google.maps.LatLng(lat, lng);

    let marker = new google.maps.Marker({
        map: this.map,
        animation: google.maps.Animation.DROP,
        position: latLng,
        title: place.name
    });

    let infoWindow = new google.maps.InfoWindow({
       content: `<>custom template here with some basic details</>`
    });

    marker.addListener('click', ()=> {
       infoWindow.open(this.map, marker);

    });

    this.markers.push(marker);
}


问:
How can i view the MVC Object Model graphically
This page explains MVC result types, in part, by showing a graphic tree of that part of the object model. What tool was used to render that graphic?</p>

答:
It looks like a Class Diagram from the Visual Studio Class Designer:

http://msdn.microsoft.com/en-us/library/33864ckt.aspx