问:
predict.lm after regression with missing data in Y
I don't understand how to generate predicted values from a linear regression using the predict.lm command when some value of the dependent variable Y are missing, even though no independent X observation is missing. Algebraically, this isn't a problem, but I don't know an efficient method to do it in R. Take for example this fake dataframe and regression model. I attempt to assign predictions in the source dataframe but am unable to do so because of one missing Y value: I get an error.

```<code># Create a fake dataframe
x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(100,200,300,400,NA,600,700,800,900,100)
df <- as.data.frame(cbind(x,y))

# Regress X and Y
model<-lm(y~x+1)
summary(model)

# Attempt to generate predictions in source dataframe but am unable to.
df$y_ip<-predict.lm(testy)

Error in `$<-.data.frame`(`*tmp*`, y_ip, value = c(221.............
  replacement has 9 rows, data has 10
</code>```

I got around this problem by generating the predictions using algebra, df$y<-B0+ B1*df$x, or  generating the predictions by calling the coefficients of the model df$y<-((summary(model)$coefficients[1, 1]) + (summary(model)$coefficients[2, 1]*(df$x)) ; however, I am now working with a big data model with hundreds of coefficients, and these methods are no longer practical. I'd like to know how to do it using the predict function.

Thank you in advance for your assistance!

答:
Actually, you are not using correctly the predict.lm function.
Either way you have to input the model itself as its first argument, hereby model, with or without the new data. Without the new data, it will only predict on the training data, thus excluding your NA row and you need this workaround to fit the initial data.frame:

```<code>df$y_ip[!is.na(df$y)] <- predict.lm(model)
</code>```

Or explicitly specifying some new data. Since the new x has one more row than the training x it will fill the missing row with a new prediction:

```<code>df$y_ip <- predict.lm(model, newdata = df)
</code>```

Body:
I don't understand how to generate predicted values from a linear regression using the predict.lm command when some value of the dependent variable Y are missing, even though no independent X observation is missing. Algebraically, this isn't a problem, but I don't know an efficient method to do it in R. Take for example this fake dataframe and regression model. I attempt to assign predictions in the source dataframe but am unable to do so because of one missing Y value: I get an error.

# Create a fake dataframe
x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(100,200,300,400,NA,600,700,800,900,100)
df <- as.data.frame(cbind(x,y))

# Regress X and Y
model<-lm(y~x+1)
summary(model)

# Attempt to generate predictions in source dataframe but am unable to.
df$y_ip<-predict.lm(testy)

Error in `$<-.data.frame`(`*tmp*`, y_ip, value = c(221.............
  replacement has 9 rows, data has 10

I got around this problem by generating the predictions using algebra, df$y<-B0+ B1*df$x, or  generating the predictions by calling the coefficients of the model df$y<-((summary(model)$coefficients[1, 1]) + (summary(model)$coefficients[2, 1]*(df$x)) ; however, I am now working with a big data model with hundreds of coefficients, and these methods are no longer practical. I'd like to know how to do it using the predict function.

Thank you in advance for your assistance!

Body:
Actually, you are not using correctly the predict.lm function.
Either way you have to input the model itself as its first argument, hereby model, with or without the new data. Without the new data, it will only predict on the training data, thus excluding your NA row and you need this workaround to fit the initial data.frame:

df$y_ip[!is.na(df$y)] <- predict.lm(model)

Or explicitly specifying some new data. Since the new x has one more row than the training x it will fill the missing row with a new prediction:

df$y_ip <- predict.lm(model, newdata = df)


来源: stackexchange

问:
Why is .insert not adding entry text into array (Python)
This part of my code is the problem: I want to add names to Name_List by entering text into the entry widget. Then use the "add" button to insert the item into Name_List by the function add_name.

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

Name_List = []

...

class NamePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        name=StringVar()
        name_entry= tk.Entry(self, text="Enter name:", textvariable=name)
        name_entry.pack()
        add_button= tk.Button(self, text="Add",
                              command=lambda: self.add_name(name))
        add_button.pack()
        To_Role_List= tk.Button(self, text="Assign Roles",
                                command=lambda: self.print_namelist())
        To_Role_List.pack()

    def add_name(self,name,i=0):
        Name_List.insert(i, name)
        print(Name_List)
        i+=1

    def print_namelist(self):
        for i in [0,len(Name_List)]:
            print (Name_List[i])

app=TOS_outline()
app.mainloop()
</code>```

My result, after entering the name "Alpha" into the Entry widget, appears to be this (using print of course):

```<code>[<tkinter.StringVar object at 0x03E7D650>]
</code>```

What do I need to change/fix?

答:
If you want to use a python list, dont use a counter or range like:

```<code>def add_name(self,name,i=0):
    Name_List.insert(i, name)
    print(Name_List)
    i+=1

def print_namelist(self):
    for i in [0,len(Name_List)]:
        print (Name_List[i])
</code>```

instead use:

```<code>def add_name(self,name):
    Name_List.append(name)
    print(Name_List)

def print_namelist(self):
    for name in Name_List:
        print (name)
</code>```

And use get() to obtain the value of the StringVar object

```<code>nombre = StringVar()
id_art = IntVar()
nombre.set("Python para impacientes")
id_art.set(1)
blog = ttk.Entry(ventana, textvariable=nombre, width=25)
arti = ttk.Label(ventana, textvariable=id_art)
print('Blog:', nombre.get())
print('Id artículo:', id_art.get())
</code>```

Example from: http://python-para-impacientes.blogspot.com.es/2016/02/variables-de-control-en-tkinter.html (Spanish)

ContentLicense: CC BY-SA 3.0

Body:
This part of my code is the problem: I want to add names to Name_List by entering text into the entry widget. Then use the "add" button to insert the item into Name_List by the function add_name.

import tkinter as tk
from tkinter import *

Name_List = []

...

class NamePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        name=StringVar()
        name_entry= tk.Entry(self, text="Enter name:", textvariable=name)
        name_entry.pack()
        add_button= tk.Button(self, text="Add",
                              command=lambda: self.add_name(name))
        add_button.pack()
        To_Role_List= tk.Button(self, text="Assign Roles",
                                command=lambda: self.print_namelist())
        To_Role_List.pack()

    def add_name(self,name,i=0):
        Name_List.insert(i, name)
        print(Name_List)
        i+=1

    def print_namelist(self):
        for i in [0,len(Name_List)]:
            print (Name_List[i])

app=TOS_outline()
app.mainloop()

My result, after entering the name "Alpha" into the Entry widget, appears to be this (using print of course):

[<tkinter.StringVar object at 0x03E7D650>]

What do I need to change/fix?

Body:
If you want to use a python list, dont use a counter or range like:

def add_name(self,name,i=0):
    Name_List.insert(i, name)
    print(Name_List)
    i+=1

def print_namelist(self):
    for i in [0,len(Name_List)]:
        print (Name_List[i])

instead use:

def add_name(self,name):
    Name_List.append(name)
    print(Name_List)

def print_namelist(self):
    for name in Name_List:
        print (name)

And use get() to obtain the value of the StringVar object

nombre = StringVar()
id_art = IntVar()
nombre.set("Python para impacientes")
id_art.set(1)
blog = ttk.Entry(ventana, textvariable=nombre, width=25)
arti = ttk.Label(ventana, textvariable=id_art)
print('Blog:', nombre.get())
print('Id artículo:', id_art.get())

Example from: http://python-para-impacientes.blogspot.com.es/2016/02/variables-de-control-en-tkinter.html (Spanish)


问:
Unable to read/write files in shared hosting (hostgator)
I have developed MVC 5 project it works fine on local file server and on other hostings like (dhosting, Go daddy) but when i upload it to shared hosting(hostgator) it throws an security exception i.e.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

when i add <trust level="Full" /> the error changes to Configuration Error i.e.

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: This configuration section cannot be used at this path.  This happens when the site administrator has locked access to this section using  from an inherited configuration file.

Source Error: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

Is there any way to resolve this issue or should i talk to the hosting provider to provide full trust ?

答:
The trick is working all in the memory, in my case I'm creating a Excel File using the EPPlus Library</p>

```<code>        var stream = new MemoryStream(package.GetAsByteArray());

        Response.AppendHeader("content-disposition", "attachment; filename=MyFile.xlsx");
        Response.ContentType = "application/octet-stream";
        Response.BinaryWrite(stream.ToArray());
        Response.End();
</code>```

Body:
The trick is working all in the memory, in my case I'm creating a Excel File using the EPPlus Library

        var stream = new MemoryStream(package.GetAsByteArray());

        Response.AppendHeader("content-disposition", "attachment; filename=MyFile.xlsx");
        Response.ContentType = "application/octet-stream";
        Response.BinaryWrite(stream.ToArray());
        Response.End();


问:
Why is javascript looping through elements but executing jQuery function on all of them simultaneously?
I have a text "HELLO" and I want to loop through every letter and animate it so it fades in and out.Here's my code.

EDIT: I put the answer in the snippet to see it in action.

Code:

$(document).ready(function() {
  var $letters = $('p[id^="letter-"');
  $letters.each(function(index) {
    $(this).css({
      'animation': 'pulse 500ms ' + index * 500 + 'ms' + ' linear'
    })
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}</code>```

H

E

L

L

O
```

And here's a link to a pen.
Instead of doing the animation one letter at a time, it's animating the whole thing at once.How can this be fixed? Shouldn't a loop finish executing all the commands and then move on to the next step? Maybe there's a better approach to this that I don't know of?

答:
Use animation-delay in combination with your loop variable:

$(document).ready(function() {
  for (var i = 0; i < 5; i++) {
    $('#' + i).css({
      'animation': 'pulse 0.5s linear',
      'animation-delay': i + 's'
    })
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}</code>```

H

E

L

L

O
```

ContentLicense: CC BY-SA 4.0

Body:
I have a text "HELLO" and I want to loop through every letter and animate it so it fades in and out.Here's my code.

EDIT: I put the answer in the snippet to see it in action.

Code:

$(document).ready(function() {
  var $letters = $('p[id^="letter-"');
  $letters.each(function(index) {
    $(this).css({
      'animation': 'pulse 500ms ' + index * 500 + 'ms' + ' linear'
    })
  });
});

html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}

H

E

L

L

O

And here's a link to a pen.
Instead of doing the animation one letter at a time, it's animating the whole thing at once.How can this be fixed? Shouldn't a loop finish executing all the commands and then move on to the next step? Maybe there's a better approach to this that I don't know of?

Body:
Use animation-delay in combination with your loop variable:

$(document).ready(function() {
  for (var i = 0; i < 5; i++) {
    $('#' + i).css({
      'animation': 'pulse 0.5s linear',
      'animation-delay': i + 's'
    })
  }
});

html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='0'>H</p>
<p id='1'>E</p>
<p id='2'>L</p>
<p id='3'>L</p>
<p id='4'>O</p>


问:
Using Ringtone to detect near and far of a Proximity sensor in android
In my app, I have to play a sound as long as the hand is near the proximity sensor and stop the sound when it is far from the sensor. This is the snippet of the code I use.

```<code>public void onSensorChanged(SensorEvent event) {
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),notification);

    if (event.values[0] == 0) {
          r.play();
    }

   else{
        r.stop();
    }
}
</code>```

But my app doesn't work as expected. Even if I move my hand away from the sensor, the ringtone would stop only after it has fully played.

I am new to android programming. So I wasn't able to rectify the errors through the info I get from google search. If the logic is wrong, please tell an other way to do this. Thanks in advance.

答: You are calling r.stop(); while r is null. You say r = in the if block, and that's why that part of the code works. But whenever you enter the else instead of the if, r is null and your program crashes.

Body:
In my app, I have to play a sound as long as the hand is near the proximity sensor and stop the sound when it is far from the sensor. This is the snippet of the code I use.

public void onSensorChanged(SensorEvent event) {
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),notification);

    if (event.values[0] == 0) {
          r.play();
    }

   else{
        r.stop();
    }
}

But my app doesn't work as expected. Even if I move my hand away from the sensor, the ringtone would stop only after it has fully played.

I am new to android programming. So I wasn't able to rectify the errors through the info I get from google search. If the logic is wrong, please tell an other way to do this. Thanks in advance.


问:
Unable to compile downloaded binaries when executing elm-test
I am unable to run my unit tests via the command line:

```<code>elm-test
</code>```

PS C:\my_path\client> elm-test Downloading binaries from
  https://dl.bintray.com/elmlang/elm-test/0.18.6/win32-x64.tar.gz
  Compilation failed for
  C:\my_path\client\elm-stuff\generated-code\elm-community\elm-test\src\Mainc5862d6
  a0878fab784555034eda0ebc7.elm

Note:
I'm not sure if this is a bug on the package or if it's within my control.

答:
Unluckily for you, you've got elm-test@0.18.6, which had a few bugs in it.

The latest version should fix the issue.

Body:
I am unable to run my unit tests via the command line:

elm-test

PS C:\my_path\client> elm-test Downloading binaries from
  https://dl.bintray.com/elmlang/elm-test/0.18.6/win32-x64.tar.gz
  Compilation failed for
  C:\my_path\client\elm-stuff\generated-code\elm-community\elm-test\src\Mainc5862d6
  a0878fab784555034eda0ebc7.elm

Note:
I'm not sure if this is a bug on the package or if it's within my control.


问:
Python Beautiful Soup cannot find table
I have a web scraping code that cannot find a table.
My code looks like:

```<code>site = 'http://etfdb.com/compare/market-cap/'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site, headers=hdr)
page = urlopen(req)
soup = BeautifulSoup(page)
table = soup.find('table', {"class":"table mm-mobile-table table-striped
table-bordered"})
</code>```

The tables HTML looks like:

```<code><table class="table mm-mobile-table table-striped table-bordered" data-
icons-prefix="fa" data-icons="{"columns":"fa-th"}" data-
striped="true" data-toggle="table">
</code>```

but for some reason my code always returns table as none. I do not know why but any help would be appreciated. Thanks.

答:
You need to specify what exactly you want to parse

```<code>soup = BeautifulSoup(page, 'html.parser')
</code>```

Then you can very well verify if it parsed properly

```<code>print(soup.prettify())
</code>```

Title: Python Beautiful Soup cannot find table

Body:
I have a web scraping code that cannot find a table.
My code looks like:

site = 'http://etfdb.com/compare/market-cap/'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site, headers=hdr)
page = urlopen(req)
soup = BeautifulSoup(page)
table = soup.find('table', {"class":"table mm-mobile-table table-striped
table-bordered"})

The tables HTML looks like:

but for some reason my code always returns table as none. I do not know why but any help would be appreciated. Thanks.

Body:
You need to specify what exactly you want to parse

soup = BeautifulSoup(page, 'html.parser')

Then you can very well verify if it parsed properly

print(soup.prettify())


问:
How does an audio converter work?
I currently have the idea to code a small audio converter (e.g. FLAC to MP3 or m4a format) application in C# or Python but my problem is I do not know at all how audio conversion works.

After a research, I heard about Analog-to-digital / Digital-to-analog converter but I guess it would be a Digital-to-digital or something like that isn't it ?

If someone could precisely explain how it works, it would be greatly appreciated.

Thanks.

答:
digital audio is called PCM which is the raw audio format fundamental to any audio processing system ... its uncompressed ... just a series of integers representing the height of the audio curve for each sample of the curve (the Y axis where time is the X axis along this curve)

... this PCM audio can be compressed using some codec then bundled inside a container often together with video or meta data channels ... so to convert audio from A to B you would first need to understand the container spec as well as the compressed audio codec so you can decompress audio A into PCM format ... then do the reverse ... compress the PCM into codec of B then bundle it into the container of B

Before venturing further into this I suggest you master the art of WAVE audio files ... beauty of WAVE is that its just a 44 byte header followed by the uncompressed integers of the audio curve ... write some code to read a WAVE file then parse the header (identify bit depth, sample rate, channel count, endianness) to enable you to iterate across each audio sample for each channel ... prove that its working by sending your bytes into an output WAVE file ... diff input WAVE against output WAVE as they should be identical ... once mastered you are ready to venture into your above stated goal ... do not skip over groking notion of interleaving stereo audio as well as spreading out a single audio sample which has a bit depth of 16 bits across two bytes of storage and the reverse namely stitching together multiple bytes into a single integer with a bit depth of 16, 24 or even 32 bits while keeping endianness squared away ... this may sound scary at first however all necessary details are on the net as its how I taught myself this level of detail

modern audio compression algorithms leverage knowledge of how people perceive sound to discard information which is indiscernible ( lossy ) as opposed to lossless algorithms which retain all the informational load of the source ... opus (http://opus-codec.org/) is a current favorite codec untainted by patents and is open source

Title: How does an audio converter work?


问:
Not getting fields from GetType().GetFields with BindingFlag.Default
I am using the Reflection classes in order to get all the fields inside a certain object.
My problem however is that it works perfectly when the fields are inside a normal class, like:

```<code>class test
{
   string test1 = string.Empty;
   string test2 = string.Empty;
}
</code>```

Here i get both test1 and test2, my problem is that i use abstraction and thus several classes combined.

I got something like:

```<code>class test3 : test2
{
   string test4 = string.Empty;
   string test5 = string.Empty;
}

class test2 : test1
{
   string test2 = string.Empty;
   string test3 = string.Empty;
}
class test1
{
   string test0 = string.Empty;
   string test1 = string.Empty;
}
</code>```

But when I run it, I don't get the fields back from the GetType().GetFields(BindingFlag.Default).

Everyone of those fields also have a property, get; set; attached to it.
When I run the code, I get the properties all the way back to test1 but not the actual fields.

This is the code that I'm trying to get the fields with:

```<code>FieldInfo[] fields = Obj.GetType().GetFields(BindingFlags.Default);
foreach (FieldInfo field in fields)
</code>```

I have also tried:

```<code>FieldInfo[] fields = Obj.GetType().GetFields(BindingFlags.Public
                                             | BindingFlags.Instance
                                             | BindingFlags.NonPublic
                                             | BindingFlags.Static);
</code>```

I use the same code for the properties:

```<code>PropertyInfo[] properties = Obj.GetType().GetProperties(BindingFlags.Public
                                             | BindingFlags.Instance
                                             | BindingFlags.NonPublic
                                             | BindingFlags.Static);

foreach (PropertyInfo property in properties)
</code>```

Any ideas why I get the properties from the abstracted classes but not the fields?

答:
Enumeration of all type fields including private members from base classes.</p>

```<code>public static IEnumerable<FieldInfo> EnumerateFields(this Type type, BindingFlags flags) =>
   type.BaseType?.EnumerateFields(flags)
       .Concat(type.GetFields(flags | BindingFlags.DeclaredOnly)) ??
   type.EnumerateFields(flags);
</code>```

Body:
I am using the Reflection classes in order to get all the fields inside a certain object.
My problem however is that it works perfectly when the fields are inside a normal class, like:

class test
{
   string test1 = string.Empty;
   string test2 = string.Empty;
}

Here i get both test1 and test2, my problem is that i use abstraction and thus several classes combined.

I got something like:

class test3 : test2
{
   string test4 = string.Empty;
   string test5 = string.Empty;
}

class test2 : test1
{
   string test2 = string.Empty;
   string test3 = string.Empty;
}
class test1
{
   string test0 = string.Empty;
   string test1 = string.Empty;
}

But when I run it, I don't get the fields back from the GetType().GetFields(BindingFlag.Default).

Everyone of those fields also have a property, get; set; attached to it.
When I run the code, I get the properties all the way back to test1 but not the actual fields.

This is the code that I'm trying to get the fields with:

FieldInfo[] fields = Obj.GetType().GetFields(BindingFlags.Default);
foreach (FieldInfo field in fields)

I have also tried:

FieldInfo[] fields = Obj.GetType().GetFields(BindingFlags.Public
                                             | BindingFlags.Instance
                                             | BindingFlags.NonPublic
                                             | BindingFlags.Static);

I use the same code for the properties:

PropertyInfo[] properties = Obj.GetType().GetProperties(BindingFlags.Public
                                             | BindingFlags.Instance
                                             | BindingFlags.NonPublic
                                             | BindingFlags.Static);

foreach (PropertyInfo property in properties)

Any ideas why I get the properties from the abstracted classes but not the fields?

Body:
Enumeration of all type fields including private members from base classes.

public static IEnumerable<FieldInfo> EnumerateFields(this Type type, BindingFlags flags) =>
   type.BaseType?.EnumerateFields(flags)
       .Concat(type.GetFields(flags | BindingFlags.DeclaredOnly)) ??
   type.EnumerateFields(flags);


问:
where to init another class in NSObject class?
alright, guys:

I met a problem during communicating between two classes,
the ViewControllerClass MyViewController calls a method changeViewBackgroundColor from a NSObjectClass Assistant

here is the method:

in Assistant.h

```<code>@interface Assistant : NSObject {

 MyViewControllere *myViewController;
</code>```

in Assistant.m

```<code>- (void)changeViewBackgroundColor:(id)sender
{
    myViewController.myView.backgroundColor = [UIColor whiteColor];
}
</code>```

but i know this not gonna work, i need to myViewController = [[MyViewController alloc] init] the myViewController, the super class of Assistant, there is no place to implement it, if i implement in the changeViewBackgroundColor method, it be a little too late, there are several methods in this Assistant class, they all need myViewController = [[MyViewController alloc] init], question is where i'm gonna put this init call?

答:
override the init method and in init method create the object of myViewcontroller  . like

```<code> -(void)init {
              if(self=[super init]){
                 //create the object for my view controller
               }
   return self;
}
</code>```

i am still not sure for what purpose u using Assistant class....

ContentLicense: CC BY-SA 2.5

Body:
alright, guys:

I met a problem during communicating between two classes,
the ViewControllerClass MyViewController calls a method changeViewBackgroundColor from a NSObjectClass Assistant

here is the method:

in Assistant.h

@interface Assistant : NSObject {

 MyViewControllere *myViewController;

in Assistant.m

- (void)changeViewBackgroundColor:(id)sender
{
    myViewController.myView.backgroundColor = [UIColor whiteColor];
}

but i know this not gonna work, i need to myViewController = [[MyViewController alloc] init] the myViewController, the super class of Assistant, there is no place to implement it, if i implement in the changeViewBackgroundColor method, it be a little too late, there are several methods in this Assistant class, they all need myViewController = [[MyViewController alloc] init], question is where i'm gonna put this init call?

Body:
override the init method and in init method create the object of myViewcontroller  . like

 -(void)init {
              if(self=[super init]){
                 //create the object for my view controller
               }
   return self;
}

i am still not sure for what purpose u using Assistant class....


问:
Scroll to UITableViewCell from String
I want to automatically scroll to a UITableViewCell. I know how to do this by the row number like

```<code>var indexPath = NSIndexPath(forRow: numberOfRowYouWant, inSection: 0)
self.tableview.scrollToRowAtIndexPath(indexPath,
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
</code>```

But, I want to scroll to the cell that equals a string. I have a struct

```<code>struct Song {
    var title: String
    var artist: String
}

var songs: [Song] = [
    Song(title: "Title 1", artist "Artist 1"),
    Song(title: "Title 2", artist "Artist 2"),
    Song(title: "Title 3", artist "Artist 3"),
]
</code>```

And the UITableViewCell's title is equal to the title and the subtitle is equal to the artist. Whenever a user taps on a UIButton, I want it to scroll to the cell that is Song(title: "Title 3", artist "Artist 3"). How would I do this?

答:
Add a property to your Song class like this:

```<code>struct Song {
var title: String
var artist: String
var idOrder: Int
}
</code>```

Then you have to order your songs in your list by idOrder. idOrder is also your row's number and so you can use your code:

```<code>    var indexPath = NSIndexPath(forRow: numberOfRowYouWant, inSection: 0)
    self.tableview.scrollToRowAtIndexPath(song.idOrder,
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
</code>```

Title: Scroll to UITableViewCell from String

Body:
I want to automatically scroll to a UITableViewCell. I know how to do this by the row number like

var indexPath = NSIndexPath(forRow: numberOfRowYouWant, inSection: 0)
self.tableview.scrollToRowAtIndexPath(indexPath,
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)

But, I want to scroll to the cell that equals a string. I have a struct

struct Song {
    var title: String
    var artist: String
}

var songs: [Song] = [
    Song(title: "Title 1", artist "Artist 1"),
    Song(title: "Title 2", artist "Artist 2"),
    Song(title: "Title 3", artist "Artist 3"),
]

And the UITableViewCell's title is equal to the title and the subtitle is equal to the artist. Whenever a user taps on a UIButton, I want it to scroll to the cell that is Song(title: "Title 3", artist "Artist 3"). How would I do this?

Body:
Add a property to your Song class like this:

struct Song {
var title: String
var artist: String
var idOrder: Int
}

Then you have to order your songs in your list by idOrder. idOrder is also your row's number and so you can use your code:

    var indexPath = NSIndexPath(forRow: numberOfRowYouWant, inSection: 0)
    self.tableview.scrollToRowAtIndexPath(song.idOrder,
               atScrollPosition: UITableViewScrollPosition.Middle, animated: true)


问:
I want to know what exactly sys.exit(-1) returns in python?
My code goes like this:

```<code>if (not Y):
    print ("Can't print")
    sys.exit(-1)
</code>```

I am unable to understand what does the argument (-1) returns?

答: sys.exit(-1) tells the program to quit. It basically just stops the python code from continuing execution. -1 is just the status code that is passed in. Generally 0 denotes successful execution, any other number (usually 1) means something broke.

Body:
My code goes like this:

if (not Y):
    print ("Can't print")
    sys.exit(-1)

I am unable to understand what does the argument (-1) returns?


问:
Changing font color of UIBarButtonItem
I tried to change the font color of the right bar button item to purple, but it still shows up as white. I've consulted this question and this question. How do I fix this?

Code

```<code>let sortButton = UIButton(frame: CGRect(x: 0, y: 0, width: 34, height: 15))
    sortButton.setTitle("SORT", for: .normal)
    sortButton.titleLabel?.tintColor = UIColor.myMusicPurple
    sortButton.tintColor = UIColor.myMusicPurple
    navigationItem.rightBarButtonItem =  UIBarButtonItem(customView: sortButton)
    navigationItem.rightBarButtonItem?.tintColor = UIColor.myMusicPurple
</code>```

答:
This should do the trick (if you have plain text)</p>

```<code>let rightBarButtonItem = UIBarButtonItem(title: "Some text", style: .plain, target: self, action: #selector(someAction))
rightBarButtonItem.tintColor = UIColor.myMusicPurple

navigationItem.rightBarButtonItem = rightBarButtonItem
</code>```

Title: Changing font color of UIBarButtonItem

Body:
I tried to change the font color of the right bar button item to purple, but it still shows up as white. I've consulted this question and this question. How do I fix this?

Code

let sortButton = UIButton(frame: CGRect(x: 0, y: 0, width: 34, height: 15))
    sortButton.setTitle("SORT", for: .normal)
    sortButton.titleLabel?.tintColor = UIColor.myMusicPurple
    sortButton.tintColor = UIColor.myMusicPurple
    navigationItem.rightBarButtonItem =  UIBarButtonItem(customView: sortButton)
    navigationItem.rightBarButtonItem?.tintColor = UIColor.myMusicPurple

Body:
This should do the trick (if you have plain text)

let rightBarButtonItem = UIBarButtonItem(title: "Some text", style: .plain, target: self, action: #selector(someAction))
rightBarButtonItem.tintColor = UIColor.myMusicPurple

navigationItem.rightBarButtonItem = rightBarButtonItem


问:
How to test api calls using fetch
I can't find a definitive answer on what the proper way to unit test fetch is online. I'm using the create-react-app build. so far this is the closest I've found where a user recommends using nock & node-fetch. I have seen some development on a library here: https://github.com/wheresrhys/fetch-mock but it's build is failing which makes me nervous.

Goal is to make this play nicely with jest

Does anyone have any recommendations from experience on the best way to test request using the fetch api?

答:
You should use fetch-mock like you linked to test the new fetch api calls.

The fact that the build is failing means absolutely nothing to you. This is just for the devs to know when committing to github for continuous development. When you use npm i --save-dev fetch-mock it will download a (hopefully) working release version that the github author specifically publishes, not the failing build.

Example from my project for a redux thunk action:

```<code>import expect from 'expect';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';

import * as actions from './formActions';

const mockStore = configureStore([thunk]);
const store = mockStore({});
const body = {
  email: 'test@gmail.com',
};

describe('registerFormActions', () => {
  let calledActions;

  beforeEach(() => {
    store.clearActions();
    calledActions = store.getActions();
  });

  afterEach(() => {
    fetchMock.reset().restore();
  });

  it('should post form', () => {
    fetchMock.postOnce('/account/register', body);

    store.dispatch(actions.submit()).then(() => {
      expect(fetchMock.called('/account/register')).toBe(true);
    });
  });
});

export const submit = formData => dispatch =>
fetch('/account/register', {
  method: 'post',
  body: formData,
  credentials: 'same-origin',
}).then((response) => {
  if (response.ok) {
     // Do something cool
  }
});
</code>```

Title: How to test api calls using fetch

Body:
You should use fetch-mock like you linked to test the new fetch api calls.

The fact that the build is failing means absolutely nothing to you. This is just for the devs to know when committing to github for continuous development. When you use npm i --save-dev fetch-mock it will download a (hopefully) working release version that the github author specifically publishes, not the failing build.

Example from my project for a redux thunk action:

import expect from 'expect';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';

import * as actions from './formActions';

const mockStore = configureStore([thunk]);
const store = mockStore({});
const body = {
  email: 'test@gmail.com',
};

describe('registerFormActions', () => {
  let calledActions;

  beforeEach(() => {
    store.clearActions();
    calledActions = store.getActions();
  });

  afterEach(() => {
    fetchMock.reset().restore();
  });

  it('should post form', () => {
    fetchMock.postOnce('/account/register', body);

    store.dispatch(actions.submit()).then(() => {
      expect(fetchMock.called('/account/register')).toBe(true);
    });
  });
});

export const submit = formData => dispatch =>
fetch('/account/register', {
  method: 'post',
  body: formData,
  credentials: 'same-origin',
}).then((response) => {
  if (response.ok) {
     // Do something cool
  }
});


问:
Error when pushing Rails App to Heroku
I've been walking through railstutorial.org trying to deploy my first rails app and have been banging my head trying to figure out all the setup stuff.  This should all really be a one-click thing, update to newest ruby/newest rails, setup git and you're good to go, but it's a HUGE headache.  Sorry I had to vent.

My error comes when I try to push to heroku while I'm in the current directory of my test app first_app:

```<code>XXXXXX-Computer:first_app XXXXXX$ git push heroku master
fatal: The remote end hung up unexpectedly
</code>```

Searching the error led me to https://git.wiki.kernel.org/index.php/GitFaq#Git_push_fails_with_.22fatal:_The_remote_end_hung_up_unexpectedly.22.3F
which suggests that my public key may not be installed correctly.  I have been able to push to a git repo fine and checking my heroku keys spits out my public key as expected:

```<code>XXXXXX-Computer:first_app XXXXXX$ heroku keys
=== 1 key for XXXXXX@gmail.com
ssh-rsa AAAAB3NzaC...u4iGALvQ== XXXXXX@gmail.com
</code>```

My only deviation from the tutorial is that I'm using ruby 1.8.7/rails 3.03 because I was having some trouble with ruby version manager rvm.  I could update ruby to 1.9.2, but when I went to check the rails version, I got this:

```<code>XXXXXX-Computer:first_app XXXXXX$ rails -v
/Library/Ruby/Site/1.8/rubygems.rb:779:in `report_activate_error': Could not find RubyGem rails (>= 0) (Gem::LoadError)
</code>```

from /Library/Ruby/Site/1.8/rubygems.rb:214:in activate'
 from /Library/Ruby/Site/1.8/rubygems.rb:1082:ingem'
 from /usr/bin/rails:18

This is my first time using git and rvm as well, so I apologize if it's a basic question.  I've been trying at this for a while and haven't been making that much progress for what should be a simple thing.  I really appreciate any help the collective genius of stackoverflow can offer.  Thank you in advance.

答:
Heroku would tell you if it were a key issue. That error sounds more like a git/network issue.

Heroku occasionally has issues with pushing, which you can monitor here: http://status.heroku.com/. When it happens, all you can do is wait and try again later.

It could also be your config for the heroku remote. Could you post the output of git remote show heroku to be sure?

As for upgrading, it shouldn't affect you here. Gems are specific to the version of ruby you installed them for so if you upgrade to 1.9 you'll have to reinstall your gems. That's why rails had an error on 1.9.

Title: Error when pushing Rails App to Heroku

Body:
I've been walking through railstutorial.org trying to deploy my first rails app and have been banging my head trying to figure out all the setup stuff.  This should all really be a one-click thing, update to newest ruby/newest rails, setup git and you're good to go, but it's a HUGE headache.  Sorry I had to vent.

My error comes when I try to push to heroku while I'm in the current directory of my test app first_app:

XXXXXX-Computer:first_app XXXXXX$ git push heroku master
fatal: The remote end hung up unexpectedly

Searching the error led me to https://git.wiki.kernel.org/index.php/GitFaq#Git_push_fails_with_.22fatal:_The_remote_end_hung_up_unexpectedly.22.3F
which suggests that my public key may not be installed correctly.  I have been able to push to a git repo fine and checking my heroku keys spits out my public key as expected:

XXXXXX-Computer:first_app XXXXXX$ heroku keys
=== 1 key for XXXXXX@gmail.com
ssh-rsa AAAAB3NzaC...u4iGALvQ== XXXXXX@gmail.com

My only deviation from the tutorial is that I'm using ruby 1.8.7/rails 3.03 because I was having some trouble with ruby version manager rvm.  I could update ruby to 1.9.2, but when I went to check the rails version, I got this:

XXXXXX-Computer:first_app XXXXXX$ rails -v
/Library/Ruby/Site/1.8/rubygems.rb:779:in `report_activate_error': Could not find RubyGem rails (>= 0) (Gem::LoadError)

from /Library/Ruby/Site/1.8/rubygems.rb:214:in activate'
 from /Library/Ruby/Site/1.8/rubygems.rb:1082:ingem'
 from /usr/bin/rails:18

This is my first time using git and rvm as well, so I apologize if it's a basic question.  I've been trying at this for a while and haven't been making that much progress for what should be a simple thing.  I really appreciate any help the collective genius of stackoverflow can offer.  Thank you in advance.


问:
How to have user input index selection of object in list with specific criteria
I am trying to figure out how to have a user input the index number of an object in a list. My ultimate goal is to show a list of the spells in your spell book sorted by index number. I then want the user to be able to input the index number to choose the spell and perform a function with it. Here is a simple example:

(The spells are objects)

```<code>spells = [spell1(), spell2()]
print(spells.index(Spell),Spell.name)
</code>```

Should show:

```<code>0 spell1

1 spell2

x = input('Input number of spell')
print(spells[int(x)].description)
</code>```

So, by inputting the index number of the object in the list I retrieved its description. I have gotten the function itself to work. However, I am having difficulty setting up rules so that it does not accept any input other than the available indexes in the list. In this example, only 0 and 1 should be available inputs. I also wanted the option of 'p' to go back to the previous screen.

答:
So you've got two conditions that need to pass: x must a valid number and it must be within the bounds of your spell list.

You can wrap this in whatever control flow suits your application. For example, you could re-prompt the user until they give a valid input:

```<code>def validate_spell_index(spell_list, i):
    return i.isdigit() and int(i) in range(len(spell_list))

x = input('Spell index> ')
while not validate_spell_index(spells, x):
    print('Please give a number between 0 and {}.'.format(len(spells) - 1))
    x = input('Spell index> ')

print(spells[int(x)].description)
</code>```

demo (I aplogize for any mispelled spells)

Body:
I am trying to figure out how to have a user input the index number of an object in a list. My ultimate goal is to show a list of the spells in your spell book sorted by index number. I then want the user to be able to input the index number to choose the spell and perform a function with it. Here is a simple example:

(The spells are objects)

spells = [spell1(), spell2()]
print(spells.index(Spell),Spell.name)

Should show:

0 spell1

1 spell2

x = input('Input number of spell')
print(spells[int(x)].description)

So, by inputting the index number of the object in the list I retrieved its description. I have gotten the function itself to work. However, I am having difficulty setting up rules so that it does not accept any input other than the available indexes in the list. In this example, only 0 and 1 should be available inputs. I also wanted the option of 'p' to go back to the previous screen.

Body:
So you've got two conditions that need to pass: x must a valid number and it must be within the bounds of your spell list.

You can wrap this in whatever control flow suits your application. For example, you could re-prompt the user until they give a valid input:

def validate_spell_index(spell_list, i):
    return i.isdigit() and int(i) in range(len(spell_list))

x = input('Spell index> ')
while not validate_spell_index(spells, x):
    print('Please give a number between 0 and {}.'.format(len(spells) - 1))
    x = input('Spell index> ')

print(spells[int(x)].description)

demo (I aplogize for any mispelled spells)


答:
What about using:

```<code>func setTitleColor(UIColor?, for: UIControlState)
</code>```

Documentation says it sets the color of the title to use for the specified state.

```<code>sortButton.setTitleColor( .red, for: .normal)
</code>```

Title: Changing font color of UIBarButtonItem

Body:
What about using:

func setTitleColor(UIColor?, for: UIControlState)

Documentation says it sets the color of the title to use for the specified state.

sortButton.setTitleColor( .red, for: .normal)


问:
How do I use For...In f{a,b,c,d}c, but with variables?
I'm trying to make a loop in Bash. I tested the loop with for adr in a{a,b,c}d and it works perfectly with aad, abd, acd

But if I have a variable with the value a{a,b,c}d, it doesn't return the above values; instead it runs only once with the value a{a,b,c}d.

How do I enable this?

Alternatively, I'm trying to take an input from the user, and then replace all instances of ~const~ with {b,c,d,f,g...y,z} and then run the loop I described above.

Unfortunately, as I said, it isn't working. Is there any oher way to make this work?

答:
These are some workarounds:

```<code>$ aa=( a{a,b,c}d );for adr in ${aa[@]};do echo "$adr";done #using array
aad
abd
acd

$ aa=$(echo a{a,b,c}d);for adr in ${aa};do echo "$adr";done #without array
aad
abd
acd
</code>```

This is how above can work with variables:

```<code>$ start="a"
$ var1="a"
$ var2="b"
$ var3="c"
$ end="d"
$ aa=$(echo $start{${var1},${var2},${var3}}$end)
$ for adr in $aa;do echo "$adr";done
aad
abd
acd
</code>```

Body:
These are some workarounds:

$ aa=( a{a,b,c}d );for adr in ${aa[@]};do echo "$adr";done #using array
aad
abd
acd

$ aa=$(echo a{a,b,c}d);for adr in ${aa};do echo "$adr";done #without array
aad
abd
acd

This is how above can work with variables:

$ start="a"
$ var1="a"
$ var2="b"
$ var3="c"
$ end="d"
$ aa=$(echo $start{${var1},${var2},${var3}}$end)
$ for adr in $aa;do echo "$adr";done
aad
abd
acd


问:
Invalid UUID String solr
I am using solr to index a very large number of documents. One of my requirements is that each documents needs to have a unique id, which I tried to implement using the Unique Key way. However, when I try using the "post" command to index the documents as normally, I get many

```<code><response>
<lst name="responseHeader"><int name="status">400</int><int name="QTime">15</int></lst><lst name="error"><lst name="metadata"><str name="error-class">org.apache.solr.common.SolrException</str><str name="root-error-class">org.apache.solr.common.SolrException</str></lst><str name="msg">Invalid UUID String: '/Volumes/filePlace/file1.html'</str><int name="code">400</int></lst>
</response>
</code>```

in the output, and no documents are indexed. How do I fix this?

The post command I use is regular syntax:

```<code>post -c NewCore .
</code>```

where . is the current folder containing all the files.

答:
I figured out that my error was that I was indexing rich documents using the post tool included in solr. However, when indexing rich documents such as html with post, the HTTP POST request needs to have literal.id specified to something, otherwise it doesn't run. The post tool automatically sets literal.id to the file location, and since the field id is set to be of type UUID, this causes an error. I have now switched id in the managedschema file to be of type string and decided to use individual post commands such as

```<code>post -c NewCore -params literal.id=55 /Volumes/mainVolume/thingy.html
</code>```

and to assign each rich document an id before it is indexed.

Title: Invalid UUID String solr

Body:
I am using solr to index a very large number of documents. One of my requirements is that each documents needs to have a unique id, which I tried to implement using the Unique Key way. However, when I try using the "post" command to index the documents as normally, I get many

<response>
<lst name="responseHeader"><int name="status">400</int><int name="QTime">15</int></lst><lst name="error"><lst name="metadata"><str name="error-class">org.apache.solr.common.SolrException</str><str name="root-error-class">org.apache.solr.common.SolrException</str></lst><str name="msg">Invalid UUID String: '/Volumes/filePlace/file1.html'</str><int name="code">400</int></lst>
</response>

in the output, and no documents are indexed. How do I fix this?

The post command I use is regular syntax:

post -c NewCore .

where . is the current folder containing all the files.

Body:
I figured out that my error was that I was indexing rich documents using the post tool included in solr. However, when indexing rich documents such as html with post, the HTTP POST request needs to have literal.id specified to something, otherwise it doesn't run. The post tool automatically sets literal.id to the file location, and since the field id is set to be of type UUID, this causes an error. I have now switched id in the managedschema file to be of type string and decided to use individual post commands such as

post -c NewCore -params literal.id=55 /Volumes/mainVolume/thingy.html

and to assign each rich document an id before it is indexed.


问:
CircleCI 4G memory breach - Django migrations
We are using circleci for our Django/Python project. While the test database is being setup as part of TransactionTestCase, the memory shoots up to ~3g and hence breaching the 4g limit of our circle ci environment. I debugged using ssh and found that some tests run in parallel where the 4g limit is breached and hence circle ci build fails.

Is there a good way to reduce the memory footprint while setting up databases for tests?

Any help will be greatly appreciated!

答: I was able to do a mprof using memory_profiler. Disabling migrations brought down the memory usage.</p>


问:
React Jest - import JS module without using require/export
Is it possible to use Jest to test individual JavaScript files without using require/export?

Let's say I want to test abc.js. Here is an example of abc.js:

```<code>(function(){
   return {
       foo: function(){}
   }
})();
</code>```

Now let's say my test file is abc.test.js. I want to test if foo is a function. How would I go on about testing this file without using modules.exports in abc.js and require in abc.test.js?

Thanks in advance

答:
Use a named function, a try/catch block, and an inline assertion to test it with plain Node.js:

```<code>const assert = require('assert');

(function hi(){
  hi.foo = Function;
  try
    {
    assert.ok(typeof hi.foo === 'function', 'Not a function');
    assert.ok(typeof hi.foo === 'string', 'Not a string');
    }
  catch(e)
    {
    console.log(e.message);
    }
  }
)();
</code>```

then run it:

```<code>node foo.js
</code>```

Comment out the test-oriented code to avoid including it in the source file:

```<code>/*const assert = require('assert');*/

(function hi(){
  hi.foo = Function;
  /*
  try
    {
    assert.ok(typeof hi.foo === 'function', 'Not a function');
    assert.ok(typeof hi.foo === 'string', 'Not a string');
    }
  catch(e)
    {
    console.log(e.message);
    }
  */
  }
)();
</code>```

Then remove the comments programmatically and pipe the output to node in a *nix shell:

```<code>cat foo.js | tr -d '/*' | node
</code>```

or Powershell:

```<code>$string = cat foo.js
$string.Split("/*") | node
</code>```

And use Grunt or another tool to strip out comment blocks in the build process.

References

Errors | Node.js v8.1.3 Documentation

Assert | Node.js v8.1.3 Documentation

tr(1) Mac OS X Manual Page

grunt-stripcomments

Using the Split Method in PowerShell – Hey, Scripting Guy! Blog

Extending JavaScript with inline unit tests

When I uncomment one line of code, I receive this error: _http_outgoing.js:359 throw new Error('Can\'t set headers after they are sent.');
https://www.npmjs.com/package/babel-plugin-s2s-jest-unit-test-case

babel-plugin-s2s-jest-unit-test-case - npm

Body:
Is it possible to use Jest to test individual JavaScript files without using require/export?

Let's say I want to test abc.js. Here is an example of abc.js:

(function(){
   return {
       foo: function(){}
   }
})();

Now let's say my test file is abc.test.js. I want to test if foo is a function. How would I go on about testing this file without using modules.exports in abc.js and require in abc.test.js?

Thanks in advance

Body:
Use a named function, a try/catch block, and an inline assertion to test it with plain Node.js:

const assert = require('assert');

(function hi(){
  hi.foo = Function;
  try
    {
    assert.ok(typeof hi.foo === 'function', 'Not a function');
    assert.ok(typeof hi.foo === 'string', 'Not a string');
    }
  catch(e)
    {
    console.log(e.message);
    }
  }
)();

then run it:

node foo.js

Comment out the test-oriented code to avoid including it in the source file:

/*const assert = require('assert');*/

(function hi(){
  hi.foo = Function;
  /*
  try
    {
    assert.ok(typeof hi.foo === 'function', 'Not a function');
    assert.ok(typeof hi.foo === 'string', 'Not a string');
    }
  catch(e)
    {
    console.log(e.message);
    }
  */
  }
)();

Then remove the comments programmatically and pipe the output to node in a *nix shell:

cat foo.js | tr -d '/*' | node

or Powershell:

$string = cat foo.js
$string.Split("/*") | node

And use Grunt or another tool to strip out comment blocks in the build process.

References

Errors | Node.js v8.1.3 Documentation

Assert | Node.js v8.1.3 Documentation

tr(1) Mac OS X Manual Page

grunt-stripcomments

Using the Split Method in PowerShell – Hey, Scripting Guy! Blog

Extending JavaScript with inline unit tests

When I uncomment one line of code, I receive this error: _http_outgoing.js:359 throw new Error('Can\'t set headers after they are sent.');
https://www.npmjs.com/package/babel-plugin-s2s-jest-unit-test-case

babel-plugin-s2s-jest-unit-test-case - npm


问:
Initialize QML-signal before Component.onCompleted
I have the following problem:
I wrote a qml-GUI and an interface class to communicate with some C++ code by connecting signals on the qml-side with slots on the c++ side. The event or button based trigger work fine, but I need one signal that has to be triggerd directly at startup. I tried it by using Component.onCompleted from my ApplicationWindow. Howevery,

the output "setInitDrone() called" is generated but
  getInitDrone() is never reached.
  The QT documentation says:
  "The order of running the onCompleted handlers is undefined."

Can I make sure that the signal has already been initialized when I'm trying to send it, or is there any other method instead of using Component.onCompleted?

Thanks for any help!

main.qml:

```<code>ApplicationWindow{
  id: appWindow
  visible: true
  minimumHeight: 800
  minimumWidth: 700
  visibility: Window.Maximized

  signal setInitDrone()

  Component.onCompleted: {
    setInitDrone()
    print("setInitDrone() called")
  }
}
</code>```

qml_cpp_interface.cpp:

```<code>void Qml_cpp_interface::getInitDrone(){
  qDebug() << "Cpp initDrone received";
  flightserver.init();
}
</code>```

groundstation.cpp:

```<code>QGuiApplication app(argc, argv);

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

//Connect with C++ code
QObject *item = engine.rootObjects().first();
Qml_cpp_interface qml_cpp_interface;

QObject::connect(item, SIGNAL(setInitDrone()), &qml_cpp_interface,SLOT(getInitDrone()));

return app.exec();
</code>```

答:
You are doing it wrong, instead of accessing QML stuff from C++, you should be accessing C++ from QML.

Expose Qml_cpp_interface to QML as it would make sense exposing a core logic interface. Since you are doing initialization, you don't even need a signal, since presumably, you are only going to initialize once, which is what it means to "initialize".

Then you can simply call the initialization via

Component.onCompleted: Qml_cpp_interface.getInitDrone()

Also, I don't see any valid reason to initialize from QML, I mean you can directly initialize from C++, even implicitly from Qml_cpp_interface's constructor. So by the time your GUI loads, you are already initialized.

Body:
I have the following problem:
I wrote a qml-GUI and an interface class to communicate with some C++ code by connecting signals on the qml-side with slots on the c++ side. The event or button based trigger work fine, but I need one signal that has to be triggerd directly at startup. I tried it by using Component.onCompleted from my ApplicationWindow. Howevery,

the output "setInitDrone() called" is generated but
  getInitDrone() is never reached.
  The QT documentation says:
  "The order of running the onCompleted handlers is undefined."

Can I make sure that the signal has already been initialized when I'm trying to send it, or is there any other method instead of using Component.onCompleted?

Thanks for any help!

main.qml:

ApplicationWindow{
  id: appWindow
  visible: true
  minimumHeight: 800
  minimumWidth: 700
  visibility: Window.Maximized

  signal setInitDrone()

  Component.onCompleted: {
    setInitDrone()
    print("setInitDrone() called")
  }
}

qml_cpp_interface.cpp:

void Qml_cpp_interface::getInitDrone(){
  qDebug() << "Cpp initDrone received";
  flightserver.init();
}

groundstation.cpp:

QGuiApplication app(argc, argv);

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

//Connect with C++ code
QObject *item = engine.rootObjects().first();
Qml_cpp_interface qml_cpp_interface;

QObject::connect(item, SIGNAL(setInitDrone()), &qml_cpp_interface,SLOT(getInitDrone()));

return app.exec();


答:
I don't know maybe it's because their code is not well-structured [deliberately] and BeautifulSoup couldn't parse it. But maybe this helps you:

```<code>import re    # to extract table with regex
table_soup = BeautifulSoup( re.findall(r'<table.*>.*</table>', page.read())[0] )
</code>```

Also you can investigate further with something like this:

```<code>for tag in soup.find_all():
   if tag.name == 'div':
      if str(tag).find("table-striped") > -1:
         print repr( str(tag)[:100] )
</code>```

To see which div tags contain the table, if any:

```<code>'<div class="mm-header">\n<div class="container">\n<div class="row">\n<div class="col-xs-12">\n<div class'
'<div class="container">\n<div class="row">\n<div class="col-xs-12">\n<div class="mm-user-links hidden-x'
'<div class="row mm-header-content">\n<div class="col-sm-4 mm-header-logos">\n<button class="navbar-tog'
'<div class="col-sm-4 mm-header-logos">\n<button class="navbar-toggle">\n<span class="fa fa-bars"></spa'
</code>```

So I guess BeautifulSoup couldn't break down the last one into child tags.

Edit:

Sorry I forgot to add page.read() to get page source first, see the second line again.

If you don't want to use regex, you can use a better parser rather than the default one: html5lib

First install it:

# pip install html5lib

The you can use it by:

soup = BeautifulSoup(page, 'html5lib')

Title: Python Beautiful Soup cannot find table

Body:
I have a web scraping code that cannot find a table.
My code looks like:

site = 'http://etfdb.com/compare/market-cap/'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site, headers=hdr)
page = urlopen(req)
soup = BeautifulSoup(page)
table = soup.find('table', {"class":"table mm-mobile-table table-striped
table-bordered"})

The tables HTML looks like:

but for some reason my code always returns table as none. I do not know why but any help would be appreciated. Thanks.

Body:
I don't know maybe it's because their code is not well-structured [deliberately] and BeautifulSoup couldn't parse it. But maybe this helps you:

import re    # to extract table with regex
table_soup = BeautifulSoup( re.findall(r'<table.*>.*</table>', page.read())[0] )

Also you can investigate further with something like this:

for tag in soup.find_all():
   if tag.name == 'div':
      if str(tag).find("table-striped") > -1:
         print repr( str(tag)[:100] )

To see which div tags contain the table, if any:

'<div class="mm-header">\n<div class="container">\n<div class="row">\n<div class="col-xs-12">\n<div class'
'<div class="container">\n<div class="row">\n<div class="col-xs-12">\n<div class="mm-user-links hidden-x'
'<div class="row mm-header-content">\n<div class="col-sm-4 mm-header-logos">\n<button class="navbar-tog'
'<div class="col-sm-4 mm-header-logos">\n<button class="navbar-toggle">\n<span class="fa fa-bars"></spa'

So I guess BeautifulSoup couldn't break down the last one into child tags.

Edit:

Sorry I forgot to add page.read() to get page source first, see the second line again.

If you don't want to use regex, you can use a better parser rather than the default one: html5lib

First install it:

# pip install html5lib

The you can use it by:

soup = BeautifulSoup(page, 'html5lib')


问:
Append selected after ajax call
I have a Select 2 drop down search function. I am trying to load the results from an ajax call as the selected/default values. I am not sure where I am going wrong? What is the syntax I need to change here so that when I click my modal it shows results preset.

```<code>$(document).ready(function() {
  $('.editApptModal-button').click(function() {
    var appointmentID = $(this).attr('data-appointmentID');

    $('#editApptModal').find('input[name="appointmentID"]').val(appointmentID);
    $.ajax({
      type: 'ajax',
      method: 'get',
      url: '/ajax',
      async: false,
      dataType: 'json',
      success: function(response) {

        console.log(JSON.stringify(response));

        $.each(response.employees.data, function(key, value) {
          $('select').append($("<option selected></option>",
            //<HERE Selected is not working.
            //If I remove selected results load in dropdown
            {
              value: value.id,
              text: value.name
            }));
        });

        $('#editApptModal').modal('show');
      },
      error: function(response) {
        alert('Could not displaying data' + response);
      }
    });

    $('#editApptModal').modal('show');
  });
});

<select multiple="multiple" name="employees[]" id="form-field-select-4" class="form-control search-select">
<option selected value=""></option>
</code>```

答:
First you should try to append only once because it's an heavy operation.
And by setting attributes directly seems to work here.

var datas = [
  {value: 'toto', text: 'Toto'},
  {value: 'titi', text: 'Titi'}
];

var options = '';
$.each(datas, function(key, value) {
  options += '<option selected>'+value.text+'</option>';
});

$('#select').append(options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select multiple id="select"></select></code>```

Title: Append selected after ajax call

Body:
I have a Select 2 drop down search function. I am trying to load the results from an ajax call as the selected/default values. I am not sure where I am going wrong? What is the syntax I need to change here so that when I click my modal it shows results preset.

$(document).ready(function() {
  $('.editApptModal-button').click(function() {
    var appointmentID = $(this).attr('data-appointmentID');

    $('#editApptModal').find('input[name="appointmentID"]').val(appointmentID);
    $.ajax({
      type: 'ajax',
      method: 'get',
      url: '/ajax',
      async: false,
      dataType: 'json',
      success: function(response) {

        console.log(JSON.stringify(response));

        $.each(response.employees.data, function(key, value) {
          $('select').append($("<option selected></option>",
            //<HERE Selected is not working.
            //If I remove selected results load in dropdown
            {
              value: value.id,
              text: value.name
            }));
        });

        $('#editApptModal').modal('show');
      },
      error: function(response) {
        alert('Could not displaying data' + response);
      }
    });

    $('#editApptModal').modal('show');
  });
});

<select multiple="multiple" name="employees[]" id="form-field-select-4" class="form-control search-select">
<option selected value=""></option>

Body:
First you should try to append only once because it's an heavy operation.
And by setting attributes directly seems to work here.

var datas = [
  {value: 'toto', text: 'Toto'},
  {value: 'titi', text: 'Titi'}
];

var options = '';
$.each(datas, function(key, value) {
  options += '<option selected>'+value.text+'</option>';
});

$('#select').append(options);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select multiple id="select"></select>


答:
You have to issue the refresh command after you are done. Here a quick snippet of it working doing the same thing for one of my projects. TransportRecord_TransportCarrierID is the ID for my select element.

```<code>                $('#TransportRecord_TransportCarrierID').empty();
                $.each(jsonResponse, function (key, item) {
                    var option = $('<option selected>').text(item.Text).val(item.Value);
                    $('#TransportRecord_TransportCarrierID').append(option);
                });
                $('#TransportRecord_TransportCarrierID').selectpicker('refresh');
</code>```

Html

```<code><select class="form-control selectpicker" data-live-search="true" data-style="btn-defaultWhite" multiple="multiple" id="TransportRecord_TransportCarrierID" name="TransportRecord.TransportCarrierID">//your initial options</select>
</code>```

Title: Append selected after ajax call

Body:
You have to issue the refresh command after you are done. Here a quick snippet of it working doing the same thing for one of my projects. TransportRecord_TransportCarrierID is the ID for my select element.

                $('#TransportRecord_TransportCarrierID').empty();
                $.each(jsonResponse, function (key, item) {
                    var option = $('<option selected>').text(item.Text).val(item.Value);
                    $('#TransportRecord_TransportCarrierID').append(option);
                });
                $('#TransportRecord_TransportCarrierID').selectpicker('refresh');

Html

<select class="form-control selectpicker" data-live-search="true" data-style="btn-defaultWhite" multiple="multiple" id="TransportRecord_TransportCarrierID" name="TransportRecord.TransportCarrierID">//your initial options</select>


问:
Emacs using Common Lisp with cl-lib.el
I have been using ELISP for a while and now I have decided to use Common Lisp using cl-lib.el extension for Emacs. The question is does cl-lib.el provide a complete CLISP extension for Emacs or it partially supports CLISP? The other question, if I include cl-lib.el in one package (I have multiple packages), does that mean the cl-lib.el will also be applied to all other packages? For example, if I have:

```<code>(load "~/elisp/file1.el") ; (require 'cl-lib.el)
(load "~/elisp/file2.el") ; does it automatically use cl-lib.el or not?
</code>```

答:
No; neither cl-lib.el nor cl.el is equivalent to Common Lisp. Not at all.

Once a library has been loaded, it is loaded. If you load file1 and it loads cl-lib, then when you later load file2, cl-lib has already been loaded. All that matters is the order of loading.

Title: Emacs using Common Lisp with cl-lib.el

Body:
I have been using ELISP for a while and now I have decided to use Common Lisp using cl-lib.el extension for Emacs. The question is does cl-lib.el provide a complete CLISP extension for Emacs or it partially supports CLISP? The other question, if I include cl-lib.el in one package (I have multiple packages), does that mean the cl-lib.el will also be applied to all other packages? For example, if I have:

(load "~/elisp/file1.el") ; (require 'cl-lib.el)
(load "~/elisp/file2.el") ; does it automatically use cl-lib.el or not?


问:
Django-Haystack Search based on multiple index fields
I am quite a newbbie with django-haystack. Following documentation and tutorials I was able to create a search App based on document content (DataBase SQLITE). As next step, I have updated my HTML template to request for more info (e.g.: Model, desired DB link, etc.)

I do not know how to approach this. Below the files I am using. My knowledge is still quite basic, so any help would be very much appreciated.

Thanks.

search.html

```<code>{% extends 'base.html' %}

{% block content %}

    <h2> Doc Search Interface</h2>

    <form method="get" action=".">
        <table>
            <P>Select Car Model:</P>
            <P><LABEL ACCESSKEY=5><INPUT TYPE=checkbox NAME="CarModel" VALUE="A5"> A5</LABEL><BR>
            <LABEL ACCESSKEY=8><INPUT TYPE=checkbox NAME="CarModel" VALUE="A8"> A8</LABEL><BR>
            <LABEL ACCESSKEY=3><INPUT TYPE=checkbox NAME="CarModel" VALUE="A3"> A3</LABEL></P>

            <tr>
            <P>Type and click enter for Search!</P>
                <input type="search" id="id_q" name="q" placeholder="Search" >
            </tr>
        </table>

        {% if query %}
            <h3>Let´s see if we have got here the document you were looking for...</h3>

            {% for result in page.object_list %}
                <p>
                    <a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a>
                </p>
            {% empty %}
                <p>No results found.</p>
            {% endfor %}

            {% if page.has_previous or page.has_next %}
                <div>
                    {% if page.has_previous %}<a href="?q={{ query }}&page={{ page.previous_page_number }}">{% endif %}« Previous{% if page.has_previous %}</a>{% endif %}
                    |
                    {% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}Next »{% if page.has_next %}</a>{% endif %}
                </div>
            {% endif %}
        {% else %}
            {# Show some example queries to run, maybe query syntax, something else? #}
        {% endif %}
    </form>
{% endblock %}
</code>```

models.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.template import RequestContext
from django.http import HttpResponse

class Document(models.Model):

user_id = models.CharField(max_length=6, default='admin')
pub_date = models.DateTimeField()
title = models.CharField(max_length=200)
Link= models.URLField()
content = models.TextField()
CarModel= models.TextField()

    def get_absolute_url(self):
        return self.Link
    def __unicode__(self):
        return self.title
</code>```

search_indexes.py

```<code>from haystack import indexes
from test3.models import Document

class DocumentIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, use_template=True)
    content_auto=indexes.EdgeNgramField(model_attr='content')
    CarModel=indexes.EdgeNgramField(model_attr='CarModel')
    def get_model(self):
        return Document
    def index_queryset(self, using=None):
        """Used when the entire index for model is updated. Typically to avoid some results showing when admin do not want to"""
        return self.get_model().objects
</code>```

Following this other post Using django haystack search with global search bar in template I have updated the following files

urls.py

```<code>from django.conf.urls import url
from test3.views import MySearchView

# urls.py

urlpatterns =  [url(r'^/search/?$', MySearchView.as_view(), name='My_search_view'),]
</code>```

views.py

```<code>from haystack.forms import HighlightedSearchForm
from haystack.query import SearchQuerySet
from haystack.generic_views import SearchView
from haystack.views import search_view_factory

class MySearchView(SearchView):
    """My custom search view."""
    def search_posts(request):
        post_type = str(request.GET.get('CarModel')).lower()
        print (str(request.GET.get('CarModel')).lower())
        sqs = SearchQuerySet().filter(CarModel__contains=post_type)
        clean_query = sqs.query.clean(post_type)
        result = sqs.filter(content=clean_query)
        view = search_view_factory(
            view_class=SearchView,
            template='search/search.html',
            searchqueryset=result,
            form_class=HighlightedSearchForm
            )
        return view(request)
</code>```

However, I still did not make it work...Search results are still not filtered by 'Model' field. I guess I have to add extra code, but I do not know where...

答:
I'll try respond to this. This is how I got it working:

In yourapp/urls.py

```<code>url(r'^search/$', views.search_notes, name='search_notes'),
</code>```

In yourapp/views.py import your NotesSearchForm (further below) and call that on search:

```<code>from .forms import NotesSearchForm

def search_notes(request):
   form = NotesSearchForm(request.GET)
   notes = form.search()
   return render_to_response('notes/index.html', {'notes': notes, 'form': form})

   context = { 'latest_notes_list': latest_notes_list}
   return render(request, 'notes/index.html', context)
</code>```

Then in your yourapp/forms.py is where the magic happens:

```<code>from haystack.forms import SearchForm

class NotesSearchForm(SearchForm):

   # First we add the form fields, in your case BooleanFields.
   sports = forms.BooleanField()
   fiction = forms.BooleanField()
   non_fiction = forms.BooleanField()

   def search(self):
      # Here we store the SearchQuerySet received from other processing.
      sqs = super(NotesSearchForm, self).search()

      if not self.is_valid():
         return self.no_query_found()

      # Then filter your results when the search come back

      if self.cleaned_data['sports']:
         sqs = sqs.filter(genre='sports')
      if self.cleaned_data['fiction']:
         sqs = sqs.filter(genre='fiction')
      if self.cleaned_data['non_fiction']:
         sqs = sqs.filter(genre='non_fiction')

      return sqs

   def no_query_found(self):
      # This we add to make all results show if nothing is selected or searched for (optional)
      return self.searchqueryset.all()
</code>```

Note that here I put 'genre' as what the field is named in your model. This field also need to be present in your search_indexes.py, like this:

```<code>genre = indexes.CharField(model_attr='genre')
</code>```

Finally, let me show you the yourapp/templates/notes/index.html:

```<code><!-- Form here -->
{{ form }}

<!-- Search results here -->
{% for note in notes %}

   {{ note.object.title }}
   {{ notes.object.body|linebreaks }}">

{% endfor %}
</code>```

Hope it works for you! Let me know if you get stuck.

Body:
I am quite a newbbie with django-haystack. Following documentation and tutorials I was able to create a search App based on document content (DataBase SQLITE). As next step, I have updated my HTML template to request for more info (e.g.: Model, desired DB link, etc.)

I do not know how to approach this. Below the files I am using. My knowledge is still quite basic, so any help would be very much appreciated.

Thanks.

search.html

{% extends 'base.html' %}

{% block content %}

 Doc Search Interface

    <form method="get" action=".">

Select Car Model:

<INPUT TYPE=checkbox NAME="CarModel" VALUE="A5"> A5

            <INPUT TYPE=checkbox NAME="CarModel" VALUE="A8"> A8

            <INPUT TYPE=checkbox NAME="CarModel" VALUE="A3"> A3

Type and click enter for Search!

                <input type="search" id="id_q" name="q" placeholder="Search" >

        {% if query %}

Let´s see if we have got here the document you were looking for...

            {% for result in page.object_list %}

                    {{ result.object.title }}

            {% empty %}

No results found.

            {% endfor %}

            {% if page.has_previous or page.has_next %}

                    {% if page.has_previous %}{% endif %}« Previous{% if page.has_previous %}{% endif %}
                    |
                    {% if page.has_next %}{% endif %}Next »{% if page.has_next %}{% endif %}

            {% endif %}
        {% else %}
            {# Show some example queries to run, maybe query syntax, something else? #}
        {% endif %}
    </form>
{% endblock %}

models.py

from django.db import models
from django.contrib.auth.models import User
from django.template import RequestContext
from django.http import HttpResponse

class Document(models.Model):

user_id = models.CharField(max_length=6, default='admin')
pub_date = models.DateTimeField()
title = models.CharField(max_length=200)
Link= models.URLField()
content = models.TextField()
CarModel= models.TextField()

    def get_absolute_url(self):
        return self.Link
    def __unicode__(self):
        return self.title

search_indexes.py

from haystack import indexes
from test3.models import Document

class DocumentIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, use_template=True)
    content_auto=indexes.EdgeNgramField(model_attr='content')
    CarModel=indexes.EdgeNgramField(model_attr='CarModel')
    def get_model(self):
        return Document
    def index_queryset(self, using=None):
        """Used when the entire index for model is updated. Typically to avoid some results showing when admin do not want to"""
        return self.get_model().objects

Following this other post Using django haystack search with global search bar in template I have updated the following files

urls.py

from django.conf.urls import url
from test3.views import MySearchView

# urls.py

urlpatterns =  [url(r'^/search/?$', MySearchView.as_view(), name='My_search_view'),]

views.py

from haystack.forms import HighlightedSearchForm
from haystack.query import SearchQuerySet
from haystack.generic_views import SearchView
from haystack.views import search_view_factory

class MySearchView(SearchView):
    """My custom search view."""
    def search_posts(request):
        post_type = str(request.GET.get('CarModel')).lower()
        print (str(request.GET.get('CarModel')).lower())
        sqs = SearchQuerySet().filter(CarModel__contains=post_type)
        clean_query = sqs.query.clean(post_type)
        result = sqs.filter(content=clean_query)
        view = search_view_factory(
            view_class=SearchView,
            template='search/search.html',
            searchqueryset=result,
            form_class=HighlightedSearchForm
            )
        return view(request)

However, I still did not make it work...Search results are still not filtered by 'Model' field. I guess I have to add extra code, but I do not know where...

Body:
I'll try respond to this. This is how I got it working:

In yourapp/urls.py

url(r'^search/$', views.search_notes, name='search_notes'),

In yourapp/views.py import your NotesSearchForm (further below) and call that on search:

from .forms import NotesSearchForm

def search_notes(request):
   form = NotesSearchForm(request.GET)
   notes = form.search()
   return render_to_response('notes/index.html', {'notes': notes, 'form': form})

   context = { 'latest_notes_list': latest_notes_list}
   return render(request, 'notes/index.html', context)

Then in your yourapp/forms.py is where the magic happens:

from haystack.forms import SearchForm

class NotesSearchForm(SearchForm):

   # First we add the form fields, in your case BooleanFields.
   sports = forms.BooleanField()
   fiction = forms.BooleanField()
   non_fiction = forms.BooleanField()

   def search(self):
      # Here we store the SearchQuerySet received from other processing.
      sqs = super(NotesSearchForm, self).search()

      if not self.is_valid():
         return self.no_query_found()

      # Then filter your results when the search come back

      if self.cleaned_data['sports']:
         sqs = sqs.filter(genre='sports')
      if self.cleaned_data['fiction']:
         sqs = sqs.filter(genre='fiction')
      if self.cleaned_data['non_fiction']:
         sqs = sqs.filter(genre='non_fiction')

      return sqs

   def no_query_found(self):
      # This we add to make all results show if nothing is selected or searched for (optional)
      return self.searchqueryset.all()

Note that here I put 'genre' as what the field is named in your model. This field also need to be present in your search_indexes.py, like this:

genre = indexes.CharField(model_attr='genre')

Finally, let me show you the yourapp/templates/notes/index.html:

<!-- Form here -->
{{ form }}

<!-- Search results here -->
{% for note in notes %}

   {{ note.object.title }}
   {{ notes.object.body|linebreaks }}">

{% endfor %}

Hope it works for you! Let me know if you get stuck.


问:
Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default
I've downloaded iOS 8 Gold Master for the iPhone and the SDK.

I tested the app and it works fine, except for one thing.

I have a text field where a number pad will appear if the user wants to type something, in addition, a custom button is added to the empty area when the keyboard shows up.

```<code>- (void)addButtonToKeyboard
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
    {
        // create custom button
        UIButton * doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        doneButton.frame = CGRectMake(-2, 163, 106, 53);
        doneButton.adjustsImageWhenHighlighted = NO;
        [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
        [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
        [doneButton addTarget:self action:@selector(saveNewLead:) forControlEvents:UIControlEventTouchUpInside];

        // locate keyboard view
        UIWindow * tempWindow = [[[UIApplication sharedApplication] windows]objectAtIndex:1];
        UIView* keyboard;
        for(int i=0; i<[tempWindow.subviews count]; i++)
        {
            keyboard = [tempWindow.subviews objectAtIndex:i];

            // keyboard view found; add the custom button to it
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
                if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
                    [keyboard addSubview:doneButton];
            } else {
                if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
                    [keyboard addSubview:doneButton];
            }
        }
    }

}
</code>```

This was working fine up till now.

First of all, I'm getting this warning:

Can't find keyplane that supports type 4 for keyboard
  iPhone-Portrait-NumberPad; using
  3876877096_Portrait_iPhone-Simple-Pad_Default

then that custom button is also not showing, which I think because of these 2 lines:

```<code>if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
</code>```

and

```<code>if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
</code>```

Any suggestions?

答:
Go into Simulator-> Hardware->Keyboard and unchecking Connect Hardware Keyboard.

The same as many answers above BUT did not change for me until I quit and restart the simulator. xcode 8.2.1 and Simulator 10.0.

Body:
I've downloaded iOS 8 Gold Master for the iPhone and the SDK.

I tested the app and it works fine, except for one thing.

I have a text field where a number pad will appear if the user wants to type something, in addition, a custom button is added to the empty area when the keyboard shows up.

- (void)addButtonToKeyboard
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
    {
        // create custom button
        UIButton * doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        doneButton.frame = CGRectMake(-2, 163, 106, 53);
        doneButton.adjustsImageWhenHighlighted = NO;
        [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
        [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
        [doneButton addTarget:self action:@selector(saveNewLead:) forControlEvents:UIControlEventTouchUpInside];

        // locate keyboard view
        UIWindow * tempWindow = [[[UIApplication sharedApplication] windows]objectAtIndex:1];
        UIView* keyboard;
        for(int i=0; i<[tempWindow.subviews count]; i++)
        {
            keyboard = [tempWindow.subviews objectAtIndex:i];

            // keyboard view found; add the custom button to it
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
                if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
                    [keyboard addSubview:doneButton];
            } else {
                if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
                    [keyboard addSubview:doneButton];
            }
        }
    }

}

This was working fine up till now.

First of all, I'm getting this warning:

Can't find keyplane that supports type 4 for keyboard
  iPhone-Portrait-NumberPad; using
  3876877096_Portrait_iPhone-Simple-Pad_Default

then that custom button is also not showing, which I think because of these 2 lines:

if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)

and

if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)

Any suggestions?


问:
get the current location fast and once in android
I have an android application that need device current location (latitude and longitude). I've tried some tutorial on the net and specially some solutions from stack overflow, but they doesn't work well for me. My requirement is so simple: First I need it to be fast and need the location once when I the fragment starts. Second I need it to be as precise as possible, I mean it should use GPS first if GPS is not available then use Network provider.

For example, I've tried this solution but it return null after 30 second, but I know there is some all the things is ok because google map and other application works well !!!

Something that almost all the answers suggest is to use getLastKnownLocation(), but I suppose it's not the current and I don't want it if it is so.

can anyone suggest me some kind of simple and fast way to get the location just ONCE ?!

答:
AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
</code>```

MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity implements LocationListener {

    private LocationManager locationManager;
    private Location onlyOneLocation;
    private final int REQUEST_FINE_LOCATION = 1234;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
    }

    @Override public void onLocationChanged(Location location) {
        onlyOneLocation = location;
        locationManager.removeUpdates(this);
    }
    @Override public void onStatusChanged(String provider, int status, Bundle extras) { }
    @Override public void onProviderEnabled(String provider) { }
    @Override public void onProviderDisabled(String provider) { }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
        case REQUEST_FINE_LOCATION:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("gps", "Location permission granted");
                try {
                    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    locationManager.requestLocationUpdates("gps", 0, 0, this);
                }
                catch (SecurityException ex) {
                    Log.d("gps", "Location permission did not work!");
                }
            }
            break;
    }
}
</code>```

Body:
AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />

MainActivity.java:

public class MainActivity extends AppCompatActivity implements LocationListener {

    private LocationManager locationManager;
    private Location onlyOneLocation;
    private final int REQUEST_FINE_LOCATION = 1234;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
    }

    @Override public void onLocationChanged(Location location) {
        onlyOneLocation = location;
        locationManager.removeUpdates(this);
    }
    @Override public void onStatusChanged(String provider, int status, Bundle extras) { }
    @Override public void onProviderEnabled(String provider) { }
    @Override public void onProviderDisabled(String provider) { }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
        case REQUEST_FINE_LOCATION:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("gps", "Location permission granted");
                try {
                    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    locationManager.requestLocationUpdates("gps", 0, 0, this);
                }
                catch (SecurityException ex) {
                    Log.d("gps", "Location permission did not work!");
                }
            }
            break;
    }
}


问:
What is the specific reason for the runtime error I'm getting here?
```<code>#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}
</code>```

What is the specific reason for the runtime error I'm getting here?

答:
```<code>    //There are things that shoudn't be there. Im not a pro but this is what I think.

    #include<stdio.h>
    #include<string.h>//you have include this library but you didn't use a function from it.
                      //I think what you want to do is use the str functions like strcpy
                      //but in this case you don't need to use it.

    void main()
    {
        char a[25],b[25],c[25];//Here you declared a character a, b and c. But if you want to store a string, you have to declare an array of characters. So instead of a, b, c, it's a[someValue], b[someValue] and c[someValue].
                   //Declare an array with a size that you think will cover the whole "alien name". e.g. a[25]..
                   //but i don't know, maybe you did it on purpose. Maybe you just want to name the aliens with one character like A, B, C. But if you want to name the aliens with a long name, you must declare an array.

        printf("Enter alien names:\n");
        scanf("%s\n%s\n%s\n",a,b,c);//You don't need to put the "\n" between those "%s". "\n" means "newline". It will work without it because scanf automatically reads next set of characters when it meets white space of newline.
                                    //--so you can remove "\n" in there and replace it with space. But you can leave it there also but  you really have to remove the last "\n" because scanf will search again for the next
                                    //--new line before it will end asking for input and pressing enter will not work because you have to type another set of characters before scanf will read the last "\n" that you put at scanF.
                                    //Another mistake here is the format specifier that you used (%s). It doesn't match declaration because you declare char a, b, c, that will only store one character each.
                                    //In case that you're really just storing one character each alien's name, you have to use the "%c" instead of "%s" and you must pass the reference of the char variable in
                                    //--scanf, e.g. scanf("%c %c %c", &a, &b, &c);
                                    //Just remember that if you plan on storing a string or a long name there, you must declare an array like I said at the beginning.
                                    //--and if it's an array, you don't need to include the '&' on every variable when you're passing it in scanF.

        //There's nothing wrong here if you're alien's names are string.
        printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
    }
</code>```

Body:
#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}

What is the specific reason for the runtime error I'm getting here?


问:
Show only results in query with more then 2 hits
didnt find a solution yet... ;-)

suppose this is the result of a query:

```<code>ID, SUBS, DATE .
19967,142, 2017-06-15 .
20214,147, 2017-05-09 .
20214,137, 2017-06-07 .
20303,147, 2017-05-31 .
</code>```

and i want only the records with an ID who are more then 1 time in result, but i do want the 2 or more records, so not GROUP BY.

How to manipulate the query?

答:
You'll have to do it in 2 steps - one to determine which IDs have multiples and another to select them.

There's many ways to do that; in this version, the ids having multiples are counted and then the data is selected separately.

In my (outdated) experience, large IN sets can be pretty slow.  If that list ends up being huge, it would make sense to use a temporary table to store the results so they can be indexed.  Regardless, an index on id seems like it could only help.

select t.* from t where t.id in ( select id, count(*) c from t having c > 1)

Body:
didnt find a solution yet... ;-)

suppose this is the result of a query:

ID, SUBS, DATE .
19967,142, 2017-06-15 .
20214,147, 2017-05-09 .
20214,137, 2017-06-07 .
20303,147, 2017-05-31 .

and i want only the records with an ID who are more then 1 time in result, but i do want the 2 or more records, so not GROUP BY.

How to manipulate the query?


问:
jsfiddle and codepen not storing window.localStorage entries
I am trying to store some items from an exercise I'm doing in codepen over to the localStorage object of the browser, but it doesn't seem to work.

I then tried the same thing over on jsFiddle, it also doesn't work.
Here's the link to the fiddle

Lastly I tried bringing the same code local to my desktop, everything is working as expected.

In all three cases here is how I am testing for success / failure:

In the Chrome console i am executing the following:

```<code>localStorage.getItem('_wikiwiggs_recipe_book_AppleJuice');
</code>```

Any thoughts as to why I may be experiencing this?

答:
OK, after my way...... too long pursuit of this answer, I have been able to do the following:

The answer for my intentions is to simply:

```<code>console.log(localStorage.getItem('_wikiwiggs_recipe_book_AppleJuice'))
</code>```

from within my codepen/jsFiddle.

I can't do this directly from the console manually, because I do not really have the privileges (for good reason) to essentially spoof the site author.

The only way that I have found to be able troubleshoot via javascript directly is to use this method.

Thanks for the help enapupe & Bobby Speirs - The answer given definitely reinforced the reasoning for this behavior.

For me though, leaving off the console.log() from your answer as trivial as this may sound, tripped me up, because I was still not seeing how I was going to troubleshoot the code.

Body:
I am trying to store some items from an exercise I'm doing in codepen over to the localStorage object of the browser, but it doesn't seem to work.

I then tried the same thing over on jsFiddle, it also doesn't work.
Here's the link to the fiddle

Lastly I tried bringing the same code local to my desktop, everything is working as expected.

In all three cases here is how I am testing for success / failure:

In the Chrome console i am executing the following:

localStorage.getItem('_wikiwiggs_recipe_book_AppleJuice');

Any thoughts as to why I may be experiencing this?

Body:
OK, after my way...... too long pursuit of this answer, I have been able to do the following:

The answer for my intentions is to simply:

console.log(localStorage.getItem('_wikiwiggs_recipe_book_AppleJuice'))

from within my codepen/jsFiddle.

I can't do this directly from the console manually, because I do not really have the privileges (for good reason) to essentially spoof the site author.

The only way that I have found to be able troubleshoot via javascript directly is to use this method.

Thanks for the help enapupe & Bobby Speirs - The answer given definitely reinforced the reasoning for this behavior.

For me though, leaving off the console.log() from your answer as trivial as this may sound, tripped me up, because I was still not seeing how I was going to troubleshoot the code.