text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Normal characters next to ASCII escapes in C strings
I'm writing a C program for a specific non-standard platform, and I need to print out a string which contains extended ASCII codes to draw a text-based UI. However, I've been needing to print out strings like the ones below:
"\xCDBaby \xCD"
and
"\xDFEDWARD\xDF"
The goal being to print out the words "Baby" and "EDWARD" with the extended ASCII bytes on each end of them. Unfortunately, the C compiler interprets these as multibytes character escapes, since it treats the B and a in "Baby" and the E and D in "EDWARD" as hex digits that specify a multibyte character value, instead of a single byte character escape followed by normal text. Is there a way to separate the escape from the real character, such as a non-valued escape to mark the end of the hex number? Right now my workaround is to insert a "%c" and use the platform's printf formatting to put the right value there, but it's hacky and there must be a better way.
Using external libraries is out of the question, unless they can run freestanding, due to the platform I'm using (no standard library, not even printf), and the situation requires that I MUST use these Extended ASCII bytes. Really, there should be some way to represent this inside the string shouldn't there? Surely I'm not the first person to want to put escapes directly next to capital letters A and B.
A:
C has a feature that causes adjacent string literals to be concatenated into a single string.
For example the three separate string literals "hello" " " "world" becomes the single string "hello world".
This is useful in cases like your because handling escape sequences in string literals is done before the concatenation. So you could solve your problem by using multiple string literals, like
"\xCD" "Baby \xCD"
or
"\xDF" "EDWARD\xDF"
For more information about the different translation phases see e.g. this reference. The two phases that are important for this case are phase 5 which handles escape sequences, and phase 6 which does the concatenation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to receive complete data from serial port in linux
I am trying to do a serial communication application. I have a device which is running angstrom qt linux image. I need to write the serial code application for that device. Because the cross compiler is set for QT4.8.7, so it do not include the QSerialPort. So I am following this link for serial communication and I have also found many good examples on it.
Below is the code:
void MainWindow::SerialOpen(QString PORT)
{
fd = open(PORT.toStdString().c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/ttyLP0\n");
exit(1);
}
saio.sa_handler = signal_handler_IO;
saio.sa_flags = 0;
saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
fcntl(fd, F_SETFL, FNDELAY);
fcntl(fd, F_SETOWN, getpid());
fcntl(fd, F_SETFL, O_ASYNC );
tcgetattr(fd,&termAttr);
cfsetispeed(&termAttr,B9600);
cfsetospeed(&termAttr,B9600);
termAttr.c_cflag &= ~PARENB;
termAttr.c_cflag &= ~CSTOPB;
termAttr.c_cflag &= ~CSIZE;
termAttr.c_cflag |= CS8;
termAttr.c_cflag |= (CLOCAL | CREAD);
termAttr.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
termAttr.c_iflag &= ~(IXON | IXOFF | IXANY);
termAttr.c_oflag &= ~OPOST;
tcsetattr(fd,TCSANOW,&termAttr);
qDebug("Serial Port configured....\n");
}
and for reading I am using:
void signal_handler_IO (int status)
{
char buf [100];
int n = read (fd, buf, sizeof buf);
if(n > 0)
{
buf[n] = '\0';
printf("Receive OK %s\n",buf);
}
}
I am using event based serial read. I am wiriting it in QT creator. The problem I am facing is that whenever I am sending characters like A or B or any other single char. It receives it. But when I send the complete string, it breaks automatically. Have a look at the below image:
As you can see in the image, it receives char like p l h but then I sent hello world. It breaks it and first received hello and then world. I again sent the hello world it receives the he then llo then worl and then d. Why is this showing this behaviour. Please help. Thanks.
A:
You are receiving your data in small chunks. Try running the read function in a while loop to append all chunks into one message like so:
#include <cstring> // needed for strcat.
#include <errno.h> // needed for strerror and errno
void signal_handler_IO (int status)
{
char buf [100];
char msg[1024];
int n;
int length = 0;
while((n = read (fd, buf, (sizeof buf)-1)) > 0)
{
buf[n] = '\0';
// you can add a check here to see if (length+n) < 1024
strcat(msg, buf);
length += n;
}
if(n<0)
{
//error handling
//EDIT: adding error handling
fprintf(stderr, "Error while receiving message: %s\n", strerror(errno));
return;
}
printf("Receive OK: '%s'\n", msg);
}
The signal handling needs to be turned off for the time of reading data so that the signal handler doesn't get called for each new chunk of data. After we're done reading the handler needs to be restored.
EDIT: Thanks to @MarkPlotnick for giving a better example on masking the signal instead of turning it off (could cause race condition). Add these two lines before calling sigaction to MainWindow::SerialOpen to mask the signal so that the handler doesn't get called again while the signal is being handled:
sigemptyset(&saio.sa_mask);
sigaddset(&saio.sa_mask, SIGIO);
The size of msg is just an example, you can set it to any value that will fit the message. Also, if you're using c++ then it would be better to use std::string instead of an array for msg.
Note the (sizeof buf)-1, if you read all characters there would be no room for the '\0' at the end of the array.
ANOTHER EDIT: After our chat conversation it turned out that read is blocking when there are no more characters to read (even though open was called with O_NDELAY flag for non-blocking reading). To fix this issue one can first check how many bytes are available for reading:
while(true)
{
size_t bytes_avail;
ioctl(fd, FIONREAD, &bytes_avail);
if(bytes_avail == 0)
break;
int n = read (fd, buf, (sizeof buf)-1);
if(n<0)
{
//error handling
fprintf(stderr, "Error while receiving message: %s\n", strerror(errno));
return;
}
buf[n] = '\0';
// you can add a check here to see if (length+n) < 1024
strcat(msg, buf);
length += n;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create custom coordinate system in postgis
I have a Wayne county Michigan parcel dataset with a custom SRID:
when I bring it into ArcGIS
Projected Coordinate System: NAD_1983_HARN_StatePlane_Michigan_South_FIPS_2113_Feet_Intl
Projection: Lambert_Conformal_Conic
False_Easting: 13123359.58005249
False_Northing: 0.00000000
Central_Meridian: -84.36666667
Standard_Parallel_1: 42.10000000
Standard_Parallel_2: 43.66666667
Latitude_Of_Origin: 41.50000000
Linear Unit: Foot
Geographic Coordinate System: GCS_North_American_1983_HARN
Datum: D_North_American_1983_HARN
Prime Meridian: Greenwich
Angular Unit: Degree
I am trying to insert this SRID into postgis. Is this enough info to go and create the insert statement into postgreSQL?
A:
It's easy here
Look it up on http://www.spatialreference.org
Find it SR-ORG:7069 NAD_1983_HARN_StatePlane_Michigan_South_FIPS_2113_IntlFeet
Click PostGIS spatial_ref_sys INSERT statement
Run that insert command.
Reproduced below,
INSERT into spatial_ref_sys (srid, auth_name, auth_srid, proj4text, srtext)
values ( 97069, 'sr-org', 7069, '', 'PROJCS["NAD_1983_HARN_StatePlane_Michigan_South_FIPS_2113_IntlFeet",GEOGCS["GCS_North_American_1983_HARN",DATUM["D_North_American_1983_HARN",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",13123359.58005249],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",-84.36666666666666],PARAMETER["Standard_Parallel_1",42.1],PARAMETER["Standard_Parallel_2",43.66666666666666],PARAMETER["Latitude_Of_Origin",41.5],UNIT["Foot",0.3048]]');
Now you have SRID 7069.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Wikis de tag copiados do Wikipédia?
Algumas pessoas têm copiado conteúdo do Wikipédia para colocar nas wikis de tag (exemplo). Como devemos lidar com isso?
Discussão no SO em inglês: Copy and pasting Wikipedia articles into tag-wikis
A:
Até usando o mesmo critério adotado no SO original, acho que não há problema em usar o conteúdo da Wikipedia, mas colar o conteúdo integral não funciona.
A intenção da tag wiki é dar uma informação básica sobre o assunto, oferecer caminhos alternativos para quem está iniciando no assunto obter informações básicas antes de perguntar e possivelmente indicar que tipo de pergunta deve usar a tag. Em geral o conteúdo da Wikipedia, na forma original, não costuma ser bom para isso.
Além disso, tanto para o fragmento quanto para o texto mais completo, o artigo na Wikipedia deve ser muito longo.
Usar alguma frase da Wikipedia cuidadosamente escolhida para ajudar na escrita do texto não me parece ser problemático.
O que deve-se observar é a tag wiki ser útil para o nosso usuário. Ela não deve substituir o artigo da Wikipedia ou ser um tratado geral sobre o assunto.
Então acho que usar trechos com parcimônia é uma boa, copiar sem contextualizar, não.
E claro que um link para o artigo na Wikipedia não só é desejável para o leitor achar mais detalhes (e é lá que eles devem estar) , mas também importante para identificar a fonte do trecho usado.
Provavelmente um caminho melhor é usar a tag wiki do SO, o que já impede colar integralmente sem adaptação já que está em inglês.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
access the value of minRequiredNonalphanumericCharacters in the membership config using c#
I want to give an error message if someone tries to create a password with too few alpha numeric characters. I want to show how many none alpha numeric characters to use. This defined in the web.config under membership with property minRequiredNonalphanumericCharacter. As this can change and I dont want to hard code the number in the error message how can I get to this value. I dont seem to be able to do this with configurationManager.
Any thoughts?
thanks
Andy
A:
Use
System.Web.Security.Membership.MinRequiredNonAlphanumericCharacters
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Having trouble removing and applying event handler on window resize. (Works in FireFox not in Chrome)
I want a button that shows or hides a div, but when I resize the browser and trigger a media query I want to disable the button, enabling it again when resizing to the previous media query.
I'm using media queries with body:after {content:'tablet'; display:none;}, body:after {content:'laptop'; display:none;} and it works fine.
I'm using jQuery .on(); and .off(); to add/remove an event handler on window resize. The problem I'm having is that the event handler is getting added but it's toggling off straight away when I click it, going back to the 'tablet` viewport size.
How do I make it so that when I resize to the "laptop" size I remove the handler, but when I resize to "tablet" again I add the event handler.
jQuery
function chooseMenu() {
$('#sidebarWrapper').css('position', 'absolute').stop(true, true).toggle('showOrHide');
} // button function
if (size != currentSize) {
if (size == 'tablet') {
$('.menuButton').on('click', chooseMenu);
$('#sidebarWrapper').css('display', 'none');
currentSize = 'tablet';
}
if (size == 'laptop') {
$('.menuButton').off();
$('#sidebarWrapper').css('position', 'static');
$('#sidebarWrapper').css('display', 'block');
currentSize = 'laptop';
}
} //if size
I'm assuming there's something wrong with my on/off or the toggle logic which I must be missing. If this isn't the case and you need to see more just ask or just check out the live site. It's the menu button on the grey strip on the left hand side. http://lartmagazine.co.uk/. (sorry for the link I just don't know how to show this in a fiddle).
Err.. Upon just checking my link I noticed that it works in FireFox but not in Chrome?
A:
The problem was that I needed to throttle my functions when I resized the window, I installed underscore.js and used this:
$(window).resize(_.debounce(function(){
},100));
I actually had this installed before but forgot about it playing around with other stuff...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does the vowel combination /ou/ appear in any Spanish words?
Spanish has many diphthongs, but I have never noticed 'ou' appearing in a word except for bou (a Catalan loanword), the surname Bousoño, and the Kantian term noúmeno.
The sound does occur across word boundaries - "tengo una casa" etc - and in some compound words e.g. estadounidenses, genitourinario, finoúgrio.
Are there any other Spanish words that contain the combination of vowels /ou/ (as a diphthong or in hiatus)?
Note: I'm not including un-assimilated French/English loanwords like coulis, rouge, touche, roulotte, bourbon, house etc as they tend to be pronounced similarly to the original voice i.e. /u/ or /au/ e.g. in sioux and its assimilated form siux, or in output.
Source:
Bowen and Stockwell do not list /ow/ (written /ou/ in this note) among their syllabic nuclei. It occurs in admittedly rare forms such as bou 'fishing with a net dragged by two boats' and the proper name Bousoño.
• "A Note on Spanish Semivowels", Sol Saporta (1956)
A:
Realizando una búsqueda para palabras que contienen "ou" en el DLE, se genera la siguiente lista:
bou, proustiano, soul1
estadounidense, estadounidismo, genitourinario
art nouveau, boutade, boutique, coulis, gouache, gourmet, mousse, rouge, roulotte, souvenir, tour, tour de force, tournée, troupe
choucroute (chucrut), glamour (glamur), coulomb (culombio), goulash (gulasch), joule (julio), sioux (siux), soufflé (suflé)
bourbon, boy scout, chill out1, country1, house1, output, underground.
La búsqueda para palabras que contienen "oú" solo arroja dos resultados:
finoúgrio (también fino-ugrio)
noúmeno
Como se puede ver, son todo extranjerismos (en cursiva - sin cursiva la adaptación española) o compuestos (como estadounidense, finoúngrio), por lo que además de los casos contemplados en la pregunta (bou y noúmeno), únicamente proustiano y soul (como señala acertadamente walen) cumplen los requisitos pedidos.
1. Estilos de música.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WCF DataContract IsReference = true and .NET 1.1
I have a WCF service which basically returns
[DataContract(IsReference = true)]
public class Person
{
public Person[] relatedPersons;
}
As you can see, it has a cercular reference, but ofcourse, IsReference = true solves the problem. Almost.
Among numerous clients, there is a .NET 1.1 application, which calls this service through basicHttpBinding. If the response contains more than one reference to the same Person, .NET 1.1 client doesn't seem to resolve the references in the XML and the second reference becomes just an empty inctance.
Any ideas how to solve this problem?
A:
No way to solve this with a .NET 1.1 client. Circular references in XML are not a standard SOAP specification which means that both the client and the server need to use WCF if you want it to work. You could always write a custom serializer on the client side which will resolve those references but I suspect it will be a lot of work if you need it to work in the general case.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Partial Rendering will only work with @form?
I have a strange situation where using @parent, or even explicit id-s dont work in the update attribute. But @form works fine.
I've made a very simple test case, that includes a simple grid whose behaviour is like this :
Every record inside the grid has a modify button
After the modify button is clicked, it'll modify the server data, and the button will be gone, since it'll be only rendered if the record has NOT been modified.
The modify button is like this :
<!-- this works, since it's using @form in the update attribute -->
<p:column>
<p:commandLink
value="modify record"
process="@this"
action="#{testUserBean.modifyRecord(user)}"
update="@form"
rendered="#{not testUserBean.isRecordModified(user)}" />
</p:column>
Notice that the update attribute makes use of @form which makes it work: when the modify button is clicked, it rerenders and disappears.
Substitute it with @this or @parent or the id of the grid, then it will NOT work. For me it's very logical to use the id of the grid in the update attribute, since i would like to refresh the grid after clicking on the buttton.
I tried making use of rowIndexVar="rowIndex" and myGridId:#{rowIndex}:link, but still aint working.
<!-- this does not work -->
<p:column>
<p:commandLink id="link"
value="modify record"
process="@this"
action="#{testUserBean.modifyRecord(user)}"
update="tblUser"
rendered="#{not testUserBean.isRecordModified(user)}" />
</p:column>
Here are the resources for this simple example :
The xhtml file
The JSF Bean file
The user POJO bean
Im using tomcat 7, and these are my dependencies :
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.0.4-b09</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.0.4-b09</version>
<scope>compile</scope>
</dependency>
Tried out primefaces 3.0.M1 also, but it got the same behavior also.
Please share your ideas. Is this a bug or i did something wrong ?
UPDATE
Hello,
I've just finished some testing, but all still fails.
Test 1 (making use of update=":gridRPBDetails") :
The JSF File :
<p:commandLink id="undoLink" value="Undo" process="@this"
action="#{tInputBean.actionUndoRemoveRecord(rpbDetail)}"
update=":gridRPBDetails"
rendered="#{tInputBean.isRemoveRecord(rpbDetail)}"
title="Batalkan buang data" />
The generated xhtml :
<a title="Batalkan buang data" onclick="PrimeFaces.ajax.AjaxRequest('/cashbank/faces/TInput.xhtml',
{formId:'j_idt38',async:false,global:true,source:'gridRPBDetails:0:undoLink',
process:'gridRPBDetails:0:undoLink',update:':gridRPBDetails'});"
href="javascript:void(0);" id="gridRPBDetails:0:undoLink">Undo</a>
Test 2 (making use of update=":gridRPBDetails:#{rowIndex}:undoLink") :
The JSF File :
<p:commandLink id="undoLink" value="Undo" process="@this"
action="#{tInputBean.actionUndoRemoveRecord(rpbDetail)}"
update=":gridRPBDetails:#{rowIndex}:undoLink"
rendered="#{tInputBean.isRemoveRecord(rpbDetail)}"
title="Batalkan buang data" />
The generated xhtml :
<a title="Batalkan buang data" onclick="PrimeFaces.ajax.AjaxRequest('/cashbank/faces/TInput.xhtml',
{formId:'j_idt38',async:false,global:true,source:'gridRPBDetails:0:undoLink',
process:'gridRPBDetails:0:undoLink',update:':gridRPBDetails:0:undoLink'});"
href="javascript:void(0);" id="gridRPBDetails:0:undoLink">Undo</a>
Both tests still fail in terms of clicking the undo button cannot refresh the record of the grid, or even the grid itself.
UPDATE
I've just updated my test using :
<p:commandLink
value="modify record"
process="@this"
action="#{testUserBean.modifyRecord(user)}"
update=":mainForm:tblUser"
rendered="#{not testUserBean.isRecordModified(user)}" />
Notice i used the :mainForm:tblUser, and i've tried the other options and still failed :
:mainForm:tblUser:
:tblUser (when i dont define the form name)
:mainForm:tblUser:#{rowIndex}:linkId
But 1 thing i notice is,nNo matter what i choosed for the update, the update always ends up as tblUser:0
<a onclick="PrimeFaces.ajax.AjaxRequest('/cashbank/faces/test.xhtml',
{formId:'mainForm',async:false,global:true,source:'tblUser:0:j_idt33',
process:'tblUser:0:j_idt33',
update:'tblUser:0'
});" href="javascript:void(0);" id="tblUser:0:j_idt33">modify record</a>
I tried modifying tblUser:0 on the fly using firebug to just tblUser, the partial rendering on the grid works fine.
Im beginning to think that this is a bug when trying to update a grid from inside a grid record.
A:
This has been answered in here.
Here is the quote from the answer :
This is more like a mojarra issue, it should work fine with myfaces
without a wrapper. Workaround is to put a wrapper.
Code:
<h:form id="frm">
<p:outputPanel id="wrapper">
<p:dataTable id="tbl">
//...
<p:commandButton update=":frm:wrapper" />
//...
<p:dataTable>
<p:outputPanel>
</h:form>
Sorry for the late update !
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create Image magick object from response stream in go lang
I am using the following code to download and upload the images from Amazon S3. Now, after downloading the image i want to resize it using the imagick library, but without writing it on to the disk. So, how do i create the image magick object directly from response stream which i will get from S3 and upload the same on Amazon S3. Could you please suggest the changes for the same in below code?
Also, How do i change it to a http handler which takes the value of key from query string?
I have commented out my code of image magick object reason being i am sure how to write it.
func main() {
file, err := os.Create("download_file")
if err != nil {
log.Fatal("Failed to create file", err)
}
defer file.Close()
downloader := s3manager.NewDownloader(session.New(&aws.Config{Region: aws.String(REGION_NAME)}))
numBytes, err := downloader.Download(file,
&s3.GetObjectInput{
Bucket: aws.String(BUCKET_NAME),
Key: aws.String(KEY),
})
if err != nil {
fmt.Println("Failed to download file", err)
return
}
fmt.Println("Downloaded file", file.Name(), numBytes, "bytes")
//mw := imagick.NewMagickWand()
// defer mw.Destroy()
// err = mw.ReadImage(file)
// if err != nil {
// panic(err)
// }
// using io.Pipe read/writer file contents.
reader, writer := io.Pipe()
go func() {
io.Copy(writer, file)
file.Close()
writer.Close()
}()
uploader := s3manager.NewUploader(session.New(&aws.Config{Region: aws.String(REGION_NAME)}))
result, err := uploader.Upload(&s3manager.UploadInput{
Body: reader,
Bucket: aws.String(BUCKET),
Key: aws.String(KEY),
})
if err != nil {
log.Fatalln("Failed to upload", err)
}
log.Println("Successfully uploaded to", result.Location)
fmt.Println("code ran successfully")
}
A:
You only need a DownloadManager if you want to download large files more efficiently. A DownloadManager requires a WriterAt (generally an os.File), which you would have to implement yourself over a []byte or use a file in memory.
If you fetch the object directly, you can read it into a []byte which can be passed to ReadImageBlob:
out, err := s3Client.GetObject(&s3.GetObjectInput{
Bucket: aws.String(BUCKET),
Key: aws.String(KEY),
})
if err != nil {
log.Fatal(err)
}
img, err := ioutil.ReadAll(out.Body)
if err != nil {
log.Fatal(err)
}
mw := imagick.NewMagickWand()
defer mw.Destroy()
err = mw.ReadImageBlob(img)
if err != nil {
log.Fatal(err)
}
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gtk3 ProgressBar(): unable to receive events in Python
I'm trying to migrate an audio player, written in python, to GTK3+. In GTK2 I used progress_bar.add_event(...pointer_motion_notify|button_press) (full code below), and set a signal handler for button_press and pointer_motion_notify. In GTK3, it appears that ProgressBar() does not emit these signals.
I have implemented a workaround using Overlay() and DrawingArea() which allows the DrawingArea to emit the signals, but should'nt need to...
Is this a bug? or am I doing it wrong?
Code:
import gi
gi.require_version("Gtk","3.0")
from gi.repository import Gtk, Gdk, GObject
class MainWindow(Gtk.Window):
def __init__(self):
super(MainWindow, self).__init__(title='ProgressBar Event Test')
self.progressbar = Gtk.ProgressBar()
self.add(self.progressbar)
self.progressbar.set_events(Gdk.EventMask.BUTTON_PRESS_MASK
| Gdk.EventMask.POINTER_MOTION_MASK)
self.progressbar.connect("button-press-event", self.on_event, 'button-press')
self.progressbar.connect("motion-notify-event", self.on_event, 'motion-notify')
self.connect("delete-event", Gtk.main_quit)
self.current_progress = 0.0
GObject.timeout_add(200,self.update_progress)
self.show_all()
def on_event(self, widget, event, data=None):
print "on_event called for %s signal"%data
return False
def update_progress(self):
self.progressbar.set_fraction(self.current_progress)
self.current_progress += 0.01
return self.current_progress <= 1 # False cancels timeout
def main():
w = MainWindow()
Gtk.main()
if __name__ == '__main__':
main()
A:
Its probably better to use an eventbox - you add the widget to the eventbox and connect to the eventbox signals themselves.
Thus:
import gi
gi.require_version("Gtk","3.0")
from gi.repository import Gtk, Gdk, GObject
class MainWindow(Gtk.Window):
def __init__(self):
super(MainWindow, self).__init__(title='ProgressBar Event Test')
eventbox = Gtk.EventBox()
self.progressbar = Gtk.ProgressBar()
eventbox.add(self.progressbar)
self.add(eventbox)
eventbox.set_events(Gdk.EventMask.BUTTON_PRESS_MASK
| Gdk.EventMask.POINTER_MOTION_MASK)
eventbox.connect("button-press-event", self.on_event, 'button-press')
eventbox.connect("motion-notify-event", self.on_event, 'motion-notify')
self.connect("delete-event", Gtk.main_quit)
self.current_progress = 0.0
GObject.timeout_add(200,self.update_progress)
self.show_all()
def on_event(self, widget, event, data=None):
print "on_event called for %s signal"%data
return False
def update_progress(self):
self.progressbar.set_fraction(self.current_progress)
self.current_progress += 0.01
return self.current_progress <= 1 # False cancels timeout
def main():
w = MainWindow()
Gtk.main()
if __name__ == '__main__':
main()
More info about the Gtk.Eventbox can be found here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VB.NET GUI choices
Can you point me to good non-Windows looking GUIs choices for VB.NET? I'm needing free but with licenses that allow closed proprietary code. Thank you.
A:
From your previous question:
I'll definitely want an attractive looking GUI. And nothing "Windows" looking.
Generally speaking, this is bad. Windows apps should look like windows apps. Otherwise hell will break loose:
alt text http://forum.computerbild.de/attachments/pc-hardware/realtek-hd-audio-manager-front-panel-problem-1470d1205060406-r.jpg
alt text http://www.techfuels.com/attachments/applications/1262d1207391664-gigabyte-easytune-5-pro-gigabyte-easytune-5-pro.jpg
Consider WPF to get a rich UI framework, though.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PostGIS extension on Postgres-xl
I'm trying to deploy a PostGIS cluster using Postgres-XL on AWS, for this I have the next architecture:
SO: ubuntu
1 GTM (172.31.45.190)
1 Coordinator (172.31.45.191)
2 Datanodes (172.31.45.192 and 172.31.45.193)
I had my cluster running but I can't manage to make PostGIS work, I tried the installation with sudo apt-get install postgis but when I try to create the extension inside my db (CREATE EXTENSION postgis;) I got the next error:
ERROR: could not open extension control file "/usr/local/pgsql/share/extension/postgis.control": No such file or directory
The postgis.control file installed by apt-get is in: "/usr/share/postgresql/9.5/extension/postgis.control" so I think is just a problem with the paths but I'm a little lost on that configuration
Thank you in advance for any help!
A:
In case anyone is running in this issue, I solved following this steps:
Install Postgres-xl and PostGIS dependencies to compile (Be sure to install the package postgresql-server-dev-9.5 in this step, otherwise it's going to brake your postgres-xl installation)
Build and install Postgres-XL with ./configure -prefix=/usr/lib/postgresql/9.5
Build and install PostGIS
Start your cluster
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AFHTTPSessionManager not deallocating
Update
After posting this as an issue to the AFNetworking repo, turns out this is in fact a usage issue on my part. Per the response to my issue:
NSURLSession retains its delegate (i.e. AFURLSessionManager). Call invalidateSessionCancelingTasks: to ensure that sessions finalize and release their delegate.
So, long story short: If you are using AHTTPSessionManager in the manner described below, make sure to call invalidateSessionCancelingTasks: to ensure that sessions finalize and release their delegate
Original Question
I have a subclassed AFHTTPSessionManager called GTAPIClient that I am using to connect to my REST API. I realize the docs state to use as a singleton but there are a few cases where I need to gin up a new instance. However, it seems that whenever I do so, the object is never deallocated. Currently, GTAPIClient literally does nothing except NSLog itself when deallocated.
Here's some sample code that demonstrates the behavior
GTAPIClient.m
@implementation GTAPIClient
- (void)dealloc
{
NSLog(@"Dealloc: %@", self);
}
@end
GTViewController.m
#import "GTBaseEntityViewController.h"
//Models
#import "GTBaseEntity.h"
//Clients
#import "GTAPIClient.h"
@interface GTBaseEntityViewController ()
@property (nonatomic, weak) GTAPIClient *client;
@property (nonatomic, weak) GTBaseEntity *weakEntity;
@end
@implementation GTBaseEntityViewController
- (IBAction)makeClient:(id)sender {
self.client = [[GTAPIClient alloc] init];
NSLog(@"I just made an API client %@", self.client);
//Another random object assigned to a similar property, just to see what happens.
self.weakEntity = [[GTBaseEntity alloc] init];
NSLog(@"I just made a random object %@", self.weakEntity);
}
- (IBAction)checkClient:(id)sender {
NSLog(@"Client: %@", self.client);
NSLog(@"Entity: %@", self.weakEntity);
}
@end
NSLog output
Fire makeClient:
//It seems to me that both NSLog's should return (null) as they are assigning to a weak property
2014-06-22 16:41:39.143 I just made an API client <GTAPIClient: 0x10b913680, baseURL: (null), session: <__NSCFURLSession: 0x10b915010>, operationQueue: <NSOperationQueue: 0x10b9148a0>{name = 'NSOperationQueue 0x10b9148a0'}>
2014-06-22 16:41:39.144 I just made a random object (null)
Fire checkClient
//Again, both NSLog's should return null for the two objects. However...client is still around. Also, it's overridden dealloc method never fired.
2014-06-22 16:44:43.722 Client: <GTAPIClient: 0x10b913680, baseURL: (null), session: <__NSCFURLSession: 0x10b915010>, operationQueue: <NSOperationQueue: 0x10b9148a0>{name = 'NSOperationQueue 0x10b9148a0'}>
2014-06-22 16:44:43.723 Entity: (null)
For reference, I am using v2.3.1 of AFNetworking. Compiler is warning me that assigning retained object to weak property will release after assignment - which is correct, and functions as expects with my random object. There is nothing else going on in the app. No other view controllers, no other methods on the GTAPIClient, all singleton functionality is removed. Any thoughts on what I am doing wrong here?
A:
Posting the response from Mattt Thompson here to assist future readers:
NSURLSession retains its delegate (i.e. AFURLSessionManager). Call invalidateSessionCancelingTasks: to ensure that sessions finalize and release their delegate.
If, like many apps, your app uses a singleton Session Manager and one URL Session for your entire app, then you don't need to worry about this.
A:
Replicating your scenario and running it through Instruments shows that AFURLSessionManagers are retained by the NSURLSessions they create, as AFURLSessionManager acts as the delegate for every NSURLSession created. This creates a retain cycle and thus the AFHTTPSessionManager cannot be released. Whether this is a bug in either library or not a bug at all, I'm not sure. You may want to report it on the AFNetworking GitHub page (https://github.com/AFNetworking/AFNetworking).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In Rust, is "as" an operator?
The Rust Reference presently says the following about the as operator:
7.2.12.5 Type cast expressions
A type cast expression is denoted with the binary operator as.
Executing an as expression casts the value on the left-hand side to the type on the right-hand side.
An example of an as expression:
fn average(values: &[f64]) -> f64 {
let sum: f64 = sum(values);
let size: f64 = len(values) as f64;
sum / size
}
(Also, since it will be relevant:
7.2.12.8 Operator precedence
The precedence of Rust binary operators is ordered as follows, going from strong to weak:
as
* / %
+ -
<< >>
)
Naïvely using this as an operator doesn't seem to work:
fn main() {
let x = 100 as u16 << 8;
}
Doesn't actually compile:
% rustc testing.rs
testing.rs:2:24: 2:25 error: expected type, found `8`
testing.rs:2 let x = 100 as u16 << 8;
With parentheses — let x = (100 as u16) << 8; — it compiles. The parens aren't required in the example in the reference, but seem to be here. What's the exact syntax here? Are parentheses required unless this is the only thing right of an =? Or am I just doing something wrong?
It is a bit weird that this is called an operator, as the RHS would seem to need to be a type, and typically, I think of an operator as taking two expressions…
A:
The trick here is as takes a type on its right hand side, i.e. the grammar of as looks something like: is expression 'as' type. The expression after the as looks a bit like (the start of) a type, it's trying to parse u16<<... as if u16 had a type parameter (an example of a type with a prefix like that would be Foo<<T>::Bar>).
This is basically just behaviour particular to << because it looks like the type parameter delimiters. If one uses an operator that can't appear after the leading identifier in a type, it works fine:
fn main() {
let x = 100 as u16 - 8;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Script to change downloaded mac wallpaper automatically?
I want to change my mac wallpaper daily with microsoft bing images.
I found this script that download the daily picture automatically, but I sill have to set the wallpaper automatically.
Is it possible to write a script (either terminal or applescript) that set the downloaded picture as wallpaper automatically?
A:
Solved! I used the Bing Wallpaper.app found here that does exactly what I needed.
A:
You could use this script taken from here.
#!/usr/bin/env python
import os
import md5
import pprint
import sys
import subprocess
from time import strftime
from urllib import URLopener
from urllib2 import urlopen
from xml.dom.minidom import parseString
# Defines source and destination of image
rss_feed = 'http://feeds.feedburner.com/bingimages';
dst_dir = os.path.expanduser('~/Pictures/DeskFeed/')
SCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""
def set_desktop_background(destination):
subprocess.Popen(SCRIPT%destination, shell=True)
def parseFeed(rss):
destination = "%s%s.jpg" % (dst_dir, strftime( "%y-%m-%d"))
if os.path.exists(destination):
sys.exit(0)
try:
rss_contents = urlopen( rss )
except:
print "Failed to read rss feed %s" % rss
return
rss_src = rss_contents.read()
rss_contents.close()
dom = parseString( rss_src )
firstitem = dom.getElementsByTagName('item')[0]
link = firstitem.getElementsByTagName( 'enclosure' )[0].getAttribute('url')
URLopener().retrieve(link, destination)
set_desktop_background(destination)
def main():
parseFeed(rss_feed)
if __name__ == "__main__":
main()
The only downside is you would need to make a cron job to run it every day.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Converting an old .raw video to .mp4?
I recently got an old Panasonic Lumix DMC-FZ50 from my father to use on a trip. On the trip I captured a video with the camera. When I put the video onto my laptop, I saw that the video extension is .raw. Is there a way for me to convert this video to .mp4?
A:
FFmpeg will probably do it, since it supports most video formats. It's a command-line program, but it is available for all major platforms.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is supplying new ETH prohibitive with Casper or an economic decision?
It has been said that the creation of new ETH will be discontinued with Caspar and PoS. Is there a fundamental reason why this is necessary, rooted in the protocol or is this a deliberate decision by the Ethereum Foundation?
A:
The creation of Ether is a subsidy to cover the costs associated with proof of work. Since Casper and/or proof of stake will no longer incur these costs, all computing resources of miners can be focused on transaction processing, which they get paid for. No reason to double pay miners.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
The regularity of successor cardinal
I was looking at two different proofs of the fact that successor cardinals are regular. It struck me as odd that both proofs used AC. Looking at the concepts involved in defining cofinality I feel as if there should a proof of this that doesn't use AC.
So, is my intuition correct or is this statement dependent on AC? Also in either case could you point me to a reference to the fact?
A:
The statement depends on the axiom of choice. It is consistent, modulo large cardinals, that all (well-ordered) infinite cardinals have cofinality $\omega$.
This was first proved by Gitik, around 1980, from a proper class of strongly compact cardinals. The result is significant, and rather involved. It is actually an interesting construction. In a forcing extension of the universe, a suitable inner model $N$ (of $\mathsf{ZF}$) is identified and a cardinal $\kappa$ such that, inside that model, the level $N_\kappa$ is shown to satisfy the statement. I do not think we have models of the statement obtained by class forcing, without at the end cutting the universe at some level.
The result has been improved since, reducing the large cardinals involved, but they are still pretty large, beyond anything we can reach with inner model theory. The best lower bound that we know of is that the statement that all cardinals are singular implies that $\mathsf{AD}$ holds in the $L(\mathbb R)$ of some suitable inner model of a forcing extension. This is a fairly recent (2008) result due to Ralf Schindler and Daniel Busche, see here. Again, it would be interesting to get the result directly in $V$ without having to pass to an extension, but technical difficulties in the implementation of the technique known as the core model induction prevent us from doing this at the moment.
(That large cardinals were needed at all has been known for a long while. A nice short argument, due to Magidor, shows how the fact that $\omega_1$ and $\omega_2$ are singular violates the covering lemma in some inner model and therefore implies that $0^\sharp$ exists, see here.)
A:
Let me add on Andres' wonderful answer, something which I think is missing.
Despite the necessity of large cardinals, it was in fact one of the first uses of the technique of forcing (and symmetric extensions) to show that in fact $\omega_1$ and $\Bbb R$ can be countable unions of countable sets.
This is a classical result due to Feferman and Levy. In her Ph.D. Thesis Ioanna Dimitriou extended this result, and proved the following theorem:
Theorem (2.10) If $V$ is a model of $\sf ZFC$, $\kappa_0$ is a regular cardinal of $V$ and $\rho$ is an ordinal in $V$, then there is a model of $\sf ZF$ with a sequence of successive alternating singular and regular cardinals that starts at $\kappa_0$ and that contains $\rho$-many singular cardinals.
And all that without large cardinals. The large cardinals come into play when we want two successive singular cardinals.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Lounge access on arrival at Singapore airport Terminal 2
I will be arriving at Singapore airport terminal 2 at 3:00 am in the morning and my hotel doesn't allow me early check-in. I have a priority pass. Will I be able to access the Lounge on arrival?
A:
I was at the Singapore airport today and was allowed the entry at the Ambassador Transit Lounge in terminal 2 with no issues whatsoever. The guy at the reception did not even bother checking the boarding pass and He told me that they always take people in holding the PP.
I don't know about the other lounges but you can always go to 'The Haven' arrivals lounge if you are denied entry.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Extract a full-scale image from a SVS file
I am trying to extract the first page of a SVS file using Libtiff.
The SVS file uses JPEG2000 compression for this image.
My plan is:
extracting raw tiles from the first page of the SVS, and
decoding it using OpenJPEG.
Below is what I tried to extract raw tiles from the SVS. I only got a 43KB output file from 152MB svs file (it failed to extract the raw tiles).
I hope someone could let me know how to extract tiles from a SVS file.
int main()
{
const char* filename = "input.svs";
TIFF* tiff_in = TIFFOpen(filename, "r");
TIFF* tiff_out = TIFFOpen("output.raw", "w");
if (tiff_in) {
uint32 imageWidth, imageLength;
uint32 tileWidth, tileLength;
uint32 tileCount, tileByteCounts;
uint32 samplePerPixel, bitsPerSample;
uint32 orientation, planarConfig, photoMetric;
uint32 xResolution, yResolution;
uint32 x, y;
ttile_t tile;
// get fileds from the input file
TIFFGetField(tiff_in, TIFFTAG_IMAGEWIDTH, &imageWidth);
TIFFGetField(tiff_in, TIFFTAG_IMAGELENGTH, &imageLength);
TIFFGetField(tiff_in, TIFFTAG_TILEWIDTH, &tileWidth);
TIFFGetField(tiff_in, TIFFTAG_TILELENGTH, &tileLength);
TIFFGetField(tiff_in, TIFFTAG_SAMPLESPERPIXEL, &samplePerPixel);
TIFFGetField(tiff_in, TIFFTAG_BITSPERSAMPLE, &bitsPerSample);
TIFFGetField(tiff_in, TIFFTAG_TILEBYTECOUNTS, &tileByteCounts);
TIFFGetField(tiff_in, TIFFTAG_ORIENTATION, &orientation);
TIFFGetField(tiff_in, TIFFTAG_PLANARCONFIG, &planarConfig);
TIFFGetField(tiff_in, TIFFTAG_PHOTOMETRIC, &photoMetric);
TIFFGetField(tiff_in, TIFFTAG_XRESOLUTION, &xResolution);
TIFFGetField(tiff_in, TIFFTAG_YRESOLUTION, &yResolution);
// set files to the output file
TIFFSetField(tiff_out, TIFFTAG_IMAGEWIDTH, imageWidth);
TIFFSetField(tiff_out, TIFFTAG_IMAGELENGTH, imageLength);
TIFFSetField(tiff_out, TIFFTAG_TILEWIDTH, tileWidth);
TIFFSetField(tiff_out, TIFFTAG_TILELENGTH, tileLength);
TIFFSetField(tiff_out, TIFFTAG_SAMPLESPERPIXEL, samplePerPixel);
TIFFSetField(tiff_out, TIFFTAG_BITSPERSAMPLE, bitsPerSample);
TIFFSetField(tiff_out, TIFFTAG_PLANARCONFIG, planarConfig);
TIFFSetField(tiff_out, TIFFTAG_PHOTOMETRIC, photoMetric);
TIFFSetField(tiff_out, TIFFTAG_XRESOLUTION, xResolution);
TIFFSetField(tiff_out, TIFFTAG_YRESOLUTION, yResolution);
//TIFFSetField(tiff_out, TIFFTAG_ROWSPERSTRIP, 1);
tdata_t buf = _TIFFmalloc(TIFFTileSize(tiff_in));
for (int tile = 0; tile < TIFFNumberOfTiles(tiff_in); tile++)
{
TIFFReadRawTile(tiff_in, tile, buf, (tsize_t)-1);
TIFFWriteRawTile(tiff_out, tile, buf, (tsize_t)sizeof(buf));
}
_TIFFfree(buf);
TIFFClose(tiff_in);
TIFFClose(tiff_out);
}
return 0;
}
A:
You are writing tiles with 8 bytes each. sizeof(buf) is the size in bytes of the pointer buf. You want to use the number of bytes actually read, which is returned by TIFFReadRawTile:
tsize_t size = TIFFReadRawTile(tiff_in, tile, buf, (tsize_t)-1);
TIFFWriteRawTile(tiff_out, tile, buf, size);
Note that here you are copying the JPEG2000-compressed data to the output file. You'll have to decompress this data using OpenJPEG, then write data of the size of the uncompressed tile, which is tileWidth * tileLength * samplePerPixel * bitsPerSample / 8 in the contiguous planar configuration, or tileWidth * tileLength * bitsPerSample / 8 in the separate planar configuration.
When using TIFFGetField and TIFFSetField, you need to check the return values. A 0 is returned if an error occurred. You cannot depend on values that were not read properly.
Other errors and warnings are typically printed to stderr. If you are developing under Windows, these will typically not be shown. I recommend that you look into TIFFSetErrorHandler and TIFFSetWarningHandler, setting suitable message display functions here will help you immensely during development.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to provide tether/anything-else globally in my meteor1.3 typescript project?
I'm hardly trying to get my existing ng2-prototype running in a meteor1.3 setup. So far i was building the prototype with webpack, and there is a provide plugin to make things like jQuery or Tether available during module building:
plugins: [
new ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"window.Tether": "tether"
})
]
As you can see, i did the same with "tether", since it's still the lib needed by bootstrap 4 alpha.
Now i'm wondering how i could achieve the same in my meteor1.3 project..? As written in the changelogs of the package "angular2-meteor", it is using webpack under the hood now to build everything.
angular2-meteor changelog
So, it should be possible to use the same provide plugin again in meteor1.3, right? But... how?
A:
From the github issue threads of "angular2-meteor":
there are multiple ways: you could install https://atmospherejs.com/coursierprive/tether, or,
since Meteor 1.3 prefers NPM now, you could install Tether NPM and require it before you use bootstrap 4, or, if you want more control and modularity, you could create own local package (in the packages folder) with all dependencies (added from NPMs) you need including Tether (similar to the way angular2-runtime done in this repo).
i will try this out and i'm already sure this will do the trick :) many thx @barbatus ;)
Update:
Ok i'm going with the npm package solution, i had tether installed already. If you don't have it, do this first:
npm install --save tether
Now, the single require statement won't be enough.. bootstrap 4 which i'm trying to include completely is asking for a window.Tether function. So i ended up doing this:
let Tether = require('tether');
window.Tether = Tether;
// import all bootstrap javascript plugins
require('bootstrap');
Cool is, there is also a typings definition file for it now, just add it by running:
typings install --save --ambient tether
After adding it to the window global context, the errors are gone... but ok, the solution trough the webpack provide plugin feels still cleaner -> it will provide the Tether object for each module separately during build, so it won't end up living in the window global context after all. But i'm just lucky to have it running now :)
PS: jQuery is provided anyways by meteor, that's the reason it is already enough to get it running by just including tether alone.
Update: yeah jQuery is included by default - but it is just a package in your /.meteor/packages file ;)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What can you do in background scripts that you can't do in other js files?
*By other js files, I mean the files you include in popup.html.
The following code works, so why should I use a background script?
Content script
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
//Some code
}
);
Script included in popup.html
chrome.tabs.query({active:true,windowId: chrome.windows.WINDOW_ID_CURRENT},
function(tab) {
chrome.tabs.sendMessage(tab[0].id, {method: "someMethod"},
function(response){
//Some code
});
});
This
A:
Background pages live as long as the Chrome browser is active (and even longer if the "background" permission is set). Popup pages are only active when the badge's popup is open. The popup can only be opened by the user.
The background page's document is never visible, whilst the popup page becomes visible on click of the badge's button.
Besides that, there's no difference between background pages and popup pages. They run in the same extension's process, and have access to the same set of APIs.
If your extension only needs to be active while the popup is active, you don't need a background page. To save the state of the popup, just use the synchronous localStorage or the asynchronous chrome.storage API. When the variables you use are too complex to be stored using either API, a background page may be useful.
One example where the use of a background page is beneficial:
Imagine an extension that downloads a huge text file from a server. The creation of the resource is very resource-intensive for the server. Technically, everything can be done from within the popup. However, offloading the task to the background page allows the user to do other tasks while the file is downloading (if you use a popup only, the download will stop when the user closes the popup).
Though you didn't ask, I'd like to make you aware of event pages. They are similar to background pages, with one difference: Event pages are automatically closed when the extension is idle. In other words, event pages are only active when needed! By doing this, your extension will profit from the advantages of background pages without needlessly wasting the user's memory.
My last example is also a perfect example of when an event page has to be used. Besides doing the http request on behalf of the popup, the background page does nothing. If you use an event page instead of a background page, you get the best of both worlds: the popup page can be closed without interrupting the download, and the extension will not waste memory.
Documentation
Learn more about Background pages and Event pages
"Popup" in this answer refers to the optional panel of the chrome.browserAction or chrome.pageAction API, set by declaring the "default_popup" key in the manifest file, or programatically using the setPopup method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using Left() for variable
I'm new to VBA.
So i was trying to append prefixes to a set of values, depending on the first number of each value.
However i get a Type mismatch error on line 4. I suppose it is because I am trying to use Left() on a variable, and it is supposed to be used on a string (or something of that sorts?)
How do i accomplish that?
Thank you in advance
Sub test()
a = UsedRange.Rows.Count
Testvariable = Range("A1", "A" & a)
FirstNo = Left(Testvariable, 1)
For i= 1 To a
If FirstNo(i,1) = "1" Then
Cells(i,2) = "abc" & FirstNo(i,1)
Else Cells(i,2) = "def" & FirstNo(i,1)
End if
Next
End Sub
A:
Trouble is you are trying to take the left of a Range object that happens to give you an array when assigned without the set keyword, when left wants a string.
This post here explains how to convert a range to a string, that you can then pass to left.
How can I convert a range to a string (VBA)?
Sub test()
dim a as long
a = UsedRange.Rows.Count
dim Testvariable as string
Testvariable = RangeToString(Range("A1", "A" & a))
dim FirstNo as string
FirstNo = Left(Testvariable, 1)
dim i as long
For i= 1 To a
If FirstNo(i,1) = "1" Then
Cells(i,2) = "abc" & FirstNo(i,1)
Else
Cells(i,2) = "def" & FirstNo(i,1)
End if
Next
End Sub
Function RangeToString(ByVal myRange as Range) as String
RangeToString = ""
If Not myRange Is Nothing Then
Dim myCell as Range
For Each myCell in myRange
RangeToString = RangeToString & "," & myCell.Value
Next myCell
'Remove extra comma
RangeToString = Right(RangeToString, Len(RangeToString) - 1)
End If
End Function
Also, be sure to always declare your variables correctly.
a = UsedRange.Rows.Count means create a variable called a of type variant and give it the value of UsedRange.Rows.Count
Testvariable = Range("A1", "A" & a) means create a variable called Testvariable of type variant and give it the .value of the range object (an array)
If these were declared properly
dim a as long
a = UsedRange.Rows.Count
dim Testvariable as string
Testvariable = Range("A1", "A" & a)
The assignment of Testvariable would have failed with a much more obvious error, informing you that you can't convert an array to a string.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pass a string by reference in Javascript
I want to create a string and pass it by reference such that I can change a single variable and have that propagate to any other object that references it.
Take this example:
function Report(a, b) {
this.ShowMe = function() { alert(a + " of " + b); }
}
var metric = new String("count");
var a = new Report(metric, "a");
var b = new Report(metric, "b");
var c = new Report(metric, "c");
a.ShowMe(); // outputs: "count of a";
b.ShowMe(); // outputs: "count of b";
c.ShowMe(); // outputs: "count of c";
I want to be able to have this happen:
var metric = new String("count");
var a = new Report(metric, "a");
var b = new Report(metric, "b");
var c = new Report(metric, "c");
a.ShowMe(); // outputs: "count of a";
metric = new String("avg");
b.ShowMe(); // outputs: "avg of b";
c.ShowMe(); // outputs: "avg of c";
Why doesn't this work?
The MDC reference on strings says metric is an object.
I've tried this, which is not what I want, but is very close:
var metric = {toString:function(){ return "count";}};
var a = new Report(metric, "a");
var b = new Report(metric, "b");
var c = new Report(metric, "c");
a.ShowMe(); // outputs: "count of a";
metric.toString = function(){ return "avg";}; // notice I had to change the function
b.ShowMe(); // outputs: "avg of b";
c.ShowMe(); // outputs: "avg of c";
alert(String(metric).charAt(1)); // notice I had to use the String constructor
// I want to be able to call this:
// metric.charAt(1)
The important points here:
I want to be able to use metric like it's a normal string object
I want each report to reference the same object.
A:
Strings in Javascript are already passed "by reference" -- calling a procedure with a string does not involve copying the string's contents. There are two issues at hand:
Strings are immutable. In contrast to C++ strings, once a JavaScript string has been created it cannot be modified.
In JavaScript, variables are not statically assigned slots like in C++. In your code, metric is a label which applies to two entirely separate string variables.
Here's one way to achieve what you want, using closures to implement dynamic scoping of metric:
function Report(a, b) {
this.ShowMe = function() { alert(a() + " of " + b); }
}
var metric = "count";
var metric_fnc = function() { return metric; }
var a = new Report(metric_fnc, "a");
var b = new Report(metric_fnc, "b");
a.ShowMe(); // outputs: "count of a";
metric = "avg";
b.ShowMe(); // outputs: "avg of b";
A:
You can wrap the string in an object and modify the field the string is stored in.
This is similar to what you are doing in the last example only without needing to change the functions.
var metric = { str : "count" }
metric.str = "avg";
Now metric.str will contain "avg"
A:
Closure?
var metric = new function() {
var _value = "count";
this.setValue = function(s) { _value = s; };
this.toString = function() { return _value; };
};
// snip ...
a.ShowMe();
metric.setValue("avg");
b.ShowMe();
c.ShowMe();
or making it a little more generic and performant:
function RefString(s) {
this.value = s;
}
RefString.prototype.toString = function() { return this.value; }
RefString.prototype.charAt = String.prototype.charAt;
var metric = new RefString("count");
// snip ...
a.ShowMe();
metric.value = "avg";
b.ShowMe();
c.ShowMe();
If you don't close on the desired string variable, then I suppose the only other way would be to modify the ShowMe function, as in @John Millikin's answer or re-architect the codebase.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Not able to start Infinispan server
I am trying to start Infinispan server in my Ubuntu machine. Below is my machine-
rkost@rj-vm9-14105:~/infinispan/infinispan-server-6.0.0.Alpha1/bin$
uname -a
Linux rj-vm9-14105 2.6.35-22-server #33-Ubuntu SMP Sun Sep 19
20:48:58 UTC 2010 x86_64 GNU/Linux
I was going through this article and I downloaded Infinispan Server distribution (Infinispan servers (HotRod, REST, Memcached)) from this link. After downloading it, I started running it from my Ubuntu machine like this-
Update:-
root@rj-vm9-14105:/home/rkost/infinispan/infinispan-server-6.0.0.Alpha1/bin# sh standalone.sh
=========================================================================
JBoss Bootstrap Environment
JBOSS_HOME: /home/rkost/infinispan/infinispan-server-6.0.0.Alpha1
JAVA: java
JAVA_OPTS: -server -XX:+UseCompressedOops -Xms64m -Xmx512m -XX:MaxPermSize=256m -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true
=========================================================================
18:11:23,417 INFO [org.jboss.modules] (main) JBoss Modules version 1.2.0.CR1
18:11:23,748 INFO [org.jboss.msc] (main) JBoss MSC version 1.0.4.GA
18:11:23,851 INFO [org.jboss.as] (MSC service thread 1-1) JBAS015899: JBoss Infinispan Server 6.0.0.Alpha1 (AS 7.2.0.Final) starting
18:11:24,998 INFO [org.xnio] (MSC service thread 1-1) XNIO Version 3.0.7.GA
18:11:25,003 INFO [org.xnio.nio] (MSC service thread 1-1) XNIO NIO Implementation Version 3.0.7.GA
18:11:25,010 INFO [org.jboss.as.server] (Controller Boot Thread) JBAS015888: Creating http management service using socket-binding (management-http)
18:11:25,020 INFO [org.jboss.remoting] (MSC service thread 1-1) JBoss Remoting version 3.2.14.GA
18:11:25,097 INFO [org.jboss.as.naming] (ServerService Thread Pool -- 21) JBAS011800: Activating Naming Subsystem
18:11:25,116 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 17) JBAS010280: Activating Infinispan subsystem.
18:11:25,143 INFO [org.jboss.as.connector.logging] (MSC service thread 1-1) JBAS010408: Starting JCA Subsystem (JBoss IronJacamar 1.0.15.Final)
18:11:25,144 INFO [org.jboss.as.security] (ServerService Thread Pool -- 23) JBAS013171: Activating Security Subsystem
18:11:25,386 INFO [org.jboss.as.jsf] (ServerService Thread Pool -- 27) JBAS012605: Activated the following JSF Implementations: [main, 1.2]
18:11:25,408 INFO [org.jboss.as.naming] (MSC service thread 1-2) JBAS011802: Starting Naming Service
18:11:25,413 INFO [org.jboss.as.security] (MSC service thread 1-1) JBAS013170: Current PicketBox version=4.0.15.Final
18:11:26,025 INFO [org.apache.coyote.ajp] (MSC service thread 1-1) JBWEB003046: Starting Coyote AJP/1.3 on ajp-/127.0.0.1:8009
18:11:26,030 INFO [org.apache.coyote.http11] (MSC service thread 1-1) JBWEB003001: Coyote HTTP/1.1 initializing on : http-/127.0.0.1:8080
18:11:26,064 INFO [org.apache.coyote.http11] (MSC service thread 1-1) JBWEB003000: Coyote HTTP/1.1 starting on: http-/127.0.0.1:8080
18:11:26,594 INFO [org.infinispan.server.endpoint] (MSC service thread 1-1) JDGS010000: HotRodServer starting
18:11:26,596 INFO [org.infinispan.server.endpoint] (MSC service thread 1-1) JDGS010001: HotRodServer listening on 127.0.0.1:11222
18:11:26,686 INFO [org.infinispan.server.endpoint] (MSC service thread 1-2) JDGS010000: WebSocketServer starting
18:11:26,686 INFO [org.infinispan.server.endpoint] (MSC service thread 1-2) JDGS010001: WebSocketServer listening on 127.0.0.1:8181
18:11:27,223 INFO [org.infinispan.factories.GlobalComponentRegistry] (MSC service thread 1-1) ISPN000128: Infinispan version: Infinispan '<TBD>' 6.0.0.Alpha1
18:11:27,883 INFO [org.infinispan.jmx.CacheJmxRegistration] (MSC service thread 1-1) ISPN000031: MBeans were successfully registered to the platform MBean server.
18:11:27,892 INFO [org.jboss.as.clustering.infinispan] (MSC service thread 1-1) JBAS010281: Started default cache from local container
18:11:28,165 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC00001: Failed to start service jboss.endpoint.websocket.websocket-connector: org.jboss.msc.service.StartException in service jboss.endpoint.websocket.websocket-connector: JDGS010004: Failed to start WebSocketServer
at org.infinispan.server.endpoint.subsystem.ProtocolServerService.start(ProtocolServerService.java:106)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_20]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_20]
at java.lang.Thread.run(Thread.java:636) [rt.jar:1.6.0_20]
Caused by: org.jboss.netty.channel.ChannelException: Failed to create a selector.
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.openSelector(AbstractNioSelector.java:337)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.<init>(AbstractNioSelector.java:95)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.<init>(AbstractNioWorker.java:51)
at org.jboss.netty.channel.socket.nio.NioWorker.<init>(NioWorker.java:45)
at org.jboss.netty.channel.socket.nio.NioWorkerPool.createWorker(NioWorkerPool.java:45)
at org.jboss.netty.channel.socket.nio.NioWorkerPool.createWorker(NioWorkerPool.java:28)
at org.jboss.netty.channel.socket.nio.AbstractNioWorkerPool.newWorker(AbstractNioWorkerPool.java:99)
at org.jboss.netty.channel.socket.nio.AbstractNioWorkerPool.init(AbstractNioWorkerPool.java:69)
at org.jboss.netty.channel.socket.nio.NioWorkerPool.<init>(NioWorkerPool.java:39)
at org.infinispan.server.core.transport.NettyTransport.<init>(NettyTransport.scala:51)
at org.infinispan.server.core.AbstractProtocolServer.startTransport(AbstractProtocolServer.scala:44)
at org.infinispan.server.core.AbstractProtocolServer.start(AbstractProtocolServer.scala:39)
at org.infinispan.server.websocket.WebSocketServer.start(WebSocketServer.java:63)
at org.infinispan.server.endpoint.subsystem.ProtocolServerService.startProtocolServer(ProtocolServerService.java:123)
at org.infinispan.server.endpoint.subsystem.ProtocolServerService.start(ProtocolServerService.java:100)
... 5 more
Caused by: java.io.IOException: Too many open files
at sun.nio.ch.EPollArrayWrapper.epollCreate(Native Method) [rt.jar:1.6.0_20]
at sun.nio.ch.EPollArrayWrapper.<init>(EPollArrayWrapper.java:87) [rt.jar:1.6.0_20]
at sun.nio.ch.EPollSelectorImpl.<init>(EPollSelectorImpl.java:70) [rt.jar:1.6.0_20]
at sun.nio.ch.EPollSelectorProvider.openSelector(EPollSelectorProvider.java:36) [rt.jar:1.6.0_20]
at java.nio.channels.Selector.open(Selector.java:226) [rt.jar:1.6.0_20]
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.openSelector(AbstractNioSelector.java:335)
... 19 more
18:11:28,181 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-1) MSC00001: Failed to start service jboss.endpoint.hotrod.hotrod-connector: org.jboss.msc.service.StartException in service jboss.endpoint.hotrod.hotrod-connector: JDGS010004: Failed to start HotRodServer
at org.infinispan.server.endpoint.subsystem.ProtocolServerService.start(ProtocolServerService.java:106)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_20]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_20]
at java.lang.Thread.run(Thread.java:636) [rt.jar:1.6.0_20]
Caused by: org.jboss.netty.channel.ChannelException: Failed to open a server socket.
at org.jboss.netty.channel.socket.nio.NioServerSocketChannel.<init>(NioServerSocketChannel.java:57)
at org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory.newChannel(NioServerSocketChannelFactory.java:205)
at org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory.newChannel(NioServerSocketChannelFactory.java:85)
at org.jboss.netty.bootstrap.ServerBootstrap.bindAsync(ServerBootstrap.java:329)
at org.jboss.netty.bootstrap.ServerBootstrap.bind(ServerBootstrap.java:266)
at org.infinispan.server.core.transport.NettyTransport.start(NettyTransport.scala:83)
at org.infinispan.server.core.AbstractProtocolServer.startTransport(AbstractProtocolServer.scala:49)
at org.infinispan.server.hotrod.HotRodServer.startTransport(HotRodServer.scala:67)
at org.infinispan.server.core.AbstractProtocolServer.start(AbstractProtocolServer.scala:39)
at org.infinispan.server.hotrod.HotRodServer.start(HotRodServer.scala:51)
at org.infinispan.server.hotrod.HotRodServer.start(HotRodServer.scala:27)
at org.infinispan.server.endpoint.subsystem.ProtocolServerService.startProtocolServer(ProtocolServerService.java:123)
at org.infinispan.server.endpoint.subsystem.ProtocolServerService.start(ProtocolServerService.java:100)
... 5 more
Caused by: java.net.SocketException: Too many open files
at sun.nio.ch.Net.socket0(Native Method) [rt.jar:1.6.0_20]
at sun.nio.ch.Net.serverSocket(Net.java:119) [rt.jar:1.6.0_20]
at sun.nio.ch.ServerSocketChannelImpl.<init>(ServerSocketChannelImpl.java:91) [rt.jar:1.6.0_20]
at sun.nio.ch.SelectorProviderImpl.openServerSocketChannel(SelectorProviderImpl.java:51) [rt.jar:1.6.0_20]
at java.nio.channels.ServerSocketChannel.open(ServerSocketChannel.java:92) [rt.jar:1.6.0_20]
at org.jboss.netty.channel.socket.nio.NioServerSocketChannel.<init>(NioServerSocketChannel.java:55)
... 17 more
18:11:28,252 INFO [org.infinispan.jmx.CacheJmxRegistration] (MSC service thread 1-1) ISPN000031: MBeans were successfully registered to the platform MBean server.
18:11:28,251 INFO [org.infinispan.jmx.CacheJmxRegistration] (MSC service thread 1-2) ISPN000031: MBeans were successfully registered to the platform MBean server.
18:11:28,256 INFO [org.jboss.as.clustering.infinispan] (MSC service thread 1-1) JBAS010281: Started other cache from security container
18:11:28,263 INFO [org.jboss.as.clustering.infinispan] (MSC service thread 1-2) JBAS010281: Started jboss-web-policy cache from security container
18:11:28,267 INFO [org.infinispan.jmx.CacheJmxRegistration] (MSC service thread 1-2) ISPN000031: MBeans were successfully registered to the platform MBean server.
18:11:28,268 INFO [org.jboss.as.clustering.infinispan] (MSC service thread 1-2) JBAS010281: Started memcachedCache cache from local container
18:11:28,271 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC00001: Failed to start service jboss.server.controller.management.security_realm.ManagementRealm.properties_authentication: org.jboss.msc.service.StartException in service jboss.server.controller.management.security_realm.ManagementRealm.properties_authentication: JBAS015228: Unable to load properties
at org.jboss.as.domain.management.security.PropertiesFileLoader.start(PropertiesFileLoader.java:81)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_20]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_20]
at java.lang.Thread.run(Thread.java:636) [rt.jar:1.6.0_20]
Caused by: java.io.FileNotFoundException: /home/rkost/infinispan/infinispan-server-6.0.0.Alpha1/standalone/configuration/mgmt-users.properties (Too many open files)
at java.io.FileInputStream.open(Native Method) [rt.jar:1.6.0_20]
at java.io.FileInputStream.<init>(FileInputStream.java:137) [rt.jar:1.6.0_20]
at org.jboss.as.domain.management.security.PropertiesFileLoader.getProperties(PropertiesFileLoader.java:108)
at org.jboss.as.domain.management.security.PropertiesFileLoader.start(PropertiesFileLoader.java:79)
... 5 more
18:11:28,272 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-1) MSC00001: Failed to start service jboss.server.controller.management.security_realm.ApplicationRealm.properties_authentication: org.jboss.msc.service.StartException in service jboss.server.controller.management.security_realm.ApplicationRealm.properties_authentication: JBAS015228: Unable to load properties
at org.jboss.as.domain.management.security.PropertiesFileLoader.start(PropertiesFileLoader.java:81)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_20]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_20]
at java.lang.Thread.run(Thread.java:636) [rt.jar:1.6.0_20]
Caused by: java.io.FileNotFoundException: /home/rkost/infinispan/infinispan-server-6.0.0.Alpha1/standalone/configuration/application-users.properties (Too many open files)
at java.io.FileInputStream.open(Native Method) [rt.jar:1.6.0_20]
at java.io.FileInputStream.<init>(FileInputStream.java:137) [rt.jar:1.6.0_20]
at org.jboss.as.domain.management.security.PropertiesFileLoader.getProperties(PropertiesFileLoader.java:108)
at org.jboss.as.domain.management.security.PropertiesFileLoader.start(PropertiesFileLoader.java:79)
... 5 more
18:11:28,284 INFO [org.infinispan.jmx.CacheJmxRegistration] (MSC service thread 1-1) ISPN000031: MBeans were successfully registered to the platform MBean server.
18:11:28,284 INFO [org.jboss.as.clustering.infinispan] (MSC service thread 1-1) JBAS010281: Started namedCache cache from local container
18:11:28,285 INFO [org.infinispan.server.endpoint] (MSC service thread 1-1) JDGS010000: REST starting
18:11:28,287 ERROR [stderr] (MSC service thread 1-1) ZoneInfo: /usr/share/javazi/ZoneInfoMappings (Too many open files)
18:11:28,289 WARN [org.jboss.modules] (MSC service thread 1-1) Failed to define class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap in Module "org.jboss.resteasy.resteasy-jaxrs:main" from local module loader @19e3118a (finder: local module finder @a94884d (roots: /home/rkost/infinispan/infinispan-server-6.0.0.Alpha1/modules,/home/rkost/infinispan/infinispan-server-6.0.0.Alpha1/modules/system/layers/base)): org.jboss.modules.ModuleLoadError: No module.xml file found at /home/rkost/infinispan/infinispan-server-6.0.0.Alpha1/modules/system/layers/base/org/apache/commons/codec/main/module.xml
at org.jboss.modules.ModuleLoadException.toError(ModuleLoadException.java:78) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.Module.getPathsUnchecked(Module.java:1180) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.Module.loadModuleClass(Module.java:513) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:182) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120) [jboss-modules.jar:1.2.0.CR1]
at java.lang.ClassLoader.defineClass1(Native Method) [rt.jar:1.6.0_20]
at java.lang.ClassLoader.defineClass(ClassLoader.java:634) [rt.jar:1.6.0_20]
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) [rt.jar:1.6.0_20]
at org.jboss.modules.ModuleClassLoader.doDefineOrLoadClass(ModuleClassLoader.java:338) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:402) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:254) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:73) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.Module.loadModuleClass(Module.java:518) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:182) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120) [jboss-modules.jar:1.2.0.CR1]
at org.infinispan.server.endpoint.subsystem.RestService.start(RestService.java:133) [infinispan-server-endpoints-6.0.0.Alpha1.jar:6.0.0.Alpha1]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_20]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_20]
at java.lang.Thread.run(Thread.java:636) [rt.jar:1.6.0_20]
18:11:28,291 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-1) MSC00001: Failed to start service jboss.endpoint.rest.rest-connector: org.jboss.msc.service.StartException in service jboss.endpoint.rest.rest-connector: Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1767) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_20]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_20]
at java.lang.Thread.run(Thread.java:636) [rt.jar:1.6.0_20]
Caused by: java.lang.NoClassDefFoundError: org/jboss/resteasy/plugins/server/servlet/ResteasyBootstrap
at org.infinispan.server.endpoint.subsystem.RestService.start(RestService.java:133)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
... 3 more
Caused by: java.lang.ClassNotFoundException: org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap from [Module "org.infinispan.server.endpoint:main" from local module loader @19e3118a (finder: local module finder @a94884d (roots: /home/rkost/infinispan/infinispan-server-6.0.0.Alpha1/modules,/home/rkost/infinispan/infinispan-server-6.0.0.Alpha1/modules/system/layers/base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398) [jboss-modules.jar:1.2.0.CR1]
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120) [jboss-modules.jar:1.2.0.CR1]
... 6 more
18:11:28,293 INFO [org.infinispan.server.endpoint] (MSC service thread 1-2) JDGS010000: MemcachedServer starting
18:11:28,294 INFO [org.infinispan.server.endpoint] (MSC service thread 1-2) JDGS010001: MemcachedServer listening on 127.0.0.1:11211
18:11:28,295 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC00001: Failed to start service jboss.endpoint.memcached.memcached-connector: org.jboss.msc.service.StartException in service jboss.endpoint.memcached.memcached-connector: JDGS010004: Failed to start MemcachedServer
at org.infinispan.server.endpoint.subsystem.ProtocolServerService.start(ProtocolServerService.java:106)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA.jar:1.0.4.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.6.0_20]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.6.0_20]
at java.lang.Thread.run(Thread.java:636) [rt.jar:1.6.0_20]
Caused by: org.jboss.netty.channel.ChannelException: Failed to create a selector.
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.openSelector(AbstractNioSelector.java:337)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.<init>(AbstractNioSelector.java:95)
at org.jboss.netty.channel.socket.nio.NioServerBoss.<init>(NioServerBoss.java:49)
at org.jboss.netty.channel.socket.nio.NioServerBossPool.newBoss(NioServerBossPool.java:55)
at org.jboss.netty.channel.socket.nio.NioServerBossPool.newBoss(NioServerBossPool.java:26)
at org.jboss.netty.channel.socket.nio.AbstractNioBossPool.init(AbstractNioBossPool.java:65)
at org.jboss.netty.channel.socket.nio.NioServerBossPool.<init>(NioServerBossPool.java:40)
at org.infinispan.server.core.transport.NettyTransport.<init>(NettyTransport.scala:39)
at org.infinispan.server.core.AbstractProtocolServer.startTransport(AbstractProtocolServer.scala:44)
at org.infinispan.server.core.AbstractProtocolServer.start(AbstractProtocolServer.scala:39)
at org.infinispan.server.memcached.MemcachedServer.start(MemcachedServer.scala:30)
at org.infinispan.server.memcached.MemcachedServer.start(MemcachedServer.scala:17)
at org.infinispan.server.endpoint.subsystem.ProtocolServerService.startProtocolServer(ProtocolServerService.java:123)
at org.infinispan.server.endpoint.subsystem.ProtocolServerService.start(ProtocolServerService.java:100)
... 5 more
Caused by: java.io.IOException: Too many open files
at sun.nio.ch.IOUtil.initPipe(Native Method) [rt.jar:1.6.0_20]
at sun.nio.ch.EPollSelectorImpl.<init>(EPollSelectorImpl.java:67) [rt.jar:1.6.0_20]
at sun.nio.ch.EPollSelectorProvider.openSelector(EPollSelectorProvider.java:36) [rt.jar:1.6.0_20]
at java.nio.channels.Selector.open(Selector.java:226) [rt.jar:1.6.0_20]
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.openSelector(AbstractNioSelector.java:335)
... 18 more
18:11:28,935 ERROR [org.jboss.as.controller.client] (Controller Boot Thread) JBAS014781: Step handler org.jboss.as.logging.LoggingOperations$CommitOperationStepHandler@3c9076d for operation add at address [("subsystem" => "logging")] failed handling operation rollback -- JBAS011565: Failed to write configuration file /home/rkost/infinispan/infinispan-server-6.0.0.Alpha1/standalone/configuration/logging.properties
18:11:28,937 INFO [org.jboss.as.controller] (Controller Boot Thread) JBAS014774: Service status report
JBAS014777: Services which failed to start: service jboss.endpoint.rest.rest-connector: org.jboss.msc.service.StartException in service jboss.endpoint.rest.rest-connector: Failed to start service
service jboss.server.controller.management.security_realm.ManagementRealm.properties_authentication: org.jboss.msc.service.StartException in service jboss.server.controller.management.security_realm.ManagementRealm.properties_authentication: JBAS015228: Unable to load properties
service jboss.endpoint.memcached.memcached-connector: org.jboss.msc.service.StartException in service jboss.endpoint.memcached.memcached-connector: JDGS010004: Failed to start MemcachedServer
service jboss.endpoint.hotrod.hotrod-connector: org.jboss.msc.service.StartException in service jboss.endpoint.hotrod.hotrod-connector: JDGS010004: Failed to start HotRodServer
service jboss.endpoint.websocket.websocket-connector: org.jboss.msc.service.StartException in service jboss.endpoint.websocket.websocket-connector: JDGS010004: Failed to start WebSocketServer
service jboss.server.controller.management.security_realm.ApplicationRealm.properties_authentication: org.jboss.msc.service.StartException in service jboss.server.controller.management.security_realm.ApplicationRealm.properties_authentication: JBAS015228: Unable to load properties
18:11:28,945 ERROR [org.jboss.as.server] (Controller Boot Thread) JBAS015956: Caught exception during boot: java.lang.NullPointerException
at org.jboss.as.controller.persistence.ConfigurationFile.createHistoryDirectory(ConfigurationFile.java:482) [jboss-as-controller-7.2.0.Final.jar:7.2.0.Final]
at org.jboss.as.controller.persistence.ConfigurationFile.successfulBoot(ConfigurationFile.java:306) [jboss-as-controller-7.2.0.Final.jar:7.2.0.Final]
at org.jboss.as.controller.persistence.BackupXmlConfigurationPersister.successfulBoot(BackupXmlConfigurationPersister.java:65) [jboss-as-controller-7.2.0.Final.jar:7.2.0.Final]
at org.jboss.as.controller.AbstractControllerService.finishBoot(AbstractControllerService.java:234) [jboss-as-controller-7.2.0.Final.jar:7.2.0.Final]
at org.jboss.as.server.ServerService.boot(ServerService.java:310) [jboss-as-server-7.2.0.Final.jar:7.2.0.Final]
at org.jboss.as.controller.AbstractControllerService$1.run(AbstractControllerService.java:188) [jboss-as-controller-7.2.0.Final.jar:7.2.0.Final]
at java.lang.Thread.run(Thread.java:636) [rt.jar:1.6.0_20]
18:11:28,945 FATAL [org.jboss.as.server] (Controller Boot Thread) JBAS015957: Server boot has failed in an unrecoverable manner; exiting. See previous messages for details.
18:11:28,959 INFO [org.jboss.as.controller] (MSC service thread 1-1) JBAS014774: Service status report
Does anyone know why I am getting the exception? And what I should do to fix the problem? I have spend whole one day to figure this thing out.
A:
I saw you already got it work. (https://community.jboss.org/message/828728)
It didn't work for you after changing /etc/security/limits.conf numbers because changes in this file are applied after re-login.
For other people with this problem, please, see https://docs.jboss.org/author/display/ISPN/Contributing+-+The+test+suite, set your limits accordingly and re-login.
Check your limits using
ulimit -a
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Optimization: Need to cut-down on server load
Our predicament is that we are using 3 media queries with different layouts which means that we're essentially generating all of the content 3 times. For instance:
<div class="small-media">
{embed="template/view_small"}
</div>
<div class="medium-media">
{embed="template/view_medium"}
</div>
<div class="large-media">
{embed="template/view_large"}
</div>
You can see how ridiculous this is. We have tons of things being pulled in and we're starting to see overages on our data for doing it this way.
We're wondering if there's a way to use PHP (or EE itself) at the top of the document to load everything once and then send only the pertinent data to the nested templates at each media query.
Thanks for any input on this.
A:
What you're doing isn't really the way to use media queries.
Why is the 'data' (from which I read 'content') different based on the user agent? Is it actually different content or are you simply talking about layout?
I would say your options here are;
Output everything once and use CSS Media Queries properly to reformat the content appropriately for the device being used to access it. i.e Make the site responsive. There should be few, if any, instances where you'd need to duplicate output data like this.
Media queries should be used to alter how elements are displayed and interact with other elements, adjust page flow or show/hide elements from view. The underlying page markup and content should be identical regardless of the user agent properties.
There are numerous articles and tutorials around regarding this approach. Try http://mobile.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/ to start with and descend down the rabbit-hole from there!
Use separate templates (or even domains) for each 'version' of the site and sniff the device when someone lands on a page, then redirect to the appropriate version. The disadvantage of this is multiple URLs for what is essentially the same content so be sure to specify canonical URLs for each page.
You could use PHP to sniff device properties and use a PHP conditional to add the template partial as required. There are a number of libraries available for doing this. I can't recommend any though since I haven't used them.
Try this library as a starting point https://code.google.com/p/php-mobile-detect/
Use an add-on to do the detection. Try http://devot-ee.com/add-ons/detect-mobile. I don't know whether this will ease the load as you may find that EE's parsing engine will still do more than it needs to. It depends when the add-on fits in the parse order.
Use Stash. Someone else mentioned this so I won't go into it further here.
Personally I'd go with option 1.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is update attributes not on the product creation form?
Why is update attributes not on the product creation form?
Why is it on the "Manage Products" Grid?
Thanks
A:
Because you cannot update something that hasn't been created yet.
Maybe you misunderstood what "update attributes" means.
It doesn't actually update any attribute. It updates attribute values for certain products.
You can select from the grid existing products and bulk update the value for one or more attributes.
All the products you select will then have the same value for certain attributes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Calculating the max and index of max within a section of array
Following the StackOverflow post Elegantly calculate mean of first three values of a list I have tweaked the code to find the maximum.
However, I also require to know the position/index of the max.
So the code below calculates the max value for the first 3 numbers and then the max value for the next 3 numbers and so on.
For example for a list of values [6 3 7 4 6 9 2 6 7 4 3 7 7 2 5 4 1 7 5 1]. The code below takes the first 3 values 6,3,7 and outputs the max as 7 and then for the next 3 values 4,6,9 outputs the value 9 and so on.
But I also want to find which position/index they are at, 1.e 7 is at position 2 and 9 at position 5. The final result [2,5,8,11,12,...]. Any ideas on how to calculate the index. Thanks in advance.
import numpy as np
np.random.seed(42)
test_data = np.random.randint(low = 0, high = 10, size = 20)
maxval = [max(test_data[i:i+3]) for i in range(0,len(test_data),3)]
print(test_data)
print(maxval)
output: test_data : [6 3 7 4 6 9 2 6 7 4 3 7 7 2 5 4 1 7 5 1]
output: [7, 9, 7, 7, 7, 7, 5]
A:
import numpy as np
np.random.seed(42)
test_data = np.random.randint(low = 0, high = 10, size = 20)
maxval = [max(test_data[i:i+3]) for i in range(0,len(test_data),3)]
index = [(np.argmax(test_data[i: i+3]) + i) for i in range(0,len(test_data),3)]
print(test_data)
print(maxval)
print(index)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Way to input caligraphic letter as a axis label in Mathematica plot
In my paper written in LATEX, I used a symbol $\mathcal{T}$ and I want to put it in the axis label of my plot.
However I could not find such functionality in Mathematica. Is it possible?
A:
You can find calligraphic script under the Palettes' Special Characters menu. E.g.
Plot[Sin[x], {x, 0, 6 Pi}, AxesLabel -> {\[ScriptCapitalT], None}]
Or, if you specifically want the LaTeX Mathcal font - apparently cmbsy10 - you can download and install it, and specify it in the Style option:-
Plot[Sin[x], {x, 0, 6 Pi}, AxesLabel -> {Style["T", FontFamily -> "cmbsy10"], None}]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I get image coordinates on mouseover with three.js?
I have an image and want to use three.js to make it so that when i mouse over the image, it gives me the coordinates the mouse is over (ie: top left corner of the image is 0,0)
If possible, I would also like to take it a step further to be able to rotate that image, and be able to get the same coordinates when mousing over the image.
How do I accomplish this? Im having trouble with this.
A:
Perhaps it would be better to solve this natively with canvas, but it involves Math. Canvas only display pixels so you need to hold track of the images. I found tremendous help reading the source code from this site Canvas-pictures . Therefore the props should go to Addy Osmani
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to compare time to a time range specified in Prolog?
Let's say i have a structure comparetime(hours,mins),
when a user keys example comparetime(10,40) ,
the structure will make comparison on a time range specified example
timing entered
1) from 10:00 to 12:00 will print a message and
2) from 18:00 to 20:00 will print a message .
if the time keyed is not inside the range, it will also print a message.
how can I do this ?
it's easy to compare words but i'm really having a tough time with comparing time.
A:
It's easy compare words?
You should try it when internationalization is involved to appreciate how difficult could be!
Far easier is compare pair of integers, as from your problem (if I understand the question).
message_on_range(1, 10:00, 12:00, 'it\'s morning!').
message_on_range(2, 18:00, 20:00, 'it\'s evening!').
comparetime(Hours, Mins) :-
message_on_range(_, Start, Stop, Message),
less_equal_time(Start, Hours:Mins),
less_equal_time(Hours:Mins, Stop),
write(Message), nl.
comparetime(_Hours, _Mins) :-
write('please check your clock!'), nl.
less_equal_time(H1:S1, H2:S2) :-
H1 == H2 -> S1 =< S2 ; H1 < H2.
You should be aware of Prolog features: your problem could require a cut after the message has been printed! I.e.
...
less_equal_time(Hours:Mins, Stop),
write(Message), nl, !.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
sudo nautilus error in 16.04
I'm trying to set up localhost with these instructions
Now at step 11 I'm supposed to open nautilus in terminal but whatever I do it throws some error at me.
I tried reinstall and update nautilus with no luck; the same errors appear after using sudo nautilus.
This is what the error looks like.
(nautilus:4594): GLib-GIO-CRITICAL **: g_dbus_interface_skeleton_unexport: assertion 'interface_->priv->connections != NULL' failed
(nautilus:4594): GLib-GIO-CRITICAL **: g_dbus_interface_skeleton_unexport: assertion 'interface_->priv->connections != NULL' failed
(nautilus:4594): Gtk-CRITICAL **: gtk_icon_theme_get_for_screen: assertion 'GDK_IS_SCREEN (screen)' failed
(nautilus:4594): GLib-GObject-WARNING **: invalid (NULL) pointer instance
(nautilus:4594): GLib-GObject-CRITICAL **: g_signal_connect_object: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed
I'm new to Linux and Ubuntu. I tried to google for the errors but without luck.
In Ubuntu I only replaced gnome network with wicd network manager
thanks in advance for any suggestions or help
Ivo
A:
These are not errors. These are warnings and all warnings are to be ignored.
With that said, you should use sudo -i to run gtk applications with sudo.
sudo -i nautilus
These warnings are normal and are to be ignored safely.
Although a fix is not necessary, there is a workaround.
The only work around requires you install the development files:
sudo apt-get update
sudo apt-get install libgdk-pixbuf2.0-dev
sudo gdk-pixbuf-query-loaders --update-cache
sudo killall nautilus
That should take care of most of the warnings.
If you don't like to see output in the terminal after running the command, you can use the nohup command like so:
nohup sudo -i nautilus
or
nohup sudo -i nautilus &
Again, in the future, you can ignore warnings like these unless there is a problem running the application.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Form Submit Button Works, but not Submit() in Link
I've done this so often before on different websites, but can't get it to work now.
I've got a simple form that posts perfectly well using a submit button, but for a specific reason I actually need it to submit via a url link instead. I'm using submit(). The form submits, but the data isn't posting.
What am I missing?
<html>
<body>
<?
if(isset($_POST['bar'])) { echo 'testing button<br>'; }
if(isset($_POST['information'])) {
echo $_POST['information'];
echo '</br>Info successfully posted.';
}
?>
<form action="test.php" method="post" id="fooform">
Hello World.<br>
Select checkbox: <input type="checkbox" id="information" name="information" value="yes">
<input type="submit" name="bar" value="Send"><br>
<a href="test.php" onclick="SubmitForm('fooform');">Confirm and Post</a><br>
<a href="test.php" onclick="this.form.submit();">Post Directly </a>
</form>
<script type="text/javascript">
function SubmitForm(formId) {
var oForm = document.getElementById(formId);
alert("Submitting");
if (oForm) { oForm.submit(); }
else { alert("DEBUG - could not find element " + formId); }
}
</script>
</body>
</html>
A:
The form starts to submit, then the href of the link is followed, and this cancels the form submission.
If you are using old-style onclick attributes, then return false; at the end to prevent the default action.
You would, however, be better off using a submit button (you are submitting a form). You can use CSS to change its appearance.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
seq to vec conversion - Key must be integer
I want to get the indices of nil elements in a vector eg.
[1 nil 3 nil nil 4 3 nil] => [1 3 4 7]
(defn nil-indices [vec]
(vec (remove nil? (map
#(if (= (second %) nil) (first %))
(partition-all 2 (interleave (range (count vec)) vec)))))
)
Running this code results in
java.lang.IllegalArgumentException: Key must be integer
(NO_SOURCE_FILE:0)
If I leave out the (vec) call surrounding everything, it seems to work, but returns a sequence instead of a vector.
Thank you!
A:
Try this instead:
(defn nil-indices [v]
(vec (remove nil? (map
#(if (= (second %) nil) (first %))
(partition-all 2 (interleave (range (count v)) v))))))
Clojure is a LISP-1: It has a single namespace for both functions and data, so when you called (vec ...), you were trying to pass your result sequence to your data as a parameter, not to the standard-library vec function.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get values from DB field into an array with PHP
I have a field in my DB that holds value separated by commas like;
$tmp_list = "COB,ISJ,NSJ,"
Now when I fetch that the row, I would like to have them in an array.
I have used array($tmp_list) but I get the values in one line only like:
[0] => 'COB,ISJ,NSJ,'
instead of
[0] => 'COB',
[1] => 'ISJ',
[2] => 'NSJ'
All help is appriciated.
A:
Use explode:
$arr = explode(',', $tmp_list);
If you like, remove the trailing comma using rtrim first:
$arr = explode(',', rtrim($tmp_list, ','));
You can also trim each element if there's a chance of getting any unwanted leading/trailing whitespace in one or more elements (as per @machine's suggestion):
$arr = array_map('trim', explode(',', rtrim($tmp_list, ',')));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get latest SVN tag in Jenkins
I would need to checkout the latest SVN tag to my Jenkins build job workspace. With tag I mean the copied folder, often used to create milestones.
I read from some stackoverflow question that one could get the latest e.g. with
"svn ls .../path/to/repo/tags | tail -n 1"
, but I don't think this can be given to Jenkins SCM field. I believe Jenkins requires the exact location in SVN. Any ideas? I would believe this is actually quite a common requirement in large projects....
A:
Suggested answer is almost correct on the assumption that:
Incremental alpha-numeric permanent naming scheme used
BASE path somehow added to result of pipe (ls output relative path to tags/)
If the above conditions are not fulfilled, you have to use slightly different command and some piece of business logic "Latest tag have the highest revision number"
>svn ls -v http://mayorat.ursinecorner.ru:8088/svn/Hello/tags/
22 lazybadg июл 17 2010 ./
11 lazybadg июл 17 2010 1.0/
22 lazybadg июл 17 2010 1.1/
output of this ls can be gawk'ed, most recent revision found in $1, relative path of needed tag in $6 (or $5, I'm lazy to test)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Expecting single values but multivalues
I am sorting an array of alphanumerics entered in an input field by the user and the result is correct.
const sortedNumbers = values.sort(function (a, b){
if (a > b) {
return 1;
} else {
return -1;
}
});
Array(3) [ "2a", "2b", "2f" ]
However, when displaying the result in HTML using the script below, I was expecting each alphanumeric in one span
document.querySelector('.pyramid').innerHTML = sortedNumbers.map(val => `<span class="values">${values}</span>`).join('');
The result however is three spans with all three alphanumerics
<span class="values">2a,2b,2f</span><span class="values">2a,2b,2f</span><span class="values">2a,2b,2f</span>
Now I am wondering, can I separate the alphanumerics so that they are each in their own span?
A:
You're using values in your template string instead of val
document.querySelector('.pyramid').innerHTML = sortedNumbers.map(val => `<span class="values">${val}</span>`).join('');
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scala akka : implement abstract class with subtype parameter
I have a problem with my design. I just want to do this but I cannot achieve it. Compilator complains about the process method not implemented in MyProcessor so MyProcessor should be abstract...
trait Event
abstract class EventProcessor extends Actor{
def receive ={
case evt : Event => process(evt)
case evts : Iterable[Event] => process(evts)
}
def process(event :Event): Iterable[SomeObject]
def process(events :Iterable[Event])={
events.flatMap(process)
}
}
case class MyEvent extends Event
class MyProcessor extends Processor{
def process(event :MyEvent)={
some processing...
}
}
I am pretty sure it's a well known pattern. What is your method ?
I need 2 things :
How to correctly implement subclass with type parameter (as decribe in first answer ?)
How to go through type erasure ?
EDIT : solution
trait Event
abstract class EventProcessor[T<:Event:ClassTag] extends Actor{
def receive ={
case evt : T=> process(evt)
case evts : Iterable[T] => process(evts)
}
def process(event :T): Iterable[SomeObject]
def process(events :Iterable[T])={
events.flatMap(process)
}
}
case class MyEvent extends Event
class MyProcessor extends Processor[MyEvent]{
def process(event :MyEvent)={
some processing...
}
}
A:
You need a type parameter:
abstract class EventProcessor[T <: Event] {
def process(event: T)
}
class MyProcessor extends Processor[MyEvent] {
def process(event: MyEvent)
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to filtering javascript array of objects
I have got two arrays . I am filtering based groupKey with PubSidebar.
let groupKey = ['oaDeal', 'Journals', 'Deposit']
// This array of object will be filtering with groupKey
const PubSidebar = [
{
value: 'Dashboard',
role: 'public',
},
{
value: 'oaDeal',
role: 'private',
content: [
{
role: 'private',
value: 'oaDeal',
},
],
},
{
value: 'Journals',
role: 'public',
content: [
{
role: 'private',
value: 'Journals',
},
{
role: 'private',
value: 'Token',
},
{
role: 'private',
value: 'policy',
},
{
role: 'private',
value: 'Deposit',
},
{ role: 'public', value: 'test' },
],
},
]
// Here is my trying code. I am filtering PubSidebar
const res = PubSidebar.filter(x => {
// when it's main outerloop role public or private and groupKey matched
if (
x.role === 'public' ||
(x.role === 'private' && groupKey.includes(x.value))
) {
// then if inner-array exist then inner array filtering
if (x.content) {
// inside content assign condition public or private and groupKey
let tempX = x.content.filter(
y =>
y.role === 'public' ||
(y.role === 'private' && groupKey.includes(y.value)) ||
x.value === y.value
)
x.content = tempX
console.log(tempX)
return x
} else {
// Other wise give me a single object public
console.log(x)
return x
}
}
})
I am facing problem to pass objects inside content array if parents value: Journals or Deposits or any value or role:pubic. I have to pass value inside content array based on groupKey.
If Journals and Deposits is existed , then adding Journals and Deposit data inside content array, including with public data . (three Objects)
If Journals is existed , then adding Journals data inside content array including with public data(two Objects)
If Deposits is existed , then adding Deposits data inside content array including with public data(two Objects)
if GroupKey journals is matched with content object in pubsidebar then two objects , we will get
{
value: 'Journals',
role: 'public',
content: [
{
role: 'private',
value: 'Journals',
},
{ role: 'public', value: 'test' },
],
}
if GroupKey Deposits is matched with content object in pubsidebar then two objects
{
value: 'Deposit',
role: 'public',
content: [
{
role: 'private',
value: 'Deposit',
},
{ role: 'public', value: 'test' },
],
}
if GroupKey Journals and Deposits is matched with content object in pubsidebar then three objects ,
{
value: 'Deposit' || "Journals",
role: 'public',
content: [
{
role: 'private',
value: 'Journals',
},
{
role: 'private',
value: 'Deposit',
},
{ role: 'public', value: 'test' },
],
}
A:
If I understand correctly you want to filter PubSidebar. Keeping values if they have a role of public or a value of whats included in the groupKey. If so this would be your function:
PubSidebar.filter(x => (x.role === 'public' || groupKey.includes(x.value));
If you want to run that on content as well we could pull it apart:
const filterByGroup = (x) => (x.role === 'public' || groupKey.includes(x.value));
let result = [];
for (let i = 0; i < PubSidebar.length; i++) {
const item = PubSidebar[i];
if (filterByGroup(item)) {
if (item.content) {
item.content = item.content.filter(filterByGroup);
}
result = [ ...result, item ];
}
}
Snippet:
let groupKey = ['oaDeal', 'Journals', 'Deposit']
const PubSidebar = [{
value: 'Dashboard',
role: 'public',
},
{
value: 'oaDeal',
role: 'private',
content: [{
role: 'private',
value: 'oaDeal',
}, ],
},
{
value: 'Journals',
role: 'public',
content: [{
role: 'private',
value: 'Journals',
},
{
role: 'private',
value: 'Token',
},
{
role: 'private',
value: 'policy',
},
{
role: 'private',
value: 'Deposit',
},
{
role: 'public',
value: 'test'
},
],
},
]
const filterByGroup = (x) => (x.role === 'public' || groupKey.includes(x.value));
let result = [];
for (let i = 0; i < PubSidebar.length; i++) {
const item = PubSidebar[i];
if (filterByGroup(item)) {
if (item.content) {
item.content = item.content.filter(filterByGroup);
}
result = [...result, item];
}
}
console.log(result);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
GWT : null stack
I get this exception every time when I want do some operation.
(TypeError): b.k.g.E is null stack: TBe([object Object]) ....
How can I correct it?
A:
First, the message should be read as "X is null" and "stack: ...", not "null stack".
You can "deobfuscate" what TBe means by looking at the symbolMap generated by GWT (by default in WEB-INF/deploy): find the symbolMap file corresponding to the permutation your browser is loading (the symbolMap file name is the same as the cache.html file loaded by your browser) and then search for TBe within it (case sensitive!), and it'll give you the corresponding method in your Java code. That might give you a hint as to what could be null.
Also, if you use Chrome, you can pretty-print the JS code in the Dev Tools, which allows you to easily debug the code: set a breakpoint in the TBe function and debug, step-by-step, inspecting variables, etc. Just as you do in Java within Eclipse (or whichever your IDE).
Note that GWT 2.5 will generate SourceMaps which will allow you to see and "debug" your Java code from within your browser! Screenshot here, and design doc there.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Difference between 上げる and 与える
I have some notes from many years back when I began to do Japanese. As you might expect, I am suspicious of my understanding at the time and of what I've written.
I have two verbs for "to give" and would like to check what the differences are.
上げる give
与える give
I also have
あげる do a favour (not 'I' but 'they')
but I don't know what I meant by my english explanation. Does anybody recognise あげる as "doing a favour"?
A:
上げる is used generally and it is also polite.
If you want to say the same meaning in not polite way, you say やる(遣る).
与える is used only when the upper rank person gives something to the lower one/ones. For example, a king gives something to the vassal/retainer.
あげる used in (し)て+あげる is used in doing somebody a favor in doing something.
I'll show you some examples;
ごみを出すのを手伝ってあげる。I would help you take out the garbage.
苦労話を聞いてあげる。I would hear your hard-luck stories.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Help me convert this 2d array code from PHP to C#
Please help me re-write this code sample in PHP to C#:
$stringArray = array();
$stringArray['field1'] = 'value1';
$stringArray['field2'] = 'value2';
$stringArray['field3'] = 'value3';
foreach ($stringArray as $key => $value)
{
echo $key . ': ' . $value;
echo "\r\n";
}
A:
Named arrays do not exist in C#. An alternative is to use a Dictionary<string, string> to recreate a similar structure.
Dictionary<string, string> stringArray = new Dictionary<string, string>();
stringArray.Add("field1", "value1");
stringArray.Add("field2", "value2");
stringArray.Add("field3", "value3");
In order to iterate through them, you can use the following:
foreach( KeyValuePair<string, string> kvp in stringArray ) {
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pegar valor do AUTO_INCREMENT de uma tabela
Quero pegar o último registro cadastrado em uma tabela do banco de dados, ou seja, o valor do AUTO_INCREMENT da tabela, tentei usando:
SELECT MAX(id) as max FROM people
Ele funciona, porém se eu não tiver nenhum registro na tabela ele retornará NULL, o que pode ser errado, pois nem sempre que retornar NULL a tabela é nova, por exemplo:
Crio 5 registro na tabela, e logo após isso eu apago os 5, a minha
query vai retornar o NULL enquanto deveria retornar o 5 (que foi o último a ser registrado, independentemente se foi apagado ou não).
Li sobre o lastInsertId() do PDO, porém nos exemplos, sempre é preciso executar uma query de INSERT antes do lastInsertId().
Qual a melhor maneira de obter o valor atual do AUTO_INCREMENT de uma tabela a qualquer momento?
PS:. Quando digo 'a qualquer momento' quero dizer que não seja preciso inserir, atualizar ou deletar um registro antes de poder pegar.
A:
Faça uma consulta no information_schema ele guarda as informações sobre os seus banco de dados(metadados), o campo a ser retornado é o AUTO_INCREMENT, é necessário informar a tabela e database.
O código abaixa retorna o próximo valor do auto-increment, caso o último registro inserido tenha sido o de id 200, a consulta retornará 201.
SELECT AUTO_INCREMENT FROM information_schema.tables
WHERE table_name = 'tabela' AND table_schema = 'database' ;
Baseado em: How to get the next auto-increment id in mysql
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java Get MulticastSocket.receive to Throw ClosedByInterruptException
I have some code that reads data from a multicast socket until a user-defined end time. I would also like to stop reading data if the thread is interrupted via a call to Thread.interrupt (or by any other user-initiated action you can come up with). I can't figure out how to get notification when the thread is interrupted. The existing code is as follows:
// These are the constants I am given
final int mcastPort = ...;
final InetAddress mcastIP = ...;
final InetAddress ifaceIP = ...; // Null indicates all interfaces should be used
final Instant endTime = ...; // Time at which to stop processing
// Initialize a datagram
final byte[] buffer = new byte[1000];
final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Process incoming datagram packets
try (final MulticastSocket socket = new MulticastSocket(port)) {
socket.joinGroup(mcastIP);
if (ifaceIP != null)
socket.setInterface(ifaceIP);
do {
final Duration soTimeout = Duration.between(Instant.now(), endTime);
socket.setSoTimeout(soTimeout);
socket.receive(packet);
// Process packet
...
} while (true);
} catch (final SocketTimeoutException e) {
// Normal condition... the recording time has ended
} catch (final ClosedByInterruptException e) {
// Uh-oh... this never happens
} ...
I saw that there was a DatagramSocket.getChannel method that returns a DatagramChannel, so I naturally assumed that type was used to read/write to the underlying socket. That assumption was incorrect, which means that MulticastSocket doesn't implement InterruptibleChannel. Because of this, MulticastSocket.receive never throws a ClosedByInterruptException.
I have searched online for examples, but can't figure out how to modify the above code to use a DatagramChannel instead of a MulticastSocket. The problems I need help with are:
How do I set the SO_TIMEOUT parameter on a DatagramChannel?
How do I convert an InetAddress into a NetworkInterface object?
The following is my best guess on how to convert my implementation from MulticastSocket to DatagramChannel to meet my requirements:
// Initialize a buffer
final ByteBuffer buffer = ByteBuffer.allocate(1000);
try (final DatagramChannel mcastChannel = DatagramChannel.open()) {
mcastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
mcastChannel.connect(new InetSocketAddress(port));
mcastChannel.join(mcastIP);
if (ifaceIP != null)
// HELP: this option requires an InterfaceAddress object,
// but I only have access to an InetAddress object
mcastChannel.setOption(StandardSocketOptions.IP_MULTICAST_IF, ifaceIP);
do {
final Duration soTimeout = Duration.between(Instant.now(), endTime);
// HELP: SO_TIMEOUT is not a member of StandardSocketOptions
mcastChannel.setOption(SO_TIMEOUT, ???);
mcastChannel.receive(buffer);
// Process packet
...
} while (true);
} ...
Will this approach even work? DatagramChannel.receive doesn't list SocketTimeoutException as one of the exceptions it is able to throw. If this will work, then please let me know how I need to change the second implementation to be equivalent to the first, but with the ability to throw a ClosedByInterruptException when a client calls Thread.interrupt. If not, then does anyone have any other ideas as to how I can meet the requirement of stopping datagram reception at a pre-defined time, while also providing a way to stop execution via user interaction?
A:
How do I set the SO_TIMEOUT parameter on a DatagramChannel?
By calling channel.socket().setSoTimeout().
How do I convert an InetAddress into a NetworkInterface object?
You enumerate the network interfaces until you find one with the required address.
DatagramChannel.receive() doesn't list SocketTimeoutException
It doesn't have to. It lists IOException, and SocketTimeoutException extends IOException.
Your second piece of code should call bind(), not connect(), and it should set the intterface before calling join(), not after. Apart from that, it should work as expected once you fix the network interface issue, and it will throw ClosedByInterruptException if interrupted.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I filter a dataframe by a subset of a string?
I'm trying to apply a filter to a dataframe based on whether a certain string is a substring of the values in a column.
For example: Let's call the substring 'X' and I want to retrieve all rows where 'X' is a substring of the value in a column called 'A'.
It feels like the code should look something like this:
df["X" in df.A]
or this:
df.loc("X" in df.A)
or something along those lines. Does anyone have an idea on how I can achieve this?
A:
try this
res = df[df['A'].str.contains("X")]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need VB code commented to convert it to Java
I am a Java developer. I have the task of converting a VB class to Java.
Can some VB developer comment the following VB code so that I can write its Java equivalent?
Public Class RmaValidationCode
' Values for test type
Public Const SOFTWARE_TEST_TYPE = 0
Public Const FIRMWARE_TEST_TYPE = 1
' Values for test length
Public Const SHORT_TEST_LENGTH = 0
Public Const LONG_TEST_LENGTH = 1
' Values for test result
Public Const PASS_TEST_RESULT = 0
Public Const FAIL_TEST_RESULT = 1
Public Const ABORT_TEST_RESULT = 2
Public Const CAUTION_TEST_RESULT = 3
' GetRMAValidationCode function bit mapped return values
Public Const RMA_VC_RET_PASS = 0
Public Const RMA_VC_RET_NULL_PTR_PARAMETER = 1
Public Const RMA_VC_RET_INVALID_STR_LENGTH = 2
Public Const RMA_VC_RET_INVALID_SN_STRING = 4
Public Const RMA_VC_RET_INVALID_TEST_TYPE = 8
Public Const RMA_VC_RET_INVALID_TEST_LENGTH = 16
Public Const RMA_VC_RET_INVALID_TEST_RESULT = 32
Private Const RMA_LENGTH = 8
Private rmaValidationCode As String
' This function will return the warranty validation code based on serial number, test type,
' test result, test software and test length.
' Test type - Generic=0, DST=1
' Test result - Pass=0, FAIL=1
' Test Software - DOS=0, Windows=1
' Test Length - Short=0 Long=1
Public Function GetRMAValidationCode(ByVal serialNumber As String, ByVal testType As Byte, _
ByVal testResult As Byte, ByVal testSoftware As Byte, ByVal testLength As Byte)
Dim returnValue As UInt32
Dim tempRMACode As String
Dim tempRMAEnumerator As CharEnumerator
Dim temp8Bit As Byte
returnValue = RMA_VC_RET_PASS
temp8Bit = 0
' Make sure we were passed valid strings
If String.IsNullOrEmpty(serialNumber) OrElse _
String.IsNullOrEmpty(rmaValidationCode) Then
returnValue = returnValue Or RMA_VC_RET_NULL_PTR_PARAMETER
End If
' Make sure our strings are big enough
If serialNumber.Length < RMA_LENGTH OrElse _
rmaValidationCode.Length < RMA_LENGTH Then
returnValue = returnValue Or RMA_VC_RET_INVALID_STR_LENGTH
End If
' Assure that valid test types were passed in
If testType <> SOFTWARE_TEST_TYPE AndAlso _
testType <> FIRMWARE_TEST_TYPE Then
returnValue = returnValue Or RMA_VC_RET_INVALID_TEST_TYPE
End If
' Assure that valid test lengths were passed in
If testLength <> SHORT_TEST_LENGTH AndAlso _
testLength <> LONG_TEST_LENGTH Then
returnValue = returnValue Or RMA_VC_RET_INVALID_TEST_LENGTH
End If
' Assure that valid test results were passed in
If testResult <> PASS_TEST_RESULT AndAlso _
testResult <> FAIL_TEST_RESULT AndAlso _
testResult <> ABORT_TEST_RESULT AndAlso _
testResult <> CAUTION_TEST_RESULT Then
returnValue = returnValue Or RMA_VC_RET_INVALID_TEST_RESULT
End If
If returnValue = RMA_VC_RET_PASS Then
' Trim leading and trailing whitespace
serialNumber.Trim()
' Check to see if the serialNumber string is long enough
' after whitespace is removed
If serialNumber.Length < RMA_LENGTH Then
Return RMA_VC_RET_INVALID_SN_STRING
End If
tempRMACode = serialNumber.ToLower()
tempRMAEnumerator = tempRMACode.GetEnumerator()
While (tempRMAEnumerator.MoveNext())
If Not Char.IsLetterOrDigit(tempRMAEnumerator.Current) Then
Return RMA_VC_RET_INVALID_SN_STRING
End If
End While
' Initialize the rmaValidationCode
rmaValidationCode = ""
' Compute and save the first 6 bytes of RMA Validation Code
temp8Bit = 0
temp8Bit = Convert.ToByte(tempRMACode.ToCharArray().GetValue(0)) + Convert.ToByte((tempRMACode.ToCharArray()).GetValue(7))
rmaValidationCode += String.Format("{0:X2}", temp8Bit)
temp8Bit = 0
temp8Bit = Convert.ToByte((tempRMACode.ToCharArray()).GetValue(1)) + Convert.ToByte((tempRMACode.ToCharArray()).GetValue(6))
rmaValidationCode += String.Format("{0:X2}", temp8Bit)
temp8Bit = 0
temp8Bit = Convert.ToByte((tempRMACode.ToCharArray()).GetValue(2)) + Convert.ToByte((tempRMACode.ToCharArray()).GetValue(5))
rmaValidationCode += String.Format("{0:X2}", temp8Bit)
' Byte 6 is the Test & Result byte.
temp8Bit = 0
temp8Bit = (testSoftware << 3) Or (testResult << 2) Or (testType << 1) Or testLength
rmaValidationCode += String.Format("{0:X1}", temp8Bit)
' Compute the parity byte
temp8Bit = 0
Dim mychar As Char
mychar = rmaValidationCode.ToCharArray().GetValue(3)
If ((Convert.ToInt32(rmaValidationCode.ToCharArray().GetValue(3), 16) Mod 2) = 1) Then
temp8Bit = temp8Bit Or (1 << 3)
Else
temp8Bit = temp8Bit Or (0 << 3)
End If
Dim value As Integer
mychar = rmaValidationCode.ToCharArray().GetValue(2)
value = System.Convert.ToInt32(mychar, 16)
If ((Convert.ToInt32(rmaValidationCode.ToCharArray().GetValue(2), 16) Mod 2) = 1) Then
temp8Bit = temp8Bit Or (1 << 2)
Else
temp8Bit = temp8Bit Or (0 << 2)
End If
mychar = rmaValidationCode.ToCharArray().GetValue(1)
If ((Convert.ToInt32(rmaValidationCode.ToCharArray().GetValue(1), 16) Mod 2) = 1) Then
temp8Bit = temp8Bit Or (1 << 1)
Else
temp8Bit = temp8Bit Or (0 << 1)
End If
mychar = rmaValidationCode.ToCharArray().GetValue(0)
If ((Convert.ToInt32(rmaValidationCode.ToCharArray().GetValue(0), 16) Mod 2) = 1) Then
temp8Bit = temp8Bit Or 1
Else
temp8Bit = temp8Bit Or 0
End If
rmaValidationCode += String.Format("{0:X1}", temp8Bit)
End If
Return rmaValidationCode
End Function
Public Sub New()
' serialNumber = " "
rmaValidationCode = " "
' testType = 0
'testLength = 0
'testResult = 0
End Sub
End Class
A:
Actually that is pretty readable and straightforward code. You may want to take a look at VB keywords as well as the AndAlso/OrElse operators (those two sometimes confuse C-style language developers). The rest that's used are just plain old .NET class library methods. Nothing too fancy and you'll find plenty of documentation about those on MSDN.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In Magento 2 what is the factory pattern and used for?
In Magento 2 what is the factory pattern and used for ? I'm new in magento so can you please explain me in detail.
A:
Factory definition:
Factories are service classes that instantiate non-injectable classes, that is, models that represent a database entity. They create a layer of abstraction between the ObjectManager and business code.
Definition of repository:
A repository object is responsible for reading and writing your object information to an object store
Use Repositories for full loading
$model->load() is not part of the service contract. I had a question on that particular topic, you might find the answers useful: Is there ever a reason to prefer $model->load() over service contracts?
Use Factories to create new entities
Repositories do not come with methods to create a new entity, so in that case you will need a factory. But use the factory for the interface, such as Magento\Catalog\Api\Data\ProductInterfaceFactory - it will create the right implementation based on DI configuration.
Then use the repository->save() method to save it.
https://magento.stackexchange.com/questions/158081/when-should-we-use-a-repository-and-factory-in-magento-2
More here in the dev docs http://devdocs.magento.com/guides/v2.0/extension-dev-guide/factories.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does anyone know why python dateutil parser is telling me it contains invalid syntax? It worked last night, will not work anymore
from dateutil import parser as _date_parser
File "C:\Program Files (x86)\Python36-32\lib\site-packages\dateutil\parser.py", line 158
l.append("%s=%s" % (attr, `value`))
^
SyntaxError: invalid syntax
My code was no different last night when I ran it. Had no problems then, but now I'm getting this SyntaxError from the dateutil parser. Here's the code from the parser itself:
def _repr(self, classname):
l = []
for attr in self.__slots__:
value = getattr(self, attr)
if value is not None:
l.append("%s=%s" % (attr, `value`))
return "%s(%s)" % (classname, ", ".join(l))
A:
Last night you used Python 2. Today you used Python 3.
In Python 2 backticks were used as a shortcut to repr. In Python 3 this alias is not used anymore and using it raises a syntax error.
Change
l.append("%s=%s" % (attr, `value`))
to either l.append("%s=%s" % (attr, value)) or l.append("%s=%s" % (attr, repr(value)))
EDIT I just noticed that this code is in dateutil itself. It seems like you somehow managed to install the Python 2 version to the Python 3 path.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redis Docker - Unable to connect from C# client
I am new to docker and redis, I have redis 3.0 running on docker using the following command:
docker run --name redisDev -d redis
It seems to start up just fine with port 6379 connected:
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b95c9402dd42 redis:3 "/entrypoint.sh redi 47 minutes ago Up 47 minutes 6379/tcp redisDev
I'm trying to connect with the following code:
var sb = new StringBuilder();
var tw = new StringWriter(sb);
ConnectionMultiplexer redis;
try
{
redis = ConnectionMultiplexer.Connect("vb-haproxy01.verify.local", tw);
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
tw.Flush();
Console.WriteLine(sb.ToString());
return;
}
I get the following error:
vb-haproxy01.verify.local:6379
1 unique nodes specified
Requesting tie-break from vb-haproxy01.verify.local:6379 > __Booksleeve_TieBreak
...
Allowing endpoints 00:00:05 to respond...
vb-haproxy01.verify.local:6379 faulted: SocketFailure on PING
vb-haproxy01.verify.local:6379 failed to nominate (Faulted)
> UnableToResolvePhysicalConnection on GET
No masters detected
vb-haproxy01.verify.local:6379: Standalone v2.0.0, master; keep-alive: 00:01:00;
int: Connecting; sub: Disconnected; not in use: DidNotRespond
vb-haproxy01.verify.local:6379: int ops=0, qu=0, qs=0, qc=1, wr=0, sync=1, socks
=2; sub ops=0, qu=0, qs=0, qc=0, wr=0, socks=2
Circular op-count snapshot; int: 0 (0.00 ops/s; spans 10s); sub: 0 (0.00 ops/s;
spans 10s)
Sync timeouts: 0; fire and forget: 0; last heartbeat: -1s ago
resetting failing connections to retry...
retrying; attempts left: 2...
1 unique nodes specified
Linux firewall settings:
sudo iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT tcp -- anywhere anywhere tcp dpt:6379
Chain FORWARD (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED
ACCEPT all -- anywhere anywhere
ACCEPT all -- anywhere anywhere
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
What am I missing?
A:
The problem is that port 6379 on the host was not forwarding port 6379 to the docker. The "-p 6379:6379" of following command fixed the problem:
docker run -d --name redisDev -p 6379:6379 redis
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java SHA-256 Program provides wrong Hash
I was solving challenges on Hackerrank.com and I met with this challenge about the java SHA-256 Cryptographic hash functions. here
I wrote the following piece of code as a solution. But some test cases are failing for my solution. Hoping to know what's wrong with my code.
public class Solution {
public static String toHexString(byte[] hash)
{
BigInteger number = new BigInteger(1, hash);
StringBuilder hexString = new StringBuilder(number.toString(16));
while (hexString.length() < 32)
{
hexString.insert(0, '0');
}
return hexString.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
try
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
System.out.println(toHexString(md.digest(input.getBytes(StandardCharsets.UTF_8))));
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
This is one test case that is failing.
A:
A 32-byte hash means a string of 64 characters. Each byte contains 2 hex digits, so you need 2 characters per byte:
while (hexString.length() < 64)
{
hexString.insert(0, '0');
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there way to write GAE JUnit for Google OAuth2 test
I search around the Google and not that I know of... I don't even see any Dev libraries availble for this as well. Any comment please?
A:
You cannot test the Google OAuth process in your unit tests because it is requiring a third party application (Google) to do it.
So it is not possible.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Quick way to update RSpec 2.9 to 3.3 with sublime text 2
I'm curious if anyone knows a quick way to update the syntax. That is
be_true to be_truthy
mock to double
stub to double
For reasons that would take to long to explain here I can't use the transpec gem. Already tried and it didn't work. I found a bit of hack here
-> expected true to respond to true?
on that worked for most of my tests but I need my tests to reflect the actual changes.
Is command + shift + F search my only option here? I imagine I'm not the only one here who has done something similar. Thanks.
A:
I would suggest doing it in the shell using perl/ruby/etc. Just be sure to run all your tests after each change, commit, and continue in case you mess up the regex. For example, the below should replace your first case. The second two would need some testing to ensure you didn't over do it.
cd spec
perl -i -p -e 's/be_true/be_truthy/g' `git grep -l be_true`
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I draw a circular arc with three points in a StreamGeometry
I'm using a StreamGeometry object to create an complete figure. The figure is a series of lines and arcs. The arcs are all circular defined by a start point, end point, and a middle point that the arc also passes through. How can I convert that into what ArcTo requires. I've been searching for a solution all morning. I will try to work the math out myself.
A:
1) Find radius of circle with plain geometry
Let's A, B, C - three points given (B is middle point of arc), M is middle point of AC chord, then
AM * CM = BM * B'M, where B' is point at another end of circle diameter, due to "intersecting chords theorem".
AM=CM=AC/2, BM+B'M = 2R, so we can find circle radius R
(2R-BM) * BM = AM^2
2R-BM = AM^2/BM
R = (BM^2+AM^2)/(2*BM)
2) Now it is possible to find circle center with vector geometry
O = B + uBM * R, where uBM = BM/|BM| is unit vector
3) size parameter of ArcTo set to (R, R)
4) rotationAngle set to atan2(OA x OC, OA * OC) (crossproduct and scalar product of OA and OC vectors)
5) set the rest of ArcTo parameters as needed
|
{
"pile_set_name": "StackExchange"
}
|
Q:
usb debugging not connected to pc
I have android device its samsung galaxy GT-S5300 and version is 2.3.6. I want to connect my device with computer for running the apps directly to device via eclipse.
I have installed the samsung kies on my system and i did the following setting on my phone but I could not get connected with pc for debugging mode(Developing). But the sd card is mounted to pc.
1)Setting -> Application -> UnKnown sources ->enabled the option.
2)Setting -> Application -> Development-> USB debugging ->enabled the option. But still not connected my device with pc for debugging mode.
How to get connected the device with pc for USB debugging mode?
A:
Hey murali_ma,
Do this...
1. Open command prompt and type adb kill-server
2. then again type adb start-server
3. then adb install path of apk
i am sure you will get the success.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CakePHP cannot modify header?
I am using CakePHP 1.3 and it keeps telling me the following.
Cannot modify header information
This ONLY happens when I include the Auth component.
var $components = array('Auth');
Am I doing something wrong, a bug, or what?
A:
Headers have to be the first part of a web page that you send. Make sure that you haven't outputted any other information before you try sending any kind of header.
This may also be useful
|
{
"pile_set_name": "StackExchange"
}
|
Q:
content().find() not working on dynamically inserted url to an iframe
I have to double click on submit to get code working after I insert dynamic url to an iframe. It looks like it sets the url in the first click and executes the code on the second.
Code works fine if url is pre inserted there.
Below is the code:
$('#search').on('click', 'button', function(){
var url = $('#url').val();
$('#url1').attr('src', url);
var pageLinks = $('#url1').contents().find('#para a');
alert(pageLinks[1]);
});
HTML
<div id="search">
<input type="text" id="url" placeholder="Enter URL" value="" />
<button type="button" id="start">START</button>
</div>
<iframe id="url1" style="width:49%;" src="" height="200" width="300"></iframe>
url page in iframe has tags like:
<p id="para"><a class="alink" href="page-1.php" target="_blank">Link</a></p>
This code works but on double click, while I am not able to figure out to do it in a single click.
A:
After few hours of research I've found the solution.
After dynamically placing url in iframe, it needed to be reloaded.
$('#search').on('click', 'button', function(){
var url = $('#url').val();
$('#url1').attr('src', url);
$('#url1').on('load', function () {
var pageLinks = $('#url1').contents().find('#para a');
alert(pageLinks[1]);
});
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Better keyboard input for XNA games
Default XNA input doesn't provide an event handler that may call some method during frame processing (between update calls, immediately when a key is pressed).
I tried using Nuclex.Input, but it has some flaws — keys like F10, Alt and Pause do not fire up assigned events. Some of those keys appear in GetKeyboard().GetState().GetPressedKeys() list, but some of them don't, which is unacceptable for making shortcuts.
I would be happy if there was a way to make the XNA's default input manager to work with events, but I haven't seen anyone say it's possible. So I'm probably looking for some other input manager that can give me any key press there can be with press/release event handler.
Or maybe there is some way to avoid using third-party library by using windows hooks like firing up handler event for any key press/release?
Or this whole XNA input way is whacked up and higher class game engines use a totally different approach?
I see everybody's been using XInput for the last few years.
A:
For now I have resorted to using Nuclex.Input for my XNA game, but I'm still looking for better alternatives.
Some problems with Nuclex.Input are that it doesn't differentiate between left and right Shift or Ctrl buttons and doesn't detect some keys (including F10, left Alt, PrintScreen and Pause).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Anaconda and ArcGIS 10.1
I am having problems installing Anaconda with ArcGIS 10.1. My problem is specifically with pandas. ArcGIS python is my default python version. I installed python 0.16.2 in this version, which installed numpy 1.9.2. Following some posts, I created a .pth file (with ZZ as preffix, in order to read first the default version modules) and put it in C:\Python27\ArcGIS10.1\Lib\site-packages, which points to the Anaconda packages (C:\Anaconda2\Lib\site-packages). I can import most of the Anaconda python modules, but I have a problem with pandas. When I import pandas, I get the following error:
RuntimeError: module compiled against API version a but this version of numpy is 9
This only happens in a Windows command window, in ArcGIS python window imports the 0.16.2 version. The Anaconda pandas and numpy versions are 0.17.1 and 1.10.1. When I import the numpy version in a command window I get 1.9.2 (ArcGIS installed numpy version). The only problem is the error above with pandas, but after the error I check the version and says 1.9.2. I have read about creating environments in Anaconda, but I need the pandas 0.16.2 version because of some new funcionalities not present in older versions. I tried uninstalling the ArcGIS pandas version to use the Anaconda version, but I got the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda2\Lib\site-packages\pandas\__init__.py", line 7, in <module>
from pandas import hashtable, tslib, lib
File "pandas\src\numpy.pxd", line 157, in init pandas.hashtable (pandas\hashtable.c:38262)
ValueError: numpy.dtype has the wrong size, try recompiling
Does anyone how can I solve this problem?
A:
I solved the problem installing numpy 1.10. It seems the Anaconda pandas version was compiled with numpy 1.10, and the numpy default python version was 1.9.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does the SSS represent in the org.apache.log4j.helpers.ISO8601DateFormat?
The JavaDoc says:
Formats a Date in the format "yyyy-MM-dd HH:mm:ss,SSS" for example
"1999-11-27 15:49:37,459".
Are they milliseconds from 000-999? The summary of the international standard date and time notation makes no mention of milliseconds.
A:
It formats Date. In Date formatting "SSS" pattern means milliseconds from 000 to 999, so you are correct.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to bind in PDO a string with %
I have the following query, (which don't work).
How do I bid strings inside an existing string with % (I believe the % is not the problem, but really not sure).
$sql="SELECT * FROM T WHERE f LIKE '%:bindParamString%'";
A:
You can include % symbols into your value:
$param = '%'.$param.'%';
$query = "SELECT * FROM T WHERE f LIKE ?";
Or use SQL to concatenate string in database:
## if you have mysql
$query = "SELECT * FROM T WHERE f LIKE CONCAT('%', ?, '%')";
It also a good idea to use LIKE instead of = then you're searching by patterns.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Vary voltage using relay. Is this possible?
I am planning to control a RGB lamp using Arduino. The lamp is 24V and I want to be able to control the brightness of the lamp. I found a relay that will let me control the 3 channels (red green and blue), but will only let me turn it on and off (Not control brightness)
I am looking for a way to control the lamp both on/off and brightness. What component will do the same as my relay, but also let me use the varying voltage from the arduino to control my 24V lamp? (Just like a transistor)
I have an external 24V powersupply along with 5V for the arduino
Thanks!
A:
No, you can't vary the voltage with a relay. The only way you could do it with a relay would be to have a selection of different voltages available, and then use multiple relays to select which voltage is used. Less than ideal.
You need to use PWM to create a square wave with varying duty cycle. The duty cycle (the percentage of time the power is on within a given period) defines the average voltage of the output. That PWM needs to be fed into a MOSFET which will in turn control the 24V power to the lamp.
It's exactly the same as driving RGB LED strips, except it's in the shape of a lamp not a long strip.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Connecting through plink and redirecting to file, not getting all the needed output in file
I'm using a batch file in Windows to connect to a Linux computer through SSH with plink to see if two certain files are up to date (they have to have today's date).
The command I use in the Windows batch file to execute plink:
plink.exe -ssh root@%THEIP% -m checkfiles.txt > temp\fileDates.txt
The "checkfiles.txt" in the Windows computer contains:
ls -l /folder/*file.dat.v* /folder/*file2.dat.v* > awk '{print $7}'
I then proceed to read "fileDates.txt" to see if both files are present and their dates.
I could delete the > awk '{print $7}' part and do it by hand on the batch file.
The problem comes when a file is missing, I get for example:
ls: cannot access /folder/*file.dat.v*: No such file or directory
I get that massage on screen and not in "fileDates.txt", and I only get the date for the second file, with no error about the first file not being found.
I'd like to have the error "No such file..." in "fileDates.txt" so I've been trying different redirection methods to no avail.
If that isn't possible, how can I tell when one file, the other or both are missing?
Thank you in advance.
A:
I found the answer. Thanks @PlasmaPower for your help (I'd upvote your answer, but I don't have enough reputation).
What was needed was two lines of code:
ls -l /folder/*file.dat.v* /folder/*file2.dat.v* &> $HOME/checkfiles.txt
cat $HOME/checkfiles.txt | awk '{print $7}'
The first one to do a temporary file with both stdout and stderr, then another line doing the awk command.
Thank you very much!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
pyspark dataframe left join and add a new column with constant vlue
I would like to join two pyspark dataframe with conditions and also add a new column.
df1 = spark.createDataFrame(
[(2010, 1, 'rdc', 'bdvs'), (2010, 1, 'rdc','yybp'),
(2007, 6, 'utw', 'itcs'), (2007, 6, 'utw','tbsw')
],
("year", "month", "u_id", "p_id"))
df2 = spark.createDataFrame(
[(2010, 1, 'rdc', 'bdvs'),
(2007, 6, 'utw', 'itcs')
],
("year", "month", "u_id", "p_id"))
df1
year month u_id p_id
2010 1 rdc bdvs
2010 1 rdc yybp
2007 6 utw ircs
2007 6 utw tbsw
df2
year month u_id p_id
2010 1 rdc bdvs
2007 6 utw ircs
new df that I need:
year month u_id p_id is_true
2010 1 rdc bdvs 1
2010 1 rdc yybp 0
2007 6 utw ircs 1
2007 6 utw tbsw 0
My python3 code:
import pyspark.sql.functions as F
t =df1.join(df2, (df1.year==df2.year) & (df1.month==df2.month) & (df1.u_id==df2.u_id), how='left').withColumn('is_true', F.when(df1.p_id==df2.p_id, F.lit(1)).otherWise(F.lit(0)))
I got error:
TypeError: 'Column' object is not callable
I tried some solutions but none of them work.
Do I miss something ? I try to add a constant as a new column value based on some conditions.
thanks
A:
change otherWise to otherwise.
Example:
t =df1.alias("df1").join(df2.alias("df2"), (df1.year==df2.year) & (df1.month==df2.month) & (df1.u_id==df2.u_id), how='left').\
withColumn('is_true', F.when(df1.p_id == df2.p_id, F.lit(1)).otherwise(F.lit(0))).select("df1.*","is_true")
t.show()
#+----+-----+----+----+-------+
#|year|month|u_id|p_id|is_true|
#+----+-----+----+----+-------+
#|2007| 6| utw|itcs| 1|
#|2007| 6| utw|tbsw| 0|
#|2010| 1| rdc|bdvs| 1|
#|2010| 1| rdc|yybp| 0|
#+----+-----+----+----+-------+
Another way without using when statement would be using left_semi,left_anti.
from pyspark.sql.functions import *
columns=df1.columns
df1.\
join(df2,columns,'left_anti').\
withColumn("is_true",lit(1)).\
unionAll(df1.\
join(df2,columns,'left_semi').\
withColumn("is_true",lit(0))).\
show()
#+----+-----+----+----+-------+
#|year|month|u_id|p_id|is_true|
#+----+-----+----+----+-------+
#|2010| 1| rdc|yybp| 1|
#|2007| 6| utw|tbsw| 1|
#|2007| 6| utw|itcs| 0|
#|2010| 1| rdc|bdvs| 0|
#+----+-----+----+----+-------+
|
{
"pile_set_name": "StackExchange"
}
|
Q:
DEAP algorithm with several weights
I'm pretty new to DEAP and looking at several places and examples I've seen it creates classes for genetic algoritms using this method:
creator.create('FitnessMax', base.Fitness, weights=(1.0, -0.5,))
creator.create('Individual', list, fitness=creator.FitnessMax)
What I don't understand is the weights parameter. It is supposed that DEAP can be used to solve multiobjectives problems (maximize and minimize), that's why weights can be positive or negative.
But how is it linked to the fitness/objective function? Must the fitness function return several values, one for each weight?
A:
For multi-objective problems, your fitness function must return a tuple with the same number of results as the specified number of weights, e.g.:
creator.create('Fitness', base.Fitness, weights=(1.0, -0.5,))
creator.create('Individual', list, fitness=creator.Fitness)
[...]
toolbox.register('evaluate', fitness)
def function_minimize(individual):
return individual[0] - sum(individual[1:])
def function_maximize(individual):
return sum(individual)
def fitness(individual):
return (function_maximize(individual), function_minimize(individual)),
Also, keep in mind that your selection method must support multi-objective problems, tournament selection for instance, doesn't, so if you use it, weights will be ignored). A selection method that supports this kind of problem is NSGA2:
toolbox.register('select', tools.selNSGA2)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I project the result of my query to the model generated by EF?
I have a method something like below :
public IEnumerable<CountryEF> GetAllCountry( )
{
using (Context context = new Context() )
{
List<CountryEF> countries = context.COUNTRY.Select(c =>
new CountryEF()
{
ID = c.ID,
Description = c.DESCRIPTION,
CURRENCYEF = c.CURRENCYEF
}
).ToList<CountryEF>();
return countries;
}
}
Where COUNTRYEF is a Model Class Generated by Entity Framework which looks like this :
public partial class COUNTRYEF
{
public COUNTRYEF()
{
}
public string ID { get; set; }
public string DESCRIPTION { get; set; }
public virtual CURRENCY CURRENCYEF { get; set; }
}
When ever I do this I get Exception. So as a fallback I have to create another class which is just a copy-paste of above class like this below :
public class COUNTRYVM //view model class
{
public COUNTRYVM()
{
}
public string ID { get; set; }
public string DESCRIPTION { get; set; }
public virtual CURRENCY CURRENCYEF { get; set; }
}
And then my query becomes like this :
public IEnumerable<CountryVM> GetAllCountry( )
{
using (Context context = new Context() )
{
List<CountryVM> countries = context.COUNTRY.Select(c =>
new CountryVM()
{
ID = c.ID,
Description = c.DESCRIPTION,
CURRENCYEF = c.CURRENCYEF
}
).ToList<CountryVM>();
return countries;
}
}
And the above solution works fine and good. But Do I really want to replicate the Model classes generated by Entity Framework like public partial class COUNTRYEF to something like public class COUNTRYVM. I really don't want to do code duplication.
What are the possible solutions for this ?
Anonymous properties also dont. I had tried the below solution :
public IEnumerable GetAllCountry( )
{
using (Context context = new Context() )
{
var countries = context.COUNTRY.Select(c =>
new //Anonymous Projection
{
ID = c.ID,
Description = c.DESCRIPTION,
CURRENCYEF = c.CURRENCYEF
}
).ToList();
return countries;
}
}
But then I cannot access the ID , Description and CurrencyEF in my Views and Controllers!!
A:
Entity Framework doesn't allow creating classes of the Entity inside it's projection. Something to do with hard for it to track which entities it should be tracking. The work around I use. Instead of copy and pasting the class just subclass it.
public partial class CountryEFSub : CountryEF
{
}
public IEnumerable<CountryEF> GetAllCountry( )
{
using (Context context = new Context() )
{
return context.COUNTRY.AsNoTracking().Select(c =>
new CountryEFSub()
{
ID = c.ID,
Description = c.DESCRIPTION,
CURRENCYEF = c.CURRENCYEF
}
).AsEnumerable();
}
}
This tricked worked in EF 5. I haven't used it with any version else. Also noticed you can leave the method type still as CountryEF.
You could create a T4 to create all the subclasses for you. Also if you need help with the projections I believe AutoMapper now supports IQueryable. Otherwise you can write the projections by hand or with expresison trees.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Function Factory in R
I try to come up with a function factory by returning a dictionary of specialized functions, more or less like functional programming style. I try to do this in the following code.
require(hash)
names = c("aa","bb","cc");
funs = hash()
for (i in seq(length(names))) {
n = names[i]
funs[[n]] = function(x) {
print(paste(n,":",x, sep=""))
}
}
Obviously, I have 3 functions in the array; however, they all behave the same as the last function in the iteration.
> funs[["aa"]](1)
[1] "cc:1"
> funs[["bb"]](2)
[1] "cc:2"
> funs[["cc"]](3)
[1] "cc:3"
My guess is that R didn't create new function instance but reuses the same function object inside the for-loop.
I try the following in hope that R will create different function object,
funs[[n]] = eval(parse(text="function(x) { print(paste(n,':',x, sep='')) }"))
but it works the same as the first one.
Do you have an idea how to create a generator that creates different function objects?
A:
According to Hadley's Advanced R Programmin, Lexical scoping, the variable n in the body of functions funs[['aa']], funs[['bb']], and funs[['cc']] are the variable n in <environment: R_GlobalEnv>.
For example:
> funs[["aa"]](1)
[1] "cc:1"
> n <- "1234"
> funs[["aa"]]("1")
[1] "1234:1"
To do what you want, I'll write a function which returns a function:
funs.gen <- function(n) {
force(n)
function(x) {
print(paste(n, ":", x, sep=""))
}
}
names = c("aa","bb","cc");
funs = hash()
for (i in seq(length(names))) {
n = names[i]
funs[[n]] = funs.gen(n)
}
funs[["aa"]](1)
funs[["bb"]](2)
funs[["cc"]](3)
Note that force is used to ask R not lazy evaluate expression n. If you remove it, then R will evaluate n out of the for loop which will produce the same result as your question.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
R - plotting thumbnails (that are in a list) on a scatterplot
I'd like to plot a set of thumbnail images as points on a scatterplot. I've started with the answer code located here but they repeat the same thumbnail throughout the plot, whereas I have a list of images.
xy <- data.frame(x=runif(337, 0, 100), y=runif(337, 0, 100))
imgfiles <- list.files(getwd(),pattern="*-scaled.png")
img <- lapply( imgfiles,function(x) readPNG(x) )
thumbnails <- function(x, y, images, width = 0.1*diff(range(x)),
height = 0.1*diff(range(y))){
images <- replicate(length(x), images, simplify=FALSE)
stopifnot(length(x) == length(y))
for (ii in seq_along(x)){
rasterImage(images[[ii]], xleft=x[ii] - 0.5*width,
ybottom= y[ii] - 0.5*height,
xright=x[ii] + 0.5*width,
ytop= y[ii] + 0.5*height, interpolate=FALSE)
}
}
plot(xy, t="n")
thumbnails(xy[,1], xy[,2], img[[11]]) # this works but the same image is repeated
I've tried wrapping thumbnail() into a loop but the plot comes out empty
for (n in length(img)){
thumbnails(xy[n,1], xy[n,2], img[[n]])
}
How do I do this? I'm not understanding how to reference the images within the list, or whether i should change them to a different data structure.
A:
I just had to get rid of this line in thumbnails()
images <- replicate(length(x), images, simplify=FALSE)
It was replicating the sample image given in the original answer. There's no need for a loop after.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# .Net3.5 adding data to a SQL Server 2005 database if it dosn't already exist and if it does update it?
Hi now playing with SQL for the first time!
I have the code below which works fine but I need to check if the entry is already in the database using CustomerName and Product to match on and if it is in the database update the other fields and if not insert all the data.
How would I do this?
Below is the code I use to insert a new record:
DateTime FirstDateSeen = new DateTime();
FirstDateSeen = DateTime.Now.Date;
DateTime LastDateSeen = new DateTime();
LastDateSeen = DateTime.Now.Date;
SqlConnectionStringBuilder MySqlConnection = new SqlConnectionStringBuilder("MY CONNECTION");
SqlConnection db = new SqlConnection(MySqlConnection.ToString());
try //sql string for first seen
{
string sqlIns = "INSERT INTO Customer (Product, Version, CustomerName, CustomerPostcode, FirstSeen, LastSeen)" +
"VALUES (@Product, @Version, @CustomerName, @CustomerPostcode, @FirstSeen, @LastSeen)";
db.Open();
SqlCommand cmdIns = new SqlCommand(sqlIns, db);
cmdIns.Parameters.Add("@CustomerName", UniqueA);
cmdIns.Parameters.Add("@Product", AppName);
cmdIns.Parameters.Add("@Version", AppVer);
cmdIns.Parameters.Add("@CustomerPostcode", UniqueB);
cmdIns.Parameters.Add("@FirstSeen", FirstDateSeen.ToShortDateString());
cmdIns.Parameters.Add("@LastSeen", LastDateSeen.ToShortDateString());
cmdIns.ExecuteNonQuery();
cmdIns.Parameters.Clear();
cmdIns.Dispose();
cmdIns = null;
}
catch (Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
finally
{
db.Close();
}
A:
IF EXISTS(SELECT CustomerName FROM Customer WHERE CustomerName = @CustomerName)
BEGIN
UPDATE Customer ..
END
ELSE
BEGIN
INSERT INTO Customer (Product, Version, CustomerName, CustomerPostcode, FirstSeen, LastSeen)
VALUES (@Product, @Version, @CustomerName, @CustomerPostcode, @FirstSeen, @LastSeen)
END
Lots of other fun stuff going on here...
Here is one pointer
catch (Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
is better as
catch (Exception ex)
{
// do stuff
throw;
}
or
catch ()
{
throw;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cross-browser client-side redirection in a new tab or window
we need a kind of client-side redirection and the only options we have are:
window.location
window.open
HTTP 301, 302, 303 responses
window.location doesn't support opening the target location in a new tab or window. (I think this is related to browsing context)
window.open doesn't work in Chrome and seems to be dependent upon some client-side configurations made to the browser, which makes it a less favorable option, since we don't have control on it.
HTTP redirect response doesn't open a new tab or window, just like window.location.
Any idea?
A:
After playing around with this for hours last night, I had a flash of inspiration this morning, and I have just tested this solution in FF3, Chrome, IE7 and IE8 - it's a bit hacky but it works in all.
<html>
<head>
<title>Redirect in a new window</title>
<script type="text/javascript">
function doIt () {
var form = document.createElement('form');
form.action = 'http://www.google.com/';
form.target = '_blank';
document.getElementById('hidden_div').appendChild(form);
form.submit();
}
</script>
<style>
#hidden_div {
display: none;
}
</style>
</head>
<body>
<div>
This is my page content<br />
<a href="http://www.google.com/">This is a link to Google</a>...<br />
...and this button will open Google in a new tab or window: <input type="button" value="Click Me!" onclick="doIt();" />
</div>
<div id="hidden_div"></div>
</body>
</html>
How It Works
You need a hidden <div> on your page somewhere that you can get a reference to in JS (no big deal - just create one with display: none).
When you want to do the redirect, use document.createElement() to create a new <form> element, assign it's action attribute with the address of the page where you want to take the user, and give it a target attribute as appropriate (I have used _blank in my example above). Then simply append it to your hidden <div> and call it's submit() method.
Hey presto, your redirect opens in a new window/tab!
Unfortunately you are still at the mercy of how the user configures their browser to handle target="_blank" but it will be either a new window or a new tab, and it should work everywhere...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Problem in Datepicker and alertsheet
I am implementing UIDATEPICKER. The problem is that when i click on the button, The alert sheet is appear and datepicker is add as subview but i want two button,
1-cancel 2-done
what will i do?
UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"How many?"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
aac.actionSheetStyle = UIActionSheetStyleBlackOpaque;
sheet = aac;
UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
if(IsDateSelected==YES)
{
theDatePicker.datePickerMode = UIDatePickerModeDate;
theDatePicker.maximumDate=[NSDate date];
}else {
theDatePicker.datePickerMode = UIDatePickerModeTime;
}
self.dtpicker = theDatePicker;
[theDatePicker release];
[dtpicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerDateToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(DatePickerCancelClick)];
[barItems addObject:cancelBtn];
////
it doesnot work ..I want this....
what will i do?
A:
-(IBAction)DatePickerView
{
iRolegameAppDelegate *appDelegate = (iRolegameAppDelegate *)[[UIApplication sharedApplication]delegate];
pickerViewDate = [[UIActionSheet alloc] initWithTitle:@"How many?"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
theDatePicker.datePickerMode = UIDatePickerModeDateAndTime;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]autorelease]];
[dateFormatter setDateFormat:@"MM/dd/YY h:mm a"];
[theDatePicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerToolbar.barStyle=UIBarStyleBlackOpaque;
[pickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
[barItems addObject:flexSpace];
UIBarButtonItem *spacer = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
[barItems addObject:spacer];
UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(DatePickerCancelClick)];
[barItems addObject:cancelBtn];
[pickerToolbar setItems:barItems animated:YES];
[pickerViewDate addSubview:pickerToolbar];
[pickerViewDate addSubview:theDatePicker];
[pickerViewDate showInView:self.view];
[pickerViewDate setBounds:CGRectMake(0,0,320, 464)];
NSDateFormatter *currentdateformate = [[NSDateFormatter alloc] init];
[currentdateformate setDateFormat:@"HH:MM, EEEE, dd-MMMM-yyyy"];
appDelegate.timestamp1 = [currentdateformate stringFromDate:[theDatePicker date]];
NSDateFormatter *currentdateformate1 = [[NSDateFormatter alloc] init];
[currentdateformate1 setDateFormat:@"MMM dd, yyyy HH:mm"];
self.updatedate = [currentdateformate1 stringFromDate:[theDatePicker date]];
}
-(IBAction)dateChanged{
iRolegameAppDelegate *appDelegate = (iRolegameAppDelegate *)[[UIApplication sharedApplication]delegate];
NSDateFormatter *currentdateformate = [[NSDateFormatter alloc] init];
[currentdateformate setDateFormat:@"HH:MM, EEEE, dd-MMMM-yyyy"];
appDelegate.timestamp1 = [currentdateformate stringFromDate:[theDatePicker date]];
NSLog(@"%@",appDelegate.timestamp1);
[currentdateformate setDateFormat:@"MMM dd, yyyy HH:mm"];
self.updatedate = [currentdateformate stringFromDate:[theDatePicker date]];
}
-(void)DatePickerCancelClick
{
self.pickerViewDate.hidden = YES;
self.view.hidden = NO;
[self.pickerViewDate dismissWithClickedButtonIndex:0 animated:YES];
}
-(BOOL)closeDatePicker:(id)sender{
//iRolegameAppDelegate *appDelegate = (iRolegameAppDelegate *)[[UIApplication sharedApplication]delegate];
[pickerViewDate dismissWithClickedButtonIndex:0 animated:YES];
[pickerToolbar release];
[pickerViewDate release];
//[SelectedTextField resignFirstResponder];
if([ self.updatedate isEqualToString:@"nil"]){
NSDateFormatter *currentdateformate = [[NSDateFormatter alloc] init];
[currentdateformate setDateFormat:@"MMM dd, yyyy HH:mm"];
self.updatedate = [currentdateformate stringFromDate:[theDatePicker date]];
[dateSelectButton setTitle:self.updatedate forState:UIControlStateNormal];
self.updatedate = @"";
}
else{
[dateSelectButton setTitle:self.updatedate forState:UIControlStateNormal];
self.updatedate = @"";
}
return YES;
}
-(IBAction)DatePickerDoneClick{
[self closeDatePicker:self];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add a string to a listbox in another opened form?
I am attempting to add a string from frmAddSegment to the listbox in frmMain. frmMain is open when doing this process, just for some reason the string is not being added to the listbox.
I've checked the string I'm attempting to add the listbox by using a message box and it is working fine, it's just not getting to the lsitbox. The modifier property on the listbox has also been set to public
frmMain fmain = new frmMain();
fmain.lstbxSegments.Items.Add(segmentPBMin.ToString()+":"+segmentPBMin.ToString()+"."+segmentPBMils);
I expected the listbox to contain a new item however it remains blank.
A:
frmMain fmain = new frmMain();
You are creating a brand new instance of "frmMain", and adding your item to that instance rather than the one currently running. You should instead do:
the_Form_That_Is_Open_Right_Now.lstbxSegments.Items.Add(... your code here);
If you're having trouble finding where your form is created, you can hit Ctrl+F, make sure the filter is set to "Entire Solution", and search for new frmMain(). You might see something that looks like this:
Application.Run(new frmMain());
You can store that instance in a variable like so:
frmMain yourForm = new frmMain();
Application.Run(yourForm);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java MultiMap Not Recognizing Key
I'm trying to store multiple values for a key in a data structure so I'm using Guava (Google Collection)'s MultiMap.
Multimap<double[], double[]> destinations = HashMultimap.create();
destinations = ArrayListMultimap.create();
double[] startingPoint = new double[] {1.0, 2.0};
double[] end = new double[] {3.0, 4.0};
destinations.put(startingPoint, end);
System.out.println(destinations.containsKey(startingPoint));
and it returns false.
Note: Key-values are being stored in the multimap as the destinations.size() increases when I put something there.It also does not happen when keys are String instead of double[].
Any idea what the problem is?
Edit: Many thanks to Jon Skeet I now implemented the class:
class Point {
double lat;
double lng;
public boolean equals(Point p) {
if (lat == p.lat && lng == p.lng)
return true;
else
return false;
}
@Override
public int hashCode() {
int hash = 29;
hash = hash*41 + (int)(lat * 100000);
hash = hash*41 + (int)(lng * 100000);
return hash;
}
public Point(double newlat, double newlng) {
lat = newlat;
lng = newlng;
}
}
And now I have a new problem. This is how I'm using it:
Multimap<Point, Point> destinations = HashMultimap.create();
destinations = ArrayListMultimap.create();
Point startingPoint = new Point(1.0, 2.0);
Point end = new Point(3.0, 4.0);
destinations.put(startingPoint, end);
System.out.println( destinations.containsKey(startingPoint) );
System.out.println( destinations.containsKey(new Point(1.0, 2.0)) );
The first one returns true, the second one returns false. It gives me an error if I put @Override before the equals method.Any Idea what the problem is now?
Thanks :)
Edit2: It now behaves exactly as expected when I changed equals to this:
@Override
public boolean equals(Object p) {
if (this == p)
return true;
else if ( !(p instanceof Point) )
return false;
else {
Point that = (Point) p;
return (that.lat == lat) && (that.lng == lng);
}
}
Thanks everyone.
A:
You're using arrays as the hash keys. That's not going to work - Java doesn't override hashCode and equals for arrays. (The Arrays class provides methods to do this, but it's not going to help you here.) Admittedly I'd expect it to work in this specific case, where you're using the exact same reference for both put and containsKey... When I test your code, it prints true. Are you sure you can reproduce it with exactly your code?
For example, while I'd expect it to work for the code you've given, I wouldn't expect this to work:
// Logically equal array, but distinct objects
double[] key = (double[]) startingPoint.clone();
System.out.println(destinations.containsKey(key));
It sounds like you shouldn't really be using double[] here - you should create a Point class which has two double variables, and overrides equals and hashCode.
Additionally, using double values in hash keys is usually a bad idea anyway, due to the nature of binary floating point arithmetic. That's going to be a problem even using the Point idea above... it should be okay if you don't need to actually do any arithmetic (if you're just copying values around) but take great care...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does it make sense to say “We came to code”
My mother language is German and I am working as IT professional.
I am about to write a small manifesto on some professional values for a group of people. Since writing source code is more or less the main activity of a programmer does it make sense to use “We came to code – and to build something valuable” as the title of the manifesto?
A:
The phrase "we came to code" is perfectly acceptable as a title. There are other examples of this scattered throughout literature and you can use virtually any variant:
We came to rock
We came to rule
We came to eat cake
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VB.Net Boolean Argument
I was working on an assignment. It is already done, but I would like to find out more efficient way to use Boolean in future projects.
I had multiple functions needed validation. I tried argument with no success and had to create individual Boolean per function.
My code is
Function valChargeParts() As Boolean
Try
If Decimal.TryParse(CDec(txtParts.Text), 1) Then
If CDec(txtParts.Text) >= 0 Then
Return True
End If
End If
Catch ex As Exception
End Try
Return False
End Function
Function valChargeLabor() As Boolean
Try
If Decimal.TryParse(CDec(txtLabor.Text), 1) Then
If CDec(txtLabor.Text) >= 0 Then
Return True
End If
End If
Catch ex As Exception
End Try
Return False
End Function
Function CalcPartsCharges() As Decimal
Dim totalParts As Integer = 0
If valChargeParts() = True Then
totalParts += CDec(txtParts.Text)
End If
Return totalParts
End Function
Function CalcLaborCharges() As Decimal
Dim totalLabor As Integer = 20
If valChargeLabor() = True Then
totalLabor *= CDec(txtLabor.Text)
End If
Return totalLabor
End Function
I tried many possible ways to my knowledge to create arguments, such as;
Function valChargeLabor(ByVal variable as Decimal) As Boolean
and tried using in function,
If Decimal.TryParse(variable, 1) Then
but none worked. I'm not sure what I'm doing wrong.
Thanks in advance.
A:
Looking at your code you are using the TryParse method which will not give you an error if it can not convert, plus you are using multiple casting to decimal that in my opinion are not needed. I have made a common routine that will return a Boolean if it can convert plus it will pass by reference the actual converted value so it will make it like your own TryParse Statement.
This is a simple Modified application to demonstrate what I am talking about.
Public Class Form1
Dim totalParts As Decimal = 0
Function validateInput(value As String, ByRef output As Decimal) As Boolean
Return Decimal.TryParse(value, output)
End Function
Function CalcPartsCharges() As Decimal
Dim tempParts As Decimal = 0
If validateInput(txtParts.Text, tempParts) Then
totalParts += tempParts
End If
Return totalParts
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Text = CalcPartsCharges().ToString()
End Sub
End Class
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does the higher price lens always reflect better quality regardless of it being 3rd party or not?
When looking at various lenses you will see the camera manufacturer lenses made by the camera manufacturer. Then you will see other 3rd party lenses (Tamron, Sigma, etc). Does it pay to get the manufacture lens over the 3rd party lens?
I ask because I have seen some lenses price vary drastically between two lenses.
Here is an example, this Nikkor Lens is priced at $586 (USD) while this Sigma Lens with the same specifications is priced at $169. That is a $417 dollar price difference! With the lower price I would assume lower quality?
Note: I do understand that this can and does vary depending on the manufacturer, model of lens, etc. The answer I am looking for is 1) What is the general rule of thumb? (if there is one) And 2) What do other photographers generally buy?
Edit - I have looked at this question and this one and those two do not answer my question.
Edit 2 - After reading this question and answers I guess my question comes down to this: Does the higher price lens always reflect better quality regardless of it being 3rd party or not?
A:
When comparing lenses, it is important to look at all the qualities and features. In this case, those really are not comparable lenses. The Sigma is their base line, whereas the Nikon is a stabilized, internally focusing, high quality glass lens. The Sigma would compare better to this lens from Nikon, also compatible in price.
When comparing lenses, its important to examine the lens 'name' to know what to look for:
Nikon 70-300mm f/4.5-5.6G ED IF AF-S VR
Focal Length: (70-300) be sure both lenses are similar focal length: 70-300 in this case
Maximum aperture:(f/4.5-5.6) Aperture has a big impact on price, as lenses with lower aperture numbers require larger pieces of glass to support such large aperture. Some zooms, like these, provide multiple maximum apertures (4.5-5.6) meaning it is f4.5 at 70, and f5.6 at 300. Pricier lenses will list f2.8 for example.
Stabilization: (VR) mechanics that reduce vibration or shake are expensive. These are called VR, IS or OS by several brands.
High quality glass: (ED) special low distortion or low dispersion lenses add to the quality of the image, but also the cost. Nikon uses the words ED, Canon doesn't use a designation, but their L lenses have such glass.
Other: (AF-S indicates ultrasonic focus motor [hat tip rfusca], IF means Internally Focusing)
A:
Good things are not cheap and cheap things are not good.
This is true of all lens manufacturers. There is a small premium for brand name lenses usually but price is largely proportional to quality. For example, Sigma produces plenty of cheap low-quality lenses but they also produce some excellent lenses and, guess what?, they are far from cheap.
When evaluating lenses you just have to look at the whole specification as @cmason mentioned. Unfortunately, there is no absolute specification for quality. The thing is that other than focal-length, aperture and a few other easily measurable specifications, plenty of things are not comparable. Stabilization for example is not the same between brands and even between models of the same brand. The same with adjectives used to describe optical glass like ED (Extra Low Dispertion, How low?), HRI (High Refrective Index, How High?), etc.
You can start with the MTF chart for contrast and sharpness but it does not say anything about distortion, vignetting and aberrations. This is when price is a big indicator as are good reviews. Sadly, they are hard to come buy and there are often large variations (more so with third-party lenses based on my experience) between lens quality from unit to unit.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java Concurrency - best complete tutorial and sample code needed
Can you please suggest some good tutorial for Java Concurrency. Where can i get some sample code also.
A:
This is also a nice series of articles covering the topic:
http://www.baptiste-wicht.com/2010/05/java-concurrency-part-1-threads/
http://www.baptiste-wicht.com/2010/05/java-concurrency-part-2-manipulate-threads/
http://www.baptiste-wicht.com/2010/08/java-concurrrency-synchronization-locks/
http://www.baptiste-wicht.com/2010/08/java-concurrency-part-4-semaphores/
http://www.baptiste-wicht.com/2010/09/java-concurrency-part-5-monitors-locks-and-conditions/
http://www.baptiste-wicht.com/2010/09/java-concurrency-atomic-variables/
http://www.baptiste-wicht.com/2010/09/java-concurrency-part-7-executors-and-thread-pools/
A:
First google link:
http://download.oracle.com/javase/tutorial/essential/concurrency/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why won't jquery run on my local machine?
The following script will work on jsfiddle (see below) but wont work on my local machine.
http://jsfiddle.net/gFaZn/
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type="text/javascript" src="script.js"></script>
<link type="text/css" rel="stylesheet" href="stylesheet.css">
</head>
<body>
<div></div>
</body>
</html>
Can anyone tell me what I am doing wrong?
Thanks
A:
// tells the browser to match the current protocol. It's fine if you're on a webserver, as it'll switch to http or https, but you're probably loading the file directly with the browser, so it'll expand to file://.
You need to specify the protocol explicitly:
src="http://...
Better yet, use a local webserver.
A:
Try replacing
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
with
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
|
{
"pile_set_name": "StackExchange"
}
|
Q:
XML Schema that allows anything (xsd:any)
I need an example of XML schema that will allow anything and everything.
It might sound weird like this, but I need that to debug my current schema. The thing is that I have a complex object that I use in a function (part of a DLL I have no control over) along with a schema, and that functions returns me the XML. For now the function throws an exception because there's an error while validating with the schema, but there shouldn't be one. So, I want a blank schema, a schema that will not cause any validation error, so I can see the XML outputted by the function.
I tried to take my current schema, and keep only the xs:schema tag to create an empty schema, but that obviously didn't work.
A:
XML Schema cannot specify that a document is valid regardless of its content.
However, if you're able to specify the root element, you can use xs:anyAttribute and xs:any to allow any attributes on the root element and any XML under the root:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:any processContents="skip" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:anyAttribute processContents="skip"/>
</xs:complexType>
</xs:element>
</xs:schema>
In your case, as long as you can be assured of a finite number of possible root element names, you can use this technique to allow any XML content under a root element with a known name.
Update: This can be written much more concisely [Credit: C. M. Sperberg-McQueen]:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root"/>
</xs:schema>
Note that this is allowing, but not requiring, root to be empty.
A:
It's often assumed that an XML schema partitions documents into those that are valid and those that are not. It's actually rather more subtle than that. When you invoke validation, you need to say how you want the validation done. The most common invocation is strict validation, in which case either the name of the root element in your instance document must correspond to the name of a global element declaration in your schema, or it must have an xsi:type attribute that matches a global type definition in your schema. It follows that no finite schema will match every document instance under strict validation.
In principle you can also invoke a schema processor to do lax validation. In this case, if there is no match for the root element name among the global element declarations in the schema, validation succeeds. So the empty schema (no declarations) matches every instance document under lax validation.
You can also invoke validation against a named type. If you invoke validation against the named type xs:anyType, then every instance is valid, regardless what the schema says.
Caveat: I've considerably simplified the rules here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scala switch which continue matching next cases after successful match
How can I do in scala switch statement which after performing one case block start perform another case block. (in java: cases without break).
switch(step) {
case 0: do something;
case 1: do something more;
case 2: etc...;
break;
default: do something else;
}
Thanks for help!
A:
def myMatch(step: Int): Int = step match {
case 0 => { dosomething(); myMatch(step + 1) }
case 1 => { dosomethingMore(); myMatch(step + 1) }
case 2 => etc()
case _ => doSomethingElse();
}
If the performance isn't critical, this should be fine.
A:
In case you can't use 0 | 1 | 2 you could use a list of actions as workaround like this:
def switch[T](i: T)(actions: (T, () => Unit)*)(default: => Unit) = {
val acts = actions.dropWhile(_._1 != i).map{_._2}
if (acts.isEmpty) default
else acts.foreach{_()}
}
def myMethod(i: Int): Unit =
switch(i)(
0 -> {() => println("do 0")},
1 -> {() => println("do 1")},
2 -> {() =>
println("do 2")
return // instead of break
},
3 -> {() => println("do 3")}
)(default = println("do default"))
myMethod(1)
// do 1
// do 2
myMethod(3)
// do 3
myMethod(5)
// do default
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting Text out of HTML into Javascript as a Function with Input Changing IDs
I am trying to create an if/else statement that checks the text of a button that the user presses. If there is no text in that button, it continues the function, if there is pre-existing text then it gives an alert stating that there is already an entry there.
Essentially, the user clicks a button and the code checks to see if that button is empty or not. However, since the button's ID is constantly changing, I don't know how to tell the code to check the pressed button. I feel that using 'this' is part of the solution to this problem, but I am too new to JavaScript to use it correctly.
This is my entire JavaScript code, off it works fine except for the two lines that have comments in them. I am trying to make the variable "inSquare" to equal the text from the button that triggered the function. Then it goes on to check the text of the variable, but currently all it does is fail the if and head straight to the else.
var turnNumber = 9;
var whoseTurn;
var inSquare;
function currentTurn(id) {
inSquare = this.innerHTML; /*This Line*/
if (inSquare === "") { /*This Line*/
if (whoseTurn === 0) {
id.innerHTML = "X";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
} else {
id.innerHTML = "O";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
}
} else {
window.alert("Something is already in that square!");
}
}
Also, here is an example of what the HTML buttons look like. (There are nine total, but they are all formatted the same).
<button id="topLeft" onclick="currentTurn(this)"></button>
<button id="topMid" onclick="currentTurn(this)"></button>
<button id="topRight" onclick="currentTurn(this)"></button>
A:
inSquare = this.innerHTML; should be inSquare = id.innerHTML;
this in your function refers to the window object, but you want to refer to the element you passed, which you provided as the id argument of the function.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ansible parse for a specific line in resulted registered var
Under my ansible playbook , i ve a task which execute a script:
- name: Execute Update on selected databases
shell: "./script_update.sh server007 {{item}} {{bdd_config[item].updateFile }}"
with_items: "{{selected_DBS}}"
register: updateResult
the result of this script ca be something like this:
INFO - ================================================================================
INFO - BEGIN 'script_update' ON ini99db1 AT 2019/05/22 12:22:06
INFO - ================================================================================
INFO - THE MySQL SERVER server007 EXISTS
INFO - THE MySQL SERVER server007 IS ON
INFO - THE DATABASE myDB EXISTS
INFO - FILE /opt/myscode_In_progress.sql EXISTS.
ERROR - ERROR 1064 (42000) at line 4 in file: '/opt/myscode_In_progress.sql': You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'azdazdazdazdazd' at line 1
INFO - SCRIPT OUTPUT : SEE LOG FILE 1
INFO - THE DB HAS BEEN CORRECTLY UPDATED
INFO - --------------------------------------------------------------------------------
INFO - THE PROCESS TERMINATED SUCCESSFULLY
INFO - SEE THE LOG FILE /opt/mysql/log/app_20190522_12H22.log
When Displaying the output of my register variable (updateResult) , it gives something like this :
"msg": {
"changed": true,
"msg": "All items completed",
"results": [
{
"_ansible_ignore_errors": null,
"_ansible_item_label": "nomadisdb",
"_ansible_item_result": true,
"_ansible_no_log": false,
"_ansible_parsed": true,
"changed": true,
"cmd": "./rcd_db_update.ksh myserver01 nomadisdb nomadisdb_In_progress.sql",
"delta": "0:00:12.786607",
"end": "2019-05-22 12:36:52.817077",
"failed": false,
"invocation": {
"module_args": {
"_raw_params": "./rcd_db_update.ksh myserver01 nomadisdb nomadisdb_In_progress.sql",
"_uses_shell": true,
"argv": null,
"chdir": "/opt/application/i99/current/sh",
"creates": null,
"executable": null,
"removes": null,
"stdin": null,
"warn": true
}
},
"item": "nomadisdb",
"rc": 0,
"start": "2019-05-22 12:36:40.030470",
"stdout_lines": [
"\tINFO - ================================================================================",
"\tINFO - BEGIN 'rcd_db_update' ON ini99db1 AT 2019/05/22 12:36:50",
"\tINFO - ================================================================================",
"\tINFO - THE MySQL SERVER myserver01 EXISTS",
"\tINFO - THE MySQL SERVER myserver01 IS ON",
"\tINFO - THE DATABASE nomadisdb EXISTS",
"\tINFO - FILE /opt/application/i99/current/sql/nomadisdb_In_progress.sql EXISTS.",
"\tERROR - ERROR 1060 (42S21) at line 4 in file: '/opt/myDB_In_progress.sql': Duplicate column name 'con_habilitation_version'",
"\tINFO - SCRIPT OUTPUT : SEE LOG FILE 1",
"\tINFO - THE DB HAS BEEN CORRECTLY UPDATED",
"\tINFO - --------------------------------------------------------------------------------",
"\tINFO - THE PROCESS TERMINATED SUCCESSFULLY",
"\tINFO - SEE THE LOG FILE /opt/mysql/log/rcd_db_update_myserver01_nomadisdb_20190522_12H36.log",
"\tINFO - ================================================================================",
"\tINFO - END 'rcd_db_update.ksh' ON ini99db1 AT 2019/05/22 12:36:50",
"\tINFO - ================================================================================"
]
}
]
}
}
My purpose is to grep over this output msg and search fo any ERROR line , like this :
"\tERROR - ERROR 1060 (42S21) at line 4 in file: '/opt/myDB_In_progress.sql': Duplicate column name 'con_habilitation_version'",
i may search it with a regExp which looks for lines that start with "ERROR" and includes "at line" and "in file"
Finally i should get this whole line as a result
I ve tried to use a regexp like this:
- name: set regex
set_fact:
regExpOfSqlError: ' '
become_user: mysql
- set_fact:
errorLine: "{{ updateResult.results | regex_search(regExpOfSqlError, ' ') }}"
become_user: mysql
But i still wonder what RegExp should i put , to search forthose lines , and ouput them
Suggestions ?
A:
A simple solution is to use the json_query filter.
Notes:
json_query is dependent on jmespath. You will need to pip(3) install jmespath prior to running the example.
The to_json | from_json hack is needed to work arround a known bug when using jmespath contains function in ansible. This needs a modification on jmespath side still waiting for approval/development
You should read the jmespath documentation for further details, but here is a quick explanation of the query string in my example: create a list projection of all input elements (updateResults.result), then select all elements in stdout_lines entry containing text ERROR and finally project the result as a flat list.
---
- name: SO Test
hosts: localhost
vars:
# This result var mimics your current captured result
# I only kept the relevant part for the example.
updateResult:
results:
- stdout_lines: [
"\tINFO - ================================================================================",
"\tINFO - BEGIN 'rcd_db_update' ON ini99db1 AT 2019/05/22 12:36:50",
"\tINFO - ================================================================================",
"\tINFO - THE MySQL SERVER myserver01 EXISTS",
"\tINFO - THE MySQL SERVER myserver01 IS ON",
"\tINFO - THE DATABASE nomadisdb EXISTS",
"\tINFO - FILE /opt/application/i99/current/sql/nomadisdb_In_progress.sql EXISTS.",
"\tERROR - ERROR 1060 (42S21) at line 4 in file: '/opt/myDB_In_progress.sql': Duplicate column name 'con_habilitation_version'",
"\tINFO - SCRIPT OUTPUT : SEE LOG FILE 1",
"\tINFO - THE DB HAS BEEN CORRECTLY UPDATED",
"\tINFO - --------------------------------------------------------------------------------",
"\tINFO - THE PROCESS TERMINATED SUCCESSFULLY",
"\tINFO - SEE THE LOG FILE /opt/mysql/log/rcd_db_update_myserver01_nomadisdb_20190522_12H36.log",
"\tINFO - ================================================================================",
"\tINFO - END 'rcd_db_update.ksh' ON ini99db1 AT 2019/05/22 12:36:50",
"\tINFO - ================================================================================"
]
tasks:
- name: Capture a list of all lines containing an error in all results
set_fact:
error_lines: "{{ updateResult.results | to_json | from_json | json_query(\"[].stdout_lines[?contains(@, 'ERROR')][]\") }}"
- name: Show lines with errors
debug:
var: error_lines
Which gives:
PLAY [SO Test] *****************************************************************
TASK [Gathering Facts] *********************************************************
ok: [localhost]
TASK [Capture a list of all lines containing an error in all results] **********
ok: [localhost]
TASK [Show lines with errors] **************************************************
ok: [localhost] => {
"error_lines": [
"\tERROR - ERROR 1060 (42S21) at line 4 in file: '/opt/myDB_In_progress.sql': Duplicate column name 'con_habilitation_version'"
]
}
PLAY RECAP *********************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does the kubernetes-vault init container need to unwrap the secret id supplied by the controller?
In the diagram on the kubernetes-vault repo, you can see that the init container takes the wrapped secret_id and the unwraps and redeems the secret_id for a token via Vault. Why doesn't the kubernetes-vault controller do this unwrapping and redemption itself and simply transmit the token to the init container?
https://github.com/Boostport/kubernetes-vault/raw/master/flow-diagram.png
A:
Note: The kubernetes-vault project is an open-source project maintained by my company.
The reason the init container unwraps the secret is 2 fold:
Only the init container and the pod it is in is able to see the final secret. That means that the kubernetes-vault controller does not know what the token is and is not able to use it for malicious purposes if compromised.
If a someone intercepts the wrapped token and unwraps it, the init container would not be able to unwrap the token and this is a good signal that cluster has been compromised. If the unwrapped token is sent to the init container, it can be intercepted and it would not be possible to alert on this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Opensplice failed to build dcpsisocpp2
I downloaded the latest source code of Opensplice DDS from https://github.com/ADLINK-IST/opensplice and tried to build it by following its instructions (source setenv, source ./configure, then make ..) in my Cygwin 64 bit.
The build (make command) appeared to be completed, but a number of modules such as dcpsisocpp2, durability, spliced didn't get built (I can't find dcpsisocpp2.dll, etc).
I wonder if anyone who is familar with Opensplice's makefile system can direct me to solve the problem.
A:
You should identify you are going to use community or enterprise version.
It seems the community version doesn't have spliced and durability services. Also, dcpsisocpp2 use C++03 which is a very old C++ standard, that when you use C++11 or C++14 writing your application, you might get some warning or error and spend lots of time fixing compile problems.
Try to use dcpssacpp which follows the C++11 standard.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Max number of players in multiplayer
How many players can play simultaneously in a multiplayer game ? Is it the same for both internet and LAN games ?
A:
The maximum players in a non-modded TL2 game is 6 players. However, an official mod by Runic Games extends this limit to 8. The limit is the same in both internet and LAN games.
Keep in mind that the host of the game (the creator) can set a smaller limit on the number of players allowed in the game, if he/she chooses.
Mod for Steam version: http://steamcommunity.com/sharedfiles/filedetails/?id=135166277
Mod for non-Steam version: http://www.runicgamesfansite.com/vbdownloads.php?do=download&downloadid=380
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Names for strokes
What do we call the different types of strokes of kanji/kana in Japanese?
For example, in Chinese the left-downward stroke is called 撇[piě] and the right-downward stroke is called 捺[nà]. And if I wanted to describe what 八 looks like, I would say (in Chinese) "一个撇, 一个捺".
Are the Japanese names for strokes commonly used? I would assume so since it's a rather convenient way (for me at least) to describe what a Chinese character looks like in the absence of any writing material to show it (alternatively I could write in the air). Can I similarly describe kanji using Japanese names for the strokes?
A:
These stroked are called 筆画, and as for kanji, it is traditionally said that there are eight types of strokes (I copied the words from the webpage that I linked below):
1) 点 ([側]{ソク})
2) 横画 ([勒]{ロク})
3) 縦画 ([努]{ド})
4) はね, かぎ ([趯]{テキ})
5) 左はらい ([掠]{リャク})
6) 右はらい ([磔]{タク})
7) 右上がりの横画 ([策]{サク})
8) 短い左はらい ([啄]{タク})
And all those eight appear in the character 永. This web page provides a good explanation.
Modern treatment suggests a slightly different set of strokes. According to this web page, it replaces 7 and 8 above with the following two:
9) かぎ
10) おれ
I think this modern set is familiar among Japanese, but when they need to refer to the kanji in the absense of a writing material, it is more common to refer to the radical (部首) or to refer to a word that includes that character (for example, 田んぼの「田」).
There are probably no such notions for kana.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is wrong with my logic?
So I was trying to do some problems from this website. And on Problem number 10 I tried to do the following:
$$\lim_{x \to 0} \frac{x^3-7x}{x^3}$$
Multiply everything by $\frac{x^{-3}}{x^{-3}}$
$$\lim_{x \to 0} \frac{x^3-7x}{x^3}\times\frac{x^{-3}}{x^{-3}}$$
Which I got equals:
$$\lim_{x \to 0} \frac{1-7x^{-2}}{1}$$
Plug in $0$ for $x$ and I get:
$$\frac{1}{1} = 1$$
But, the answer according to the website is $-\infty$. (And therefore no limit exists). What was wrong about multiply by $\frac{x^{-3}}{x^{-3}}$ ?
A:
$0^{-2}$ is $\frac1{0^2}$ which is $\frac1{0}$. Now, normally this would be a divide by zero right? Well, with limits it's not technically $0$, it's actually a very tiny number that's infintesimally close to $0$. So when you divide $1$ by some itty bitty number, you get a very massive number. As you bring that number that's very close to $0$ ever closer, the result grows ever larger. It grows infinitely large and thus to infinity. The negative arises from the negative cooeficient if I recall correctly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Improper integral problem
I am currently on this problem
$$\int_{2}^{N}\frac{dt}{t\,(\log t)^{\frac{t+1}{t}}}$$
I tried to make substitution but it wouldn't work. That is, $x=\log t$ and my result was
$$\int_{2}^{N}\frac{dt}{t\,(\log t)^{\frac{t+1}{t}}}=\int_{\log 2}^{\log N}x^{-1-e^{-x}}dx.$$
I think I got it wrong somewhere. Please, could anyone help me out?
A:
It is useful to notice that
$$ \int_{2}^{N}\frac{dt}{t\log t}=\left[\log\log t\right]_{2}^{N} = \log\log N-\log\log 2\tag{1}$$
$$\forall \alpha>0,\qquad \int_{2}^{N}\frac{dt}{t\left(\log t\right)^{1+\alpha}}=\left[-\frac{1}{\alpha\left(\log t\right)^{\alpha}}\right]_{2}^{N}=-\frac{1}{\alpha\left(\log N\right)^{\alpha}}+\frac{1}{\alpha\left(\log 2\right)^{\alpha}}\tag{2} $$
hence by evaluating the RHS of $(2)$ at $\alpha=\frac{1}{2}$ and $\alpha=\frac{1}{N}$ we have that the given integral is convergent.
On the other hand, $\frac{1}{t\left(\log t\right)^{1+\frac{1}{t}}}$ does not have an elementary primitive.
What is the actual statement of the original problem?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I test my water?
Inspired by this question. How do I test my water?
A:
If you have city water, they usually sent out a water profile a couple of times a year. It will be an average of the whole city, but it'll give you a general idea of what you're dealing with.
You can also send your water away to a lab to get tested. I've never bothered, so you'll need to find a reputable lab.
A:
A city water report is the first place to look, but given where your city gets it's water, the values can fluctuate pretty significantly. For example, my city gets water from a few sources; sometimes they'll mix in well water, and thus the water has higher hardness, or they might be taking surface water shortly after a fresh rain.
The question to also ask is "why" should you test your water. To answer that, a good starting point are sections 15.0 though 15.4 in Palmer's How to Brew:
http://www.howtobrew.com/section3/chapter15-1.html
Water chemistry does have a significant affect on beer flavor. Often water chemistry is the last bit of tweaking needed to make a good beer great. Having said that, it's also an easy way to muck up a beer. Water chemistry (aside from proper filtration) should be your last concern in making beer. Sanitation, yeast handling, temperature control, recipe formulation and brewing process should all come first.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Border-color transition css3 bug
I was trying to do a transition on a border-color property on my website, but I have a little bug on it and I don't know where he comes from.
When my mouse is on the button/link, the border becomes blue and then the transition comes.
I tried this code on firefox/chrome/opera and this problem appear on all of them, so it's probably an error from me.
You can see the problem there: http://jsfiddle.net/u3Ahk/15/
.bouton a {
transition: background-color 1s, border-color 1s;
padding: 5px 7px 8px 7px;
text-decoration: none;
}
Thanks in advance !
A:
Updated fiddle.
Explicitly state the transparent border in the normal state of the link:
.bouton a {
transition: background-color 1s, border-color 1s;
padding: 5px 7px 8px 7px;
text-decoration: none;
border: 1px solid transparent; /* this */
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I get only the attributes as in HTML the page?
Let's assume a HTML like this (attributes aren't fixed):
<input type='text' value='a' name='A' id='A'> <br>
<input type='text' value='b' id='B'><br>
<input type='checkbox' name='C'><br>
I'd like to get only the attributes as seen in the HTML, i.e from first input: type, value, name, and id. From second, text, value and id. And so on. Not all attributes of a DOM element like .attributes property does return.
Imaginary code:
function grab_attributes(element)
{
var result = {};
var attributes = element.attributes;
for(var key in attributes)
{
if(is_seen_in_html_page(key))
result[key] = attributes[i];
}
return result;
}
So (considering above HTML as our document)
var e = document.getElementsByTagName("*") [0];
var result = grab_attributes(e);
Result is:
{type: "text", value: "a", name: "A", id: "A"}
I'm stuck on how to define the is_seen_in_html_page(e) function. I'm looking for an elegant solution as possible, without regex to get that values.
A:
They are attribute nodes, so they are instances of Attr.
function grab_attributes(element) {
var result = {};
var attributes = element.attributes;
var attribute;
for(var key in attributes) {
attribute = attributes[key];
if (attribute instanceof Attr) {
result[attribute.name] = attribute.value;
}
}
return result;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reuse lines of code in Stata, Similar to JavaScript function?
I have some lines of code in a Stata do-file that I would like to reuse/execute and different points in the do file. Similar to a JavaScript function... however I do not necessarily need an input variable.
For example, I have some code:
*code to reuse
foreach x in test1 test2 test3{
rename variable_`x' variablenew_`x'
}
and I want to execute those 3 lines of code at various points in the do file. As if there was a way to label those three lines codeA and then execute codeA later in the do file.
Any suggestions?
A:
Check help program.
An example program (that takes no arguments):
// define program
capture program drop hello
program hello
display "hello world!"
end
// try it out
hello
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MYSQL Join three tables and group by joined date
I am a MySQL beginner so please be patient with me!
I have three tables
1-Order
Order Id | Order Date
2-users
user Id | Registration date
3-connection
user Id | Order ID
I am trying to calculate conversion rate grouped by date
The conversion rate, example, 300 users registered in January 2013, and 100 of them made one or more purchases, the conversion rate of the registered user to purchaser is 33%
so the final output should be
table
date | number of registered users | number of orders | Conversion rate
Jan-2011| 300 | 100 | 33%
many thanks for the help!
A:
I think something like this is that you need:
select u.registrationDate as date,
count(distinct u.id) as number_of_registered_users,
count(distinct o.id) as number_of_orders,
round(count(distinct o.id)/count(distinct u.id)*100) as conversion_rate
from users u
left join `Order` o on u.registrationDate = o.orderDate
left join connection c on c.orderId = o.id and c.usersId = u.id
group by u.registrationDate;
See SQL Fiddle.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
select tag using $(this), from ajaxform plugin constructor
Note : I have titled it very poorly, please help me improve it, if you understand my question
I am using ajaxform submit for all of my forms. I am able to programatically add a feedback div to each form successfully. I want to select only current form in my page. I am using following code.
$('form').append('<div class="feedback" />');
$('form').ajaxForm
({
success: function(responseText)
{
if(responseText=="1")
{
$(this).clearForm();
$(this).children('INPUT,select').eq(0).focus();
}
else
{
alert($(this).children().length); // This gives me 0
$(this).children('.feedback').eq(0).html(responseText);
}
}
});
I can do the above successfully only if I have one form in whole page using $('form') instead of $(this) but it makes problem when i have multiple forms in a page
A:
If you look closer at the docs, will see that the success callback is passed 4 arguments
1.) responseText or responseXML value (depending on the value of the dataType option).
2.) statusText
3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)
Use the last argument instead of $(this) for current form instance
See options tab of docs
Update by asker : working code from above answer I got is following
Instead of $(this) I could do following
$('form').append('<div class="feedback" />');
var options = { success: showResponse };
$('form').ajaxForm(options);
function showResponse(responseText, statusText, xhr, $form)
{
if(statusText == 'success')
$form.children('.feedback').html(responseText);
}
Link of example followed
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is difference between open set and open interval?
Let $\tau$ be the Euclidean topology defined on $\mathbb R$. If we define a set $S = (2,3) \cup (5,6)$. Then is the set $S$ an open set and open interval on $\tau$?
As per definition of open set,
A subset $A$ of $\tau$ is open set if $\forall x \in A$, $\hspace{5pt} \exists \hspace{3pt} a,b $ such that $x \in (a,b) \subseteq A$
As per this definition, we can find $(a,b) \in S$ such that $x \in (a,b)$. $x$ is any number in set $S$. So, set $S$ is open set.
I am not sure whether I correctly proved why set $S$ is open set. But I do not know how to prove set $S$ is open interval.
A:
$S$ is not an interval, open, or otherwise.
An interval $I$ in any ordered set has the property:
If $a<b<c$ and $a,c\in I$ then $b\in I$.
Your set $S$ is therefore open, but not an interval. It is the union of two open intervals.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
The covariance of two related variables each multiplied by a third independent variable
If given a known covariance,
\begin{equation}
cov(X,Y),
\end{equation}
what would the covariance,
\begin{equation}
cov(RX,RY)
\end{equation}
be, if R is an independant random variable with a variance $R_v$ and an expectation $R_e$?
I believe the covariance if all variables are mutually independant can be given by:
\begin{equation}
cov(RX,RY) = R_vX_eY_e
\end{equation}
where $X_e$ and $Y_e$ are the expectations of X and Y, but is it possible to solve this if there is a covariance between X and Y?
A:
If you also know the means of $X,Y$, you can use the definition of covariance:
$$\begin{align}\operatorname{cov}(RX,RY)&=E[R^2XY]-E[RX]E[RY]\\&=E[R^2]E[XY]-E[R]^2E[X]E[Y]\\&=(\sigma_r^2+\mu_r^2)(c_{xy}+\mu_x\mu_y)-\mu_r^2\mu_x\mu_y\end{align}$$
where $c_{xy}=\operatorname{cov}(X,Y)$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to run a command in Windows batch script?
I'm trying to feed the file name dynamically to a command through windows batch script. Here's my code,
@echo off
set /p path="Enter the project path: "
for /R "%path%" %%I in (*.java) do (java -classpath MyCheckStyle.jar;checkstyle-5.6-all.jar com.puppycrawl.tools.checkstyle.Main -c custom_check.xml %%I)
pause
Basically, I want to get all the .java files from any given directory and feed those java files to another command which will run for each file. In place of %%I I am trying to provide the java file dynamically. But it says java command not recognized.
If I use java -classpath MyCheckStyle.jar;checkstyle-5.6-all.jar com.puppycrawl.tools.checkstyle.Main -c custom_check.xml path/filename.java alone in a batch file. It works fine.
I have tried the following also,
@echo off
set i=-1
set /p path="Enter the project path: "
for /R "%path%" %%I in (*.java) do (
set /a i=!i!+1
set filenames[!i!]=%%I
)
set lastindex=!i!
for /L %%f in (0,1,!lastindex!) do (
java -classpath MyCheckStyle.jar;checkstyle-5.6-all.jar com.puppycrawl.tools.checkstyle.Main -c custom_check.xml !names[%%f]!
)
pause
But again it says java command not recognized.
What am doing wrong here? Why I can not pass the .java file names dynamically?
A:
Your named your variable with project path "path", and it's bad, because as soon as you do
set /p path="Enter the project path: "
you overwrite the system "path" and then Windows cannot find your "java.exe".
Rename it to project_path:
set /p project_path="Enter the project path: "
for /R "%project_path%" %%I in .......
|
{
"pile_set_name": "StackExchange"
}
|
Q:
For $H=\{(x,y)\in\mathbb{Z}:3x+4y\equiv 0 \mod 5\}$, find a group isomorphism $\mathbb{Z}^2\to H$
I'm working through group theory problems and I'm trying to do the following exercise:
For $H=\{(x,y)\in\mathbb{Z}:3x+4y\equiv 0 \mod 5\}$, find a group isomorphism $\mathbb{Z}^2\to H$ and show $[\mathbb{Z}^2:H]=5.$
I tried defining the group isomorphism in $5$ cases, letting the value of $f(x,y)\in H\subset\mathbb{Z}^2$ depend on the value of $y$ modolu $5$, but it didn't work out since the map wasn't even a homomorphism. Also, it is really simple to find an injective homomorpism by $(x,y)\mapsto(5x,5y)$, but that does not really help either, of course. I thought about choosing a map that fixes the second element, and by using an enumeration of all solutions of $3x+4y\equiv 0 \mod 5$ for each value of $y$, mapping $k\geq0$ to the $(k+1)$'th positive solution for $x$ and similarly for $k<0$. However, this also does not seem to give rise to a homomorphism, although it seems (to me) a well-defined bijection.
I think I'm missing some clever trick I can use but I don't see it. Can anyone give me a hint for the homomorphism? I think after that the second part (showing that $[\mathbb{Z}^2:H]=5$ is not too difficult therafter), so my question is mainly about the first part. Any help is much appreciated!
A:
Some ideas for you:
Define, for example,
$$f(1,0):=(2,1)\;,\;\;f(0,1):=(3,-1)$$
and extend the definition to $\;\Bbb Z^2\;$ by $\;\Bbb Z\,-$ linearity ( which is simply to apply the universal property of the free abelian group $\;\Bbb Z^2\;$ on the free generators $\;(1,0),\,(0,1)\;$). Observe that you get for free that $\;f\;$ is a group homomorphism. Now just show it is onto and its kernel has actually index $\;5\;$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
socket.io + redis - ghost sockets - is it possible?
I've made an app with node.js, socket.io, clusters, redis and it run in 8 processes.
Is it possible that each process has a some ghost-sockets? I mean sockets which has already disconnected but not every process knows about it and still has them.
My app send to client an online count(socket count from two rooms) in connection event. And process called "HEAD" send every 3 sec, to all sockets "online count" too. Why Am I telling it? When I connect to app in browser first get "online count" from one of 8 processes, let it be 60, and after 3 sec, i get from HEAD process "online count" but then it is very different number.
So I think some things aren't sync through Redis to processes. Is it possible?
A:
What you want to do is possible but it's a very convoluted way of doing it. Also, considering that you are using node.js, which doesn't have an asynchronous model but polls instead, it would likely be better to poll those connections within node.js which would be straightforward.
Your question is slightly confusing so I hope I understood it well enough.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clojure String to Form
I would like to convert a string to a form in clojure. Something like
(defn string-to-form [string]
;; some magic here
converted-to-form)
This question has the opposite direction, namely form to string. How to I go the other way?
A:
hey if i am correct your want to know
"(+ 1 2)" ;=> (+ 1 2)
if these is you problem then you can use read-string from clojure.core
(defn string-to-form [string] (read-string string))
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.