source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"superuser",
"0000546578.txt"
] | Q:
Win 7 taskbard do not apear after start
After I killed a virus in the PC and restarted it, everything works fine but the taskbar with the start menu and the icons in the desktop aren't apear.
I still can open and run everything from Task Managger but can't start the process that managges the taskbar and the desktop, however in the Processes tab I can see that dwm.exe and explorer.exe is running. I tried to delete and restart these processes but dwm.exe doesn't do anything while explorer.exe only opens up My Computer.
I also tried system restore points but there is only one point I can restore to and that didn't solve anything.
I know I could reinstall the computer but this is my last solution. What other things I should try?
A:
I'm going to oversimplify in order to put this into terms that you can understand.
When attempting to clean up after a malicious piece of software (virus), there are at least two things that can go wrong:
Overkill, which means that not only do you completely eliminate the virus, but you eliminate significant parts of the functionality of your operating system that are required for normal system operation. So, while the virus is gone, your system is not working properly because whatever tools you used to get rid of the virus also got rid of essential system components or programs.
Underkill, which means that you think you killed the virus, but some part of it remains, or it did something to adaptively avoid detection (e.g. change its signature). If any traces of malicious code are still running, it may also manifest itself as similar symptoms to overkill; the virus may be operating in a reduced functionality mode for a while until you decide to go back to using your system normally, and then it re-manifests itself.
Since it is not generally possible to tell whether you've done overkill or underkill (the worse of the two possibilities is underkill since you may lose even more of your personal information to identity thefts if you continue to use the compromised computer), you should probably avoid the risk, and just reinstall.
Nuking the system from orbit at this time (including all except, perhaps, data files which have no executable components, like mp3s and images) would be highly recommended.
|
[
"stackoverflow",
"0012281099.txt"
] | Q:
How do I duplicate VM properties to JUnit task in ANT?
As part of a JUnit test (executed from ANT) I need access to a fair few properties that are not only environment dependent, but can also change from one run to the next. In order to not affect any of numerous other devs that might use the same build.xml I wanted to define these properties on the command line with the -D flag (they're easily populated using a script). Reading about the <junit> task in ant I thought that these properties would be easily duplicated to the VM running the JUnit tests using the clonevm flag, but this doesn't seem to work. A simple <echo> before the <junit> call confirms the properties are set correctly, and I then execute the JUnit tests with the following:
<junit
printsummary="on" showoutput="true" timeout="${tests.timeout.value}"
haltonfailure="false" errorproperty="test.error.occurred"
haltonerror="false" failureproperty="test.failure.occurred" forkmode="perTest"
maxmemory="${project.junit.maxmemory}" clonevm="true">
<jvmarg line="${project.test.vmargs}"/>
<sysproperty key="java.io.tmpdir" value="${java.io.tmpdir}"/>
<formatter type="xml" usefile="true"/>
<classpath>
<path refid="build.test.classpath"/>
</classpath>
<batchtest fork="yes" todir="${test.rpt.dir}">
<fileset dir="${test.bin.dir}">
<include name="**/${test.classes.run}.class"/>
<includesfile name="${test.run.includesfile}"/>
<!-- ignore inner classes -->
<exclude name="**/*$*.class"/>
</fileset>
</batchtest>
</junit>
I then attempt to read a property value using System.getProperty("property"); but always get null. I assume I must be doing something wrong so that the properties aren't sent to the JUnit VM, or I'm not reading it correctly. Any ideas? I guess I could work around the problem (use the script to write a temporary properties file, then read that from the test), but I'd still like to know how to do this if it's even possible.
A:
Try using a nested syspropertyset element.
See junit documentation
|
[
"stackoverflow",
"0047632510.txt"
] | Q:
Consume same record after manual commit failed
I have a KafkaConsumer which consumes messages, does some processing and then a KafkaProducer sends message to another topic. I am currently manually committing the offset using Acknowledge.acknowledge() when KafkaProducer successfully sends message to another topic, but I do not call Acknowledge.acknowledge() when message fails to send. I have set ackMode to AckMode.MANUAL_IMMEDIATE
However when I do not commit the offset manually, KafkaConsumer should pick the same record that failed to process (i.e failed to send to another topic) but even on failure the offset is incremented and the next record is processed. Can anyone tell me why this is happening? And how can I achieve this?
KafkaConsumer.java
@Autowired
private KafkaProducer kafkaProducer;
@KafkaListener(id = "workerListener", topics = "${kafka.topic.name}",
containerFactory = "workerKafkaListenerContainerFactory")
public void workerListener(ConsumerRecord<?,?> consumerRecord, Acknowledgment ack) {
// Do something! Process consumer record
// Now producer will send to another topic
kafkaProducer.sendNotification(notification, ack);
}
KafkaProducer.java
...
...
public void sendNotification(String notification, Acknowledgment ack) {
ListenableFuture<SendResult<String, String>> future =
notificationKafkaTemplate.send(topicName, String);
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> result) {
handleNotificationSuccess();
ack.acknowledge();
}
@Override
public void onFailure(Throwable ex) {
handleNotificationFailure(ex);
}
});
}
public void handleNotificationSuccess() {
// handle notification success
}
public void handleNotificationFailure(Throwable ex) {
// handle notification failure
}
Please tell me if any more information is required. Thanks
EDIT 1:
I started implementing Seeking to a Specific Offset but encountered a problem. Here is the code:
@Component
public class KafkaConsumer implements ConsumerSeekAware {
private final ThreadLocal<ConsumerSeekCallback> seekCallBack = new ThreadLocal<>();
@KafkaListener(id = "workerListener", topics = "${kafka.topic.name}",
containerFactory = "workerKafkaListenerContainerFactory")
public void workerListener(ConsumerRecord<?,?> consumerRecord, Acknowledgment ack) {
this.seekCallBack().get().seek(consumerRecord.topic(), consumerRecord.partition(), 0);
// Now producer will send to another topic
kafkaProducer.sendNotification(notification, ack);
}
@Override
public void registerSeekCallback(ConsumerSeekCallback callback) {
this.seekCallBack.set(callback);
}
@Override
public void onPartitionsAssigned(Map<TopicPartition, Long> map, ConsumerSeekCallback csc) {
}
@Override
public void onIdleContainer(Map<TopicPartition, Long> map, ConsumerSeekCallback csc) {
}
}
I don't seem to understand what the problem is. Here is the stack trace:
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-12-04 23:15:18,670 ERROR o.s.b.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'kafkaConsumer' defined in class path resource [com/tgss/mdm/worker/consumer/kafkaods/config/AppConfig.class]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: @KafkaListener method 'workerListener' found on bean target class 'KafkaConsumer', but not found in any interface(s) for bean JDK proxy. Either pull the method up to an interface or switch to subclass (CGLIB) proxies by setting proxy-target-class/proxyTargetClass attribute to 'true'
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
at com.tgss.mdm.worker.consumer.kafkaods.KafkaApplication.main(KafkaApplication.java:10)
Caused by: java.lang.IllegalStateException: @KafkaListener method 'workerListener' found on bean target class 'KafkaConsumer', but not found in any interface(s) for bean JDK proxy. Either pull the method up to an interface or switch to subclass (CGLIB) proxies by setting proxy-target-class/proxyTargetClass attribute to 'true'
at org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.checkProxy(KafkaListenerAnnotationBeanPostProcessor.java:373)
at org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.processKafkaListener(KafkaListenerAnnotationBeanPostProcessor.java:341)
at org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.postProcessAfterInitialization(KafkaListenerAnnotationBeanPostProcessor.java:279)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
... 15 common frames omitted
Caused by: java.lang.NoSuchMethodException: com.sun.proxy.$Proxy79.workerListener(org.apache.kafka.clients.consumer.ConsumerRecord, org.springframework.kafka.support.Acknowledgment)
at java.lang.Class.getMethod(Class.java:1786)
at org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.checkProxy(KafkaListenerAnnotationBeanPostProcessor.java:358)
... 20 common frames omitted
A:
Caused by: java.lang.IllegalStateException: @KafkaListener method 'workerListener' found on bean target class 'KafkaConsumer', but not found in any interface(s) for bean JDK proxy. Either pull the method up to an interface or switch to subclass (CGLIB) proxies by setting proxy-target-class/proxyTargetClass attribute to 'true'
at org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.checkProxy(KafkaListenerAnnotationBeanPostProcessor.java:373)
at org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.processKafkaListener(KafkaListenerAnnotationBeanPostProcessor.java:341)
at org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.postProcessAfterInitialization(KafkaListenerAnnotationBeanPostProcessor.java:279)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
... 15 common frames omitted
Caused by: java.lang.NoSuchMethodException: com.sun.proxy.$Proxy79.workerListener(org.apache.kafka.clients.consumer.ConsumerRecord, org.springframework.kafka.support.Acknowledgment)
I would suggest to follow recommendations: or use CGLIB proxyTargetClass = true, or extract an interface with an appropriate method to let the JDK Proxy to work properly.
|
[
"scifi.stackexchange",
"0000053978.txt"
] | Q:
How could Smaug live buried under gold without breathing? (The desolation of Smaug: The film)
Before Smaug awakens because of Bilbo's ventures, there's not even a single breath amidst all the gold. His breath is only heard when he wakes up. Is he capable of living without breathing?
A:
In order of possibility:
Smaug does not need to breathe. He is a magical monster and his life processes do not resemble that of living beings. After all, he can breathe fire, fly AND speak intelligently. Of the magical origins of dragons little is actually known so they may not have the same requirements as non-magical creatures. Dragons violate so many of the natural laws of physics as to be certainly supernatural in and of themselves.
Smaug breathes, but while dormant under his gold may only breathe once in a given period which was shorter than Bilbo's initial visit. Like many serpents and reptiles, they are able to live for very long periods without any environmental resources. For example: The bushmaster viper may live an entire year on less than one meal per month.
Smaug breathes very quietly unless he wants to talk, interact, or breath fire. He may when in a hibernation state, need almost no natural resources, such as air, at all.
It has been suggested that possibly like an alligator, Smaug may lie below the gold for the most part but his nostrils may be camouflaged by the gold, and the gold may be loose enough to allow him to breathe quietly while at rest.
|
[
"stackoverflow",
"0042567704.txt"
] | Q:
TensorFlow: Not all of my variables are being restored - Python
I have another TensorFlow query:
I'm training a regression model, saving the weights and biases and then restoring them to rerun the model on a different data set. At least, that's what I'm trying to do. Not all of my weights are being restored. Here's the code used for saving my variables:
# Add ops to save and restore all the variables.
saver = tf.train.Saver({**weights, **biases})
# Save the variables to disk.
save_path = saver.save(sess, "Saved_Vars.ckpt")
And here's my entire code for restoring and running the model:
# Network Parameters
n_hidden_1 = 9
n_hidden_2 = 56
n_hidden_3 = 8
n_input = 9
n_classes = 1
# TensorFlow Graph Input
x = tf.placeholder("float", [None, n_input])
# Create Multilayer Model
def multilayer_perceptron(x, weights, biases):
# First hidden layer with RELU activation
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
layer_1 = tf.nn.relu(layer_1)
# Second hidden layer with RELU activation
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.relu(layer_2)
# Second hidden layer with RELU activation
layer_3 = tf.add(tf.matmul(layer_2, weights['h3']), biases['b3'])
layer_3 = tf.nn.relu(layer_3)
# Last output layer with linear activation
out_layer = tf.matmul(layer_3, weights['out']) + biases['out']
return out_layer
# weights and biases
weights = {
'h1': tf.Variable(tf.zeros([n_input, n_hidden_1])),
'h2': tf.Variable(tf.zeros([n_hidden_1, n_hidden_2])),
'h3': tf.Variable(tf.zeros([n_hidden_2, n_hidden_3])),
'out': tf.Variable(tf.zeros([n_hidden_3, n_classes]))
}
biases = {
'b1' : tf.Variable(tf.zeros([n_hidden_1])),
'b2': tf.Variable(tf.zeros([n_hidden_2])),
'b3': tf.Variable(tf.zeros([n_hidden_3])),
'out': tf.Variable(tf.zeros([n_classes]))
}
# Construct Model
pred = multilayer_perceptron(x, weights, biases)
pred = tf.transpose(pred)
# Initialize variables
init = tf.global_variables_initializer()
# RUNNING THE SESSION
# launch the session
sess = tf.InteractiveSession()
# Initialize all the variables
sess.run(init)
# Add ops to save and restore all the variables.
saver = tf.train.Saver({**weights, **biases})
# Restore variables from disk.
saver.restore(sess, "Saved_Vars.ckpt")
# Use the restored model to predict the target values
prediction = sess.run(pred, feed_dict={x:dataVar_scaled}) #pred.eval(feed_dict={x:X})
Now, here's what has me confused/frustrated/annoyed. From the weights I can restore 'h1', 'h2' and 'h3', but not 'out'. Why not 'out'? Is there anything that I'm doing wrong? Please can you spend a few minutes to help me?
Many thanks
I am running Python 3.5 and TensorFlow 0.12 directly on Windows 10 and I'm using Spyder IDE.
A:
It looks like you are over-writing one of the 'out' keys with this dictionary constructor:
{**weights, **biases}
For example:
weights = {'h1':1, 'h2':2, 'out':3}
biases = {'b1':4, 'b2':5, 'out':6}
print({**weights, **biases})
{'h2': 2, 'out': 6, 'b2': 5, 'b1': 4, 'h1': 1}
|
[
"ru.stackoverflow",
"0000271581.txt"
] | Q:
Добавление источника данных
При добавлении нового источника данных нельзя выбрать "модель EDM". Раньше можно было выбрать между набором данных и моделью EDM, а сейчас нет. Как можно добавить ее в источники данных сейчас? Использую VS 2013.
A:
В Visual Studio 2013 исключено расширение для работы с EDM =(
Остается пробовать через ADO.NET Entity Data Model.
|
[
"stackoverflow",
"0038647561.txt"
] | Q:
Swift - Cannot change UICollectionViewFlowLayout dynamically
On viewDidLoad I set a collectionViewLayout for a UICollectionViewCell with a UILabel saying "loading content...", when the apps fetchs the content from a server, it does something like this:
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
...
// some configuration for the layout
// here it crash:
collectionView.setCollectionViewLayout(layout, animated: true)
It crash with saying this message:
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(0x24479b0b 0x23c36dff 0x2438a6d3 0x29275999 0x29271d13 0x29272aaf 0x28be537f 0x28be4667 0x1778dc 0x165f48 0x1661b8 0x16e774 0x16f038 0xf950c 0xf9174 0xdefb0 0xe1934 0xdf98c 0x52ed78 0x52d700 0x52bfc8 0x4df9c0 0x1531ba7 0x1531b93 0x1536659 0x2443b755 0x24439c4f 0x243881c9 0x24387fbd 0x259a4af9 0x28ac0435 0x131254 0x24034873)
libc++abi.dylib: terminating with uncaught exception of type NSException
The things I did is set one collectionViewLayout replace that with another.
I tried to invalidate the layout with invalidateLayout() reloading or not reloading the collectionView before to replace the collectionViewLayout and it stills crashing.
What can I do to change the collectionViewLayout dynamically? or What am I doing wrong?
Thanks
A:
I hit the same issue for iOS9 and iOS8.
In my case, call collectionView.layoutIfNeeded() after collectionView.collectionViewLayout.invalidateLayout() to solve.
|
[
"ru.stackoverflow",
"0000341765.txt"
] | Q:
Перенос rar-файла на ftp: "Заголовок файла "???" повреждён"
Через бат файл архивирую и переношу файл на фтп, скачиваю его с фтп, пытаюсь открыть пишет: "Заголовок файла "???" повреждён". Открываю файл перед отправкой на фтп - все нормально. Куда копать?.bat :@EchoE:cd E:\Trade\Price\Opt\rar.exe a -o+ -r E:\Trade\Price\1.rar *.*ftp -s:E:\Admin\ftp2.txt//del E:\Trade\Price\1.rarexitftp2.txt :open ...70logpasscd /public_html/.../...send E:\Trade\Price\1.rarbye
A:
Оказывается в виндовс по умолчанию стоит режим передачи ASCII, с ним доходят поврежденные файлы (как минимум архивные), нужен двоичный режим и проблема решена. Вопрос закройте. Спасибо.open ...70logpasscd /public_html/.../...binarysend E:\Trade\Price\1.rarbye
|
[
"blender.stackexchange",
"0000041505.txt"
] | Q:
How can I parent a rig to another rig?
I have a rigged object that I'd like one of my characters, who is also rigged, to be holding even as his arms move. How can I attach this object to his hand?
A:
When animating a character they may need to pick up objects and move them around. The ChildOf constraint is useful for this. The advantage of using the ChildOf constraint is that you can animate the influence to allow the character to pick up and put down the object.
As you can specify an armature and bone to parent to you can also parent different object bones to different character bones, allowing you to have the character hold a piece in each hand and stretch them, or hold the doll body in one hand and lift the doll arm in the other.
|
[
"stackoverflow",
"0027553670.txt"
] | Q:
How to select sqlite order by char and number key?
Some value of col in sqlite database:
a1b2
a2b3
a1b10
a10b1
if use order by in sql it will be:
a10b1
a1b10
a1b2
a2b3
I want it like NSNumericSearch of objc like this:
a1b2
a1b10
a2b3
a10b1
How do I write the SQL statements?
A:
Start by creating a custom collating function:
int compare_natural(void *data, int len1, const void *str1, int len2, const void *str2) {
if (str1 && len1 > 0 && str2 && len2 > 0) {
NSString *s1 = [[NSString alloc] initWithBytesNoCopy:(void *)str1 length:len1 encoding:NSUTF8StringEncoding freeWhenDone:NO];
NSString *s2 = [[NSString alloc] initWithBytesNoCopy:(void *)str2 length:len2 encoding:NSUTF8StringEncoding freeWhenDone:NO];
// The use of NSNumericSearch is required for your need.
// The others are options depending on your needs
NSComparisonResult res = [s1 compare:s2 options:NSCaseInsensitiveSearch | NSNumericSearch | NSDiacriticInsensitiveSearch];
return res;
} else if (str1 && len1 > 0 && (!str2 || len2 == 0)) {
return -1; // empty strings to the end of the list (optional)
} else if (str2 && len2 > 0 && (!str1 || len1 == 0)) {
return 1; // empty strings to the end of the list (optional)
} else {
return 0;
}
}
Then register the custom collator. This needs to be done after you open the database.
// dbRef is your sqlite3 database reference
int rc = sqlite3_create_collation(dbRef, "BYNUMBER", SQLITE_UTF8, NULL, &compare_natural);
Then update your query so it ends with "COLLATE BYNUMBER"
SELECT some_col ORDER BY some_col COLLATE BYNUMBER;
|
[
"stackoverflow",
"0006691905.txt"
] | Q:
WPF Performance Problems with derived TextBox controls
I have a WPF application that renders input forms based on form-configurations saved in a database.
The forms have many controls (100+) and most of these controls are derived from a TextBox-control. On some machines (fast Hardware, Win7 32Bit, also some elder, Windows XP 32Bit), after entering data to a lot of these forms, input performance goes down. Every keystroke gets a delay of some milliseconds and the only solution to resolve this is to close the application and restart it.
My derived control overrides the metadata of the DefaultStyleKeyProperty to set a custom template.
I'm currently reasearching the app in SciTech memory profiler, but maybe someone has already experienced a similar problem with derived TextBoxes and can give me a hint and spare me some more hours/days investigating the problem?
Update
Look also here
A:
It sounds like you may have something stopping the controls on the "used forms" being GCed.
Firstly opening and use as many forms as possible looking at the windows task manager to see if you memory usage is going up – if it is not there is no point looking for memory leeks
Check you are removing all events handlers you forms/controls have put on any long lived objects.
Check that any objects you databind to implement INotifyPropertyChanged, see KB938416
I have in the past had good results using the Red Gate memory profiler.
|
[
"ethereum.meta.stackexchange",
"0000000265.txt"
] | Q:
What about adding multiple answers to a same question?
I recently noticed this post and found that there are many (4) answers from same guy.
IMHO he could have add all the answers in a single post. What do you think? Is this the right way?
PS: the answer with most up votes is a community-wiki.
A:
From the top voted answer on What is the official etiquette on answering a question twice? linked by @5chdn,
When you have two distinct answers.
It's better to post two different answers than to put them both into one answer.
Some questions will be multiple-answer types directly, like tips-and-tricks or best-practices. This allows the ones the community feels are the best/correct to float to the top.
Some computer languages have a lot of flexibility in how to solve any one problem, so by listing them both as separate answers (if very distinct) they can both be voted on by the community, and this will allow the better answer to float to the top. It also allows the comment threads to be more focused on each answer.
If you put two very different answers in one, then one could be a great answer, and one could be a terrible way to do things, but the upvotes (or downvotes) on the good (or bad) answer will drag the other along with it to the top (or bottom).
From the post referred to in this question - Common useful JavaScript snippets for geth - the answers are:
Answer 1 by @Nikhil M
Mine only when there are transactions!
Get some data from get without starting node.
View a Transaction
Print a Block Details
Check all Balances
Answer 2 by @BokkyPooBah - Script To Find Mined Blocks And Uncles + List Transactions
Answer 3 by @BokkyPooBah - Script To Find Transactions To/From An Account
Answer 4 by @BokkyPooBah - Script To Find Non-Zero Transaction Count In A Range Of Blocks
Answer 5 by @BokkyPooBah - Script To Get Account Balances And Including TheDAO Tokens
In my opinion, the scripts in Answers 2 to 5 provide different functionality, and it would be messy to include them all in one answer. This is different to the my answer in Where can I find some Solidity / Smart Contract source code examples? where the short links can be combined into one answer.
I'm happy to do whatever ESE advises regarding the posting of separate answers:
separate answers;
combine answers;
change all the separate answers into community wikis; or
stop posting new snippets to old questions.
|
[
"serverfault",
"0000151606.txt"
] | Q:
Why ethernet cables must be ended with specific arrangement
I just accepted that ethernet cables CAT 5 and more must be ended with specific arrangement.
I learned when I ending my cables to take attention that either end must be in same arrangement(568A or 568B ).
Sometime I get stacked with my fellow servant that they claim that Cable should work if just arrangement at both side are same even if it is not in 568A or 568B layouts.
My experience said that it is not true, but I am now looking for some technical argument to prove that.
A:
The number of twistings for each color pair in an Ethernet cable is different, and this helps avoiding crosstalk between them; an Ethernet cable can (and often will) work if you swap colors (as long as you do it consistently), but it will work better if you stick to the standards, especially on long distances and/or where there is a lot of electromagnetic noise.
http://en.wikipedia.org/wiki/Category_5_cable#Individual_twist_lengths
A:
If you have the same order of cables on both ends, it's a straight through cable. If you use A on one side and B on the other, it's a crossed cable (although the order is hardly random, obviously, but I suppose you knew that). The point is, the cables inside your UTP cable are nothing but copper, it doesn't matter what color the isolation is. The electrical signals passing through don't care about colors.
It will work just fine, but there is a standard in place to easily recognize what kind of cable you're dealing with and to make sure you don't mess up when making crossed cables. I'm sure there's more complicated reasons as well though, but the RFC or what not should help you out if you want to know more. :-)
EDIT: Massimo replied that it might in fact make a difference after all: the 4 pairs of cables are, according to him (I did not know this before and didn't doublecheck) twisted differently. This twisting makes sure the electromagnetical interference is reduced to a minimum (also the reason you want to make the untwisted part when making the cable as short as possible).
|
[
"anime.stackexchange",
"0000023021.txt"
] | Q:
Who enforces the rules that the gods must obey?
In episode 10, we learn that gods are forbidden from entering the dungeon. This is apparently against the rules.
But who enforces the rules? What happens to someone found in defiance of them? I mean, Hestia and co. are gods, after all.
A:
Based on episode 13 of the series, it seems like the dungeon itself enforces the rules. While having Hestia and Hermes in the search party didn't trigger any ill-effects on its own, Hestia's use of her godly powers within the dungeon resulted in a boss-level enemy along with multiple smaller mobs breaking into the sanctuary of level 18, and the characters' reactions suggested that this was the dungeon reacting to (and being upset at) the use of the power.
|
[
"salesforce.stackexchange",
"0000134304.txt"
] | Q:
Validating sObject fields in JavaScript Custom Button?
I have a button that should update a boolean field to true if certain conditions are met.
I want to do my validation in the JavaScript that fires on button click instead of letting the system run validation rules after the field has been set and then rolling back. My reasoning is justified by the annoyance of not receiving validation errors after using window.location.reload() utilizing JavaScript.
Can someone tell me specifically why I'd be receiving an undefined error for the custom field that I'm querying against a substring below?
Current_Project_Phase__c is a text field.
{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}
var currentProjectPhase = {!project_cloud__Project__c.Current_Project_Phase__c};
if (currentProjectPhase !== undefined)
{
if (currentProjectPhase.indexOf("Implementation") !== -1)
{
var projectUpdate = new sforce.SObject("project_cloud__Project__c");
projectUpdate.Id="{!project_cloud__Project__c.Id}";
projectUpdate.Submit_for_Change_Assessment__c = true;
if(projectUpdate != null)
{
try
{
sforce.connection.update([projectUpdate]);
window.location.reload();
}
catch(e)
{
alert("Error : " + e);
}
}
}
else
{
alert("You are currently not in the Implementation stage, change can not be triggered.");
}
}
else
{
alert("Current Project Phase undefined.");
}
The error I'm getting is shown below, FYI "Triage" is the value that's currently contained in the field Current_Project_Phase__c:
A:
Replace:
var currentProjectPhase = {!project_cloud__Project__c.Current_Project_Phase__c};
With:
var currentProjectPhase = "{!project_cloud__Project__c.Current_Project_Phase__c}";
Also:
if (currentProjectPhase !== undefined)
will never return false because once you declared 'var currentProjectPhase' it will never be 'undefined'. So replace it with:
if (currentProjectPhase !== '' || currentProjectPhase !== null)
|
[
"stackoverflow",
"0002618850.txt"
] | Q:
RegEx for a price in £
i have: \£\d+\.\d\d
should find: £6.95 £16.95 etc
+ is one or more
\. is the dot
\d is for a digit
am i wrong? :(
JavaScript for Greasemonkey
// ==UserScript==
// @name CurConvertor
// @namespace CurConvertor
// @description noam smadja
// @include http://www.zavvi.com/*
// ==/UserScript==
textNodes = document.evaluate(
"//text()",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
var searchRE = /\£[0-9]\+.[0-9][0-9];
var replace = 'pling';
for (var i=0;i<textNodes.snapshotLength;i++) {
var node = textNodes.snapshotItem(i);
node.data = node.data.replace(searchRE, replace);
}
when i change the regex to /Free for example it finds and changes. but i guess i am missing something!
A:
Had this written up for your last question just before it was deleted.
Here are the problems you're having with your GM script.
You're checking absolutely every
text node on the page for some
reason. This isn't causing it to
break but it's unnecessary and slow.
It would be better to look for text
nodes inside .price nodes and .rrp
.strike nodes instead.
When creating new regexp objects in
this way, backslashes must be
escaped, ex:
var searchRE = new
RegExp('\\d\\d','gi');
not
var
searchRE = new RegExp('\d\d','gi');
So you can add the backslashes, or
create your regex like this:
var
searchRE = /\d\d/gi;
Your actual regular expression is
only checking for numbers like
##ANYCHARACTER##, and will ignore £5.00 and £128.24
Your replacement needs to be either
a string or a callback function, not
a regular expression object.
Putting it all together
textNodes = document.evaluate(
"//p[contains(@class,'price')]/text() | //p[contains(@class,'rrp')]/span[contains(@class,'strike')]/text()",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
var searchRE = /£(\d+\.\d\d)/gi;
var replace = function(str,p1){return "₪" + ( (p1*5.67).toFixed(2) );}
for (var i=0,l=textNodes.snapshotLength;i<l;i++) {
var node = textNodes.snapshotItem(i);
node.data = node.data.replace(searchRE, replace);
}
Changes:
Xpath now includes only p.price and p.rrp span.strke nodes
Search regular expression created with /regex/ instead of new RegExp
Search variable now includes target currency symbol
Replace variable is now a function that replaces the currency symbol with a new symbol, and multiplies the first matched substring with substring * 5.67
for loop sets a variable to the snapshot length at the beginning of the loop, instead of checking textNodes.snapshotLength at the beginning of every loop.
Hope that helps!
[edit]Some of these points don't apply, as the original question changed a few times, but the final script is relevant, and the points may still be of interest to you for why your script was failing originally.
|
[
"stackoverflow",
"0038856157.txt"
] | Q:
A tool to pass struct to dbus method?
I've created a daemon. The daemon provides a dbus interface, with one of its methods having a signature like this (uu) -- that is a struct of two uint32 fields.
Is there a ready-to-use tool for me to invoke the method, to pass the struct in? dbus-send and d-feet doesn't seem to help.
Any pointers?
A:
gdbus should do the trick. Try the equivalent of:
gdbus call --session --dest com.example.MyTest --object-path /com/example/MyTest --method com.example.MyTest.Test "(1,2)"
... with the correct parameters for your situation of course.
I've tested the call above using a Python D-Bus service like this:
import gobject
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
OPATH = "/com/example/MyTest"
IFACE = "com.example.MyTest"
BUS_NAME = "com.example.MyTest"
class Example(dbus.service.Object):
def __init__(self):
bus = dbus.SessionBus()
bus.request_name(BUS_NAME)
bus_name = dbus.service.BusName(BUS_NAME, bus=bus)
dbus.service.Object.__init__(self, bus_name, OPATH)
@dbus.service.method(dbus_interface=IFACE,
in_signature="(uu)", out_signature="")
def Test(self, payload):
print "Got this from client:", payload
if __name__ == "__main__":
service = Example()
loop = gobject.MainLoop()
loop.run()
On the Ubuntu 15.10 machine I'm on gdbus is provided by the libglib2.0-bin package:
$ dpkg -L libglib2.0-bin | grep gdbus
/usr/bin/gdbus
/usr/share/bash-completion/completions/gdbus
/usr/share/man/man1/gdbus.1.gz
Hope this helps.
|
[
"stackoverflow",
"0023001408.txt"
] | Q:
perl Regular expression matching repeating words
a regular expression that matches any line of input that has the same word repeated
two or more times consecutively in a row. Assume there is one space between consecutive
words
if($line!~m/(\b(\w+)\b\s){2,}/{print"No match\n";}
{ print "$`"; #print out first part of string
print "<$&>"; #highlight the matching part
print "$'"; #print out the rest
}
This is best i got so far,but there is something wrong
correct me if i am wrong
\b start with a word boundary
(\w+) followed by one word or more words
\bend with a word boundary
\s then a space
{2,} check if this thing repeat 2 or more times
what's wrong with my expression
A:
This should be what you're looking for: (?:\b(\w+)\b) (?:\1(?: |$))+
Also, don't use \s when you're just looking for spaces as it's possible you'll match a newline or some other whitespace character. Simple spaces aren't delimiters or special characters in regex, so it's fine to just type the space. You can use [ ] if you want it to be more visually apparent.
|
[
"stackoverflow",
"0044829852.txt"
] | Q:
(Redefinition error) Create multiple inherting classes from one baseclass in C++
Greetings oh mighty coders,
I am a beginner and in a bit of trouble here.
There is my baseclass (sensor.h):
class sensor
{
private:
int sensor_id;
string sensor_name;
string sensor_type;
float reading;
public:
sensor();
sensor(int, char*, char*);
~sensor();
/* Few extra methods here */
};
... and I want to create 4 other classes that inherit from my baseclass sensor
(temperaturesensor, humiditysensor... and so on).
#include "sensor.h"
class temperaturesensor:public sensor
{
public:
Temperatursensor(int, char*,char*);
~Temperatursensor();
/* Few extra methods here */
};
Thing is: Every single one of these classes has to be in its own .cpp/.h file and then be included and used in my main.cpp.
using namespace std;
#include <xyz.h>
/* Other libaries here */
....
#include "temperaturesensor.h"
#include "humiditysensor.h"
int main()
{
sensor* station[2];
station [0] = new temperaturesensor(x,y,z);
station [1] = new humiditysensor(x,y,z);
}
If I include one of them it's no biggie. However: If I use multiple ones I get an redefinition error.
error C2011: 'sensor': 'class' typeredefinition
c:\users\name\desktop\project\sensor.h 14
error c2011: 'temperaturesensor' : 'class' typeredefinition
What can I do to workaround this? Note that I am not allowed to use #pragma once
Sorry for my stupidity and thanks in advance!
A:
You must use:
#ifndef FILE_H
#define FILE_H
.. normal code here
#endif
or
#pragma once
but too, I think, that sensor schould be abstract class and you schould use virtual destructor.
One more think is that array is numerate from 0.
|
[
"stackoverflow",
"0021640579.txt"
] | Q:
How to encode EOL-CR/LF in Delphi XE on Win 7 64 for MS NotePad?
I am using Delphi XE with Indy 10 SMTP client (TIdSMTP) - on a Win 7 64 machine. I'm generating a simple text file report that is sent as an email attachment with the *.txt extension. Users will normally be viewing the report attachment with MS Win Notepad.exe, the default Win 7 text editor (That cannot/will not change).
As always, I used #13+#10 in this project to represent CR/LF in Delphi strings. Never had a problem with it (although I never had to use it in Notepad AFAIK.)
But I found that the #13+#10 - CR/LF is ignored in Notepad.exe - as if it's not there, although the EOL in the attachment is recognized and rendered properly in every other editor I have around, Including NotePad++, MS Write, MS Word, Delphi, EditPad, etc. etc... I know there are problems with Notepad.exe dealing with CR alone or LF alone but I thought CR/LF always worked - but it isn't working here.
What am I doing wrong? Is this a unicode or 64 bit issue? How/what do I have to embed in my string in Delphi XE on Win7 64 platform, so that Notepad.exe will recognize and render properly EOL - CR/LF.
Relevant code as per Remy's comment:
const
EOL = #13+#10;
EMAIL_TITLE2 = 'Value expressed in $ 000''s' + EOL;
REPORT_NAME='Report';
var
list: TStringList;
s: string;
...
begin
...
list.Add (EMAIL_TITLE2)
... add more text lines + EOL;
s := list.Text;
Attachment := TIdAttachmentMemory.Create(msg.MessageParts, s);
Attachment.FileName := REPORT_NAME + '.txt';
smtpClient.Send(msg);
A:
Indy has its own EOL constant for #13#10, so you do not need to declare your own constant.
Do not include line breaks when adding a string to the TStringList. Let Add() handle the line break for you. If you need to Add() a string with line breaks in it, split the string first and Add() the pieces. And if your code is running on a non-Windows system, use the TStringList.LineBreak property to specify #13#10 as the line break used when outputting text, otherwise a platform-specific default is used instead.
Something else to watch out for is that TIdAttachmentMemory will encode a string using Indy's default charset, which is set to ASCII by default. So if you are sending text with non-ASCII characters in it, use TStringList.SaveToStream() so you can specify whatever encoding you want, such as UTF-8, and then have TIdAttachmentMemory send that TStream data instead of the original string. You can either save the TStringList to your own TStream, such as a TMemoryStream or TStringStream, and pass that to the TIdAttachmentMemory constructor, or you can use the TIdAttachmentMemory.PrepareTempStream() method to get a TStream owned by TIdAttachmentMemory that you can write data to.
Try this:
const
EMAIL_TITLE2 = 'Value expressed in $ 000''s';
var
list: TStringList;
strm: TStream;
...
begin
...
list.LineBreak := #13#10;
...
list.Add (EMAIL_TITLE2);
... add more text lines
Attachment := TIdAttachmentMemory.Create(msg.MessageParts);
Attachment.ContentType := 'text/plain';
Attachment.CharSet := 'utf-8';
Attachment.FileName := ReportName + '.txt';
strm := Attachment.PrepareTempStream;
try
list.SaveToStream(strm, TEncoding.UTF8);
finally
Attachment.FinishTempStream;
end;
smtpClient.Send(msg);
|
[
"stackoverflow",
"0028154096.txt"
] | Q:
SQL check time difference hours between record and dateTime now
I need to add to this query an additional "AND" to check if the time between two records is at least 2 hours. This is the original query:
SELECT COUNT(Viewed) FROM [Views] WHERE userIP = @userIP AND MessageID=@MessageID
I tried adding a second AND like this:
SELECT COUNT(Viewed) FROM [Views] WHERE userIP = @userIP
AND MessageID=@MessageID
AND (@Now - dateTime)>2
and also like this:
SELECT COUNT(Viewed) FROM [Views] WHERE userIP = @userIP
AND MessageID=@MessageID
AND DATEDIFF(HOUR, @Now, dateTime)>2
@Now = datetime now, (2015-01-26 09:08:28.183)
dateTime= the datetime in the table of the posted record (2015-01-25 11:06:15.001
But I am not getting the result. How to do this?
A:
Try this;
DATEDIFF(SECOND, [dateTime], @Now) > (2 * 60 * 60)
This assumes your [dateTime] values are all in the past. If they could be in the future too then wrap it in ABS().
|
[
"stackoverflow",
"0055224718.txt"
] | Q:
SQLSTATE[22023]: Invalid parameter value: 3037 Invalid GIS data provided to function mbrcontains
(Hi !)
I'm not very good at SQL and I didn't find any solution on internet, I have the following error (with Symfony4)
SQLSTATE[22023]: Invalid parameter value: 3037 Invalid GIS data provided to function mbrcontains.
My request is here :
$sql = '
SELECT * FROM rent_release r
WHERE CONTAINS("date", :yearRequested)
';
date is defined later because it's how it works with doctrine:
$stmt->execute(['yearRequested' => $year]);
Does anyone know what's the problem ?
A:
Someone helped me on Symfony slack
SELECT * FROM rent_release r WHERE YEAR(`date`) = :yearRequested
|
[
"stackoverflow",
"0008273745.txt"
] | Q:
Does .NET have a simple way to do overflow lists?
I'm looking to add a "recently opened" functionality to my application, and was wondering if there was a simple built in way to do lists that "overflow". By this I mean, when you add an element beyond the capacity of the list, all the items are shifted.
Code example of desired functionality (obviously its not true, the list would actually contain A,B,C):
List<string> list = new List<string>();
//if Overflow was 2
list.Add("A");
list.Add("B");
//List now contains A,B
list.Add("C");
//List now contains B,C
Sorry for the simple question. The problem itself is obvious to solve (intail plan was to inherit from List), I just don't like having to re-invent the wheel and confuse future programmers with custom objects when the language or framework has that functionality.
A:
As far as I know ther is no such collection in the library.
You can write this very easily, based on a List<> or an array.
// untested
class OverFlowList<T>
{
T[] _data;
int _next = 0;
public OferflowList(int limit)
{
_data = new T[limit];
}
void Add(T item)
{
_data[_next] = item;
_next = (_next + 1) % _data.Length;
}
}
A:
You can do this easily with LinkedList<T>:
LinkedList<string> list = new LinkedList<string>();
//if Overflow was 2
list.AddFirst("A");
list.AddFirst("B");
list.AddFirst("C");
list.RemoveLast();
I would, personally, wrap this into a class that you could use, ie:
public class OverflowCollection<T> : IEnumerable<T>
{
private int max;
private LinkedList<T> list = new LinkedList<T>();
public OverflowCollection(int maxItems)
{
this.max = maxItems;
}
public void Add(T item)
{
this.list.AddFirst(item);
if (this.list.Count > max)
this.list.RemoveLast();
}
// Implement IEnumerable<T> by returning list's enumerator...
}
This provides a very simple method, which has some nice advantages, including being able to change the overload amount at runtime, etc..
|
[
"stackoverflow",
"0039067373.txt"
] | Q:
JDBC and Multithreading
I am trying to run few queries using a multithreaded approach, however I think I am doing something wrong because my program takes about five minute to run a simple select statement like
SELECT * FROM TABLE WHERE ID = 123'
My implementation is below and I am using one connection object.
In my run method
public void run() {
runQuery(conn, query);
}
runQuery method
public void runQuery(Connection conn, String queryString){
Statement statement;
try {
statement = conn.createStatement();
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {}
} catch (SQLException e) {
e.printStackTrace();
}
}
Finally in the main method, I start the threads using the snippet below.
MyThread bmthread = new MyThread(conn, query);
ArrayList<Thread> allThreads = new ArrayList<>();
double start = System.currentTimeMillis();
int numberOfThreads = 1;
for(int i=0; i<=numberOfThreads; i++){
Thread th = new Thread(bmthread);
th.setName("Thread "+i);
System.out.println("Starting Worker "+th.getName());
th.start();
allThreads.add(th);
}
for(Thread t : allThreads){
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
double end = System.currentTimeMillis();
double total = end - start;
System.out.println("Time taken to run threads "+ total);
Update : I am now using separate connection for each thread.
ArrayList<Connection> sqlConn = new ArrayList<>();
for(int i =0; i<10; i++){
sqlConn.add(_ut.initiateConnection(windowsAuthURL, driver));
}
loop:
MyThread bmthread = new MyThread(sqlConn.get(i), query);
A:
As rohivats and Asaph said, one connection must be used by one and only one thread, that said, consider using a database connection pool. Taking into account that c3p0 and similars are almost abandoned, I would use HirakiCP which is really fast and reliable.
If you want something very simple you could implement a really simple connection pool using a thread safe collection (such as LinkedList), for example:
public class CutrePool{
String connString;
String user;
String pwd;
static final int INITIAL_CAPACITY = 50;
LinkedList<Connection> pool = new LinkedList<Connection>();
public String getConnString() {
return connString;
}
public String getPwd() {
return pwd;
}
public String getUser() {
return user;
}
public CutrePool(String connString, String user, String pwd) throws SQLException {
this.connString = connString;
for (int i = 0; i < INITIAL_CAPACITY; i++) {
pool.add(DriverManager.getConnection(connString, user, pwd));
}
this.user = user;
this.pwd = pwd;
}
public synchronized Connection getConnection() throws SQLException {
if (pool.isEmpty()) {
pool.add(DriverManager.getConnection(connString, user, pwd));
}
return pool.pop();
}
public synchronized void returnConnection(Connection connection) {
pool.push(connection);
}
}
As you can see getConnection and returnConnection methods are synchronized to be thread safe. Get a connection (conn = pool.getConnection();) and don't forget to return/free a connection after being used (pool.returnConnection(conn);)
|
[
"serverfault",
"0000269833.txt"
] | Q:
Ideal server specs/software for mail, file, and database storage
I'm trying to figure out what the ideal set up would for a few servers.
1) Website
1) Mail server
1) Database server
1) file server
In this given scenario, say there is a site that will offer each user 5gb of file storage space along with an e-mail and a dedicated database.
From my somewhat limited understanding of how servers work I concluded that having 1 server per feature would be the best bet so that if one goes off line the other data isn't affected.
What would be a smart and efficient way to handle this?
This is my understanding
1) The website is hosted from 1 main server that will handle user registrations and serve small files. For this I think a simple server set up is more than enough right?
2) For a mail server, to handle the equal amount of registered users., will primarily handle the e-mails and e-mail attachments
3) The database would not be capped in size and only store each clients contacts and profile settings, so every time the user logs in the settings will be pulled from the database. I plan on loading the settings into $_SESSIONs so that the database won't be queried everytime the page reloads etc. But the Contact informations will be queried from the server on every action.
4) the file server will just serve files nothing to cpu or memory intensive
As far as software goes, I was leaning towards CentOs 5.5 and Plesk 10.2 to handle the website server and MySQL 5 for the database servers, maybe Atmail for the mail server. What is recommended on the software side to be loaded on each of those servers?
I have no experience in this field, but i'm gaining some everyday. I need to be intelligently informed so that i atleast know what i'm dealing with in the event that I hire someone to handle the setups for me.
In your experience guys, what would be an ideal set up with both hardware and software configurations?
Also, take in account an example user base of 5,000 clients. So each with 5gb of webspace, email, and own database.
A:
This is a fairly broad design issue, and is pretty complex. Each of these components involves its own significant design considerations. The level you've presented it is at a pretty abstract level, so the best we can provide are pretty abstract answers.
One server per service will provide better service than co-hosting services to some extent.
File-servers do indeed tend to be very light on CPU usage (even if the file-server is Windows).
5K users at 5GB average space usage is 25TB, which is a significant amount of storage. Plan for that.
At 5K users, multiple servers might be needed for some services, depending on application loading. Plan for that from the start.
As for your follow-on questions about software and OS selection, this is a drill-down that many of us here on ServerFault have had to do in our careers. However, every one of us who has done it knows very well that a correct answer here requires vastly more data than has been provided. Or even is able to be provided in a form like a ServerFault question because it is fundamentally complex, and there are a lot of variables to consider.
To answer those questions, you'll also need to have data or answers on the following issues and topics:
A strong feel for user workflow in the entire environment.
How well the system behaves under high load.
Once load starts saturating parts of your infrastructure, how does it impact the user experience?
What kinds of events cause high load?
Morning logon?
Evening home-from-work logon?
Special events driving load?
How well the system scales.
How easy is it to add servers to parts of the workflow?
How easy is it to add web-servers?
How easy is it to add database servers?
And a whole bunch of other things. These are the kinds of things that you learn by working closely with the development process and early-adopter tests. It's an iterative process, and not the kind of thing you can just plop a proposal down on a whiteboard and get a well functioning infrastructure out of it.
|
[
"stackoverflow",
"0007416524.txt"
] | Q:
PIVOT in SQLIte
I'd like to get a table which shows parameters and values they receive for all of their parametervalues in one query.
This is my table structure:
tbl_parameter
parameterid
parametername
tbl_parametervalues
parameterid
parametervalue
Actual Structure in tbl_parameter
--------------------------------
----------------------------------
| parameterid | parametername |
|----------------------------
| TYPE | Type |
| TEMP | Temp(Deg.C) |
| TIME | Time |
| DATE | Date |
| TECHNICIAN | Technician |
| TESTLENGTH | Test Length |
| TESTRESULT | Test Result |
-----------------------------------
Actual Structure in tbl_parametervalues
------------------------------------
| parameterid | parametervalue |
|----------------------------
| TYPE | DW1 |
| TEMP | 21 |
| TIME | 10:45 PM |
| DATE | 14/09/2011 |
| TECHNICIAN | Test1 |
| TESTLENGTH | 12 |
| TESTRESULT | Pass |
| TYPE | DW2 |
| TEMP | 22 |
| TIME | 11:45 PM |
| DATE | 15/09/2011 |
| TECHNICIAN | Test2 |
| TESTLENGTH | 12 |
| TESTRESULT | Pass
-----------------------------------
I want the result set to look like this:
-----------------------------------------------------------------------------
| SL NO | Type | Temp | Time | Date | Technician | Test |Test |
| | Length |Result |
---------------------------------------------------------------------------
| 1 | DW1 | 21 |10:45 PM|14/09/2011| Test1 | 12 | Pass |
| 2 | DW2 | 22 |11.45 | 15/09/2011| Test2 | 12 | Pass |
|------------------------------------------------------------------------------
How can I accomplish this in SQLite?
A:
I could not find a definition of how to detect sets of parameter values, i.e. which "TEMP" belongs to which "TYPE". So I assume that the sets of parameter values are always entered into the database consecutively and in the order given in the question. The comment by OP seems to allow this assumption. It is not very complicated (though a little) to immplement some robustness against shuffled orders (by associating via a detour by the parameterids), but I hope it is not necessary.
I also could not find information of what "SL NO" means and where the value is coming from. So I fake it by dividing the rowid of the TESTRESULT value by 7 (the number of different parameter names, which I consider to be the size of a parameter set). It should not be hard to dig the correct values up from your database. It is not required that the rowids are on multiples of 7, as long as the parameters are entered consecutively. Just the "SL NO" might skip a few numbers, if the rowids of e.g. "TYPE" are multiples of e.g. 8, otherwise the query tolerates gaps between parameter sets.
You can find the non-query part of my MCVE at the end of this answer.
Query:
select
'SL NO',
TYPE.parametername,
TEMP.parametername,
TIME.parametername,
DATE.parametername,
TECHNICIAN.parametername,
TESTLENGTH.parametername,
TESTRESULT.parametername
from
parameter TYPE,
parameter TEMP,
parameter TIME,
parameter DATE,
parameter TECHNICIAN,
parameter TESTLENGTH,
parameter TESTRESULT
where TYPE.parameterid='TYPE'
and TEMP.rowid=TYPE.rowid+1
and TIME.rowid=TYPE.rowid+2
and DATE.rowid=TYPE.rowid+3
and TECHNICIAN.rowid=TYPE.rowid+4
and TESTLENGTH.rowid=TYPE.rowid+5
and TESTRESULT.rowid=TYPE.rowid+6
UNION ALL
select
TESTRESULT.rowid/7,
TYPE.parametervalue,
TEMP.parametervalue,
TIME.parametervalue,
DATE.parametervalue,
TECHNICIAN.parametervalue,
TESTLENGTH.parametervalue,
TESTRESULT.parametervalue
from
parametervalues TYPE,
parametervalues TEMP,
parametervalues TIME,
parametervalues DATE,
parametervalues TECHNICIAN,
parametervalues TESTLENGTH,
parametervalues TESTRESULT
where TYPE.parameterid='TYPE'
and TEMP.rowid=TYPE.rowid+1
and TIME.rowid=TYPE.rowid+2
and DATE.rowid=TYPE.rowid+3
and TECHNICIAN.rowid=TYPE.rowid+4
and TESTLENGTH.rowid=TYPE.rowid+5
and TESTRESULT.rowid=TYPE.rowid+6
;
make one table on the fly for each pivot column
select from each of those tables the entry for one column
associate entries for the same line via assumptions (as stated above) on rowids
Output:
SL NO Type Temp(Deg.C) Time Date Technician Test Length Test Result
1 DW1 21 10:45 PM 14/09/2011 Test1 12 Pass
2 DW2 22 11.45 15/09/2011 Test2 12 Pass
MCVE (.dump):
BEGIN TRANSACTION;
CREATE TABLE parametervalues(parameterid varchar(30), parametervalue varchar(30) );
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TYPE','DW1');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TEMP','21');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TIME','10:45 PM');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('DATE','14/09/2011');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TECHNICIAN','Test1');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TESTLENGTH','12');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TESTRESULT','Pass');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TYPE','DW2');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TEMP','22');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TIME','11.45');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('DATE',' 15/09/2011');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TECHNICIAN','Test2');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TESTLENGTH','12');
INSERT INTO parametervalues(parameterid,parametervalue) VALUES('TESTRESULT','Pass');
CREATE TABLE parameter (parameterid varchar(30), parametername varchar(30));
INSERT INTO parameter(parameterid,parametername) VALUES('TYPE','Type');
INSERT INTO parameter(parameterid,parametername) VALUES('TEMP','Temp(Deg.C)');
INSERT INTO parameter(parameterid,parametername) VALUES('TIME','Time');
INSERT INTO parameter(parameterid,parametername) VALUES('TATE','Date');
INSERT INTO parameter(parameterid,parametername) VALUES('TECHNICIAN','Technician');
INSERT INTO parameter(parameterid,parametername) VALUES('TESTLENGTH','Test Length');
INSERT INTO parameter(parameterid,parametername) VALUES('TESTRESULT','Test Result');
COMMIT;
Note1:
I skipped the line breaks for the headers of the "Test *" parameter names. That seems irrelevant.
Note2:
My MCVE contains values to match the desired output, not always identical to the sample input. If the values are taken from sample input, the output looks different - and more convincing. It is not important which side of the inconsistence is correct and which is the typo. I chose to implement the version which requires more flexibility.
|
[
"stackoverflow",
"0013003886.txt"
] | Q:
File Stream problems
In 2010 Visual C++ Express, I'm using
...
ifstream inFile("inputfile.dat");
double number;
while(inFile >> number)
{
cout << number << endl;
}
...to read 8 numbers stored in a file into the program, and show them on the monitor. It shows them all correctly and as needed, but I need to store each individual number as already specified doubles. From top to bottom,
Customer 1's Identification #
Balance
Payments outstanding
Purchases that have been made
then the other 4 numbers are the same thing just for a different customer. I've tried a ton of different ways to do it, but each come with:
"Run-Time Check Failure #3 - The variable 'variableName' is
being used without being initialized."
and it happens with almost all of the variables. I've searched for anything to help me with this but couldn't seem to find something that would help me to the extent of what I needed.
A:
Assuming that you really want to store these in 8 distinct variables, and not in some aggregate data type:
std::ifstream inFile("inputfile.dat");
double number;
if(inFile >> cust1id >> cust1bal >> cust1pay >> cust1purch >>
cust2id >> cust2bal >> cust2pay >> cust2purch) {
std::cout <<
"Customer 1's Identification #: " << cust1id << "\n" <<
"Balance: " < cust1bal << "\n" <<
"Payments outstanding: " << cust1pay << "\n" <<
"Purchases that have been made: " << cust1purch <<
"Customer 2's Identification #: " << cust2id << "\n" <<
"Balance: " < cust2bal << "\n" <<
"Payments outstanding: " << cust2pay << "\n" <<
"Purchases that have been made: " << cust2purch << "\n";
}
|
[
"stackoverflow",
"0005564315.txt"
] | Q:
Problem with cusom Dialog for ProgressDialog
I have a LoginDialog called from Activity. In LoginDialog I am trying to open another Dialog (mProgressDlg) to indicate the progress. In mProgressDlg layout I have 2 TextView. I get NullPointerException on setText() of any of those TextView.
LoginDialog :
private Dialog mProgressDlg;
private TextView mMessage, mprogTitle, mProgMessage;
public LoginDialog(Context context) {
super(context);
mContext = context;
ld = null;
init();
}
private void init() {
this.setContentView(R.layout.user_pass_dialog);
mMessage = (TextView) findViewById(R.id.messageText);
mMessage.setText("Loaded ");
// ProgressDialog
mProgressDlg = new Dialog(mContext);
mProgressDlg.setContentView(R.layout.progress_dialog);
mProgTitle = (TextView) findViewById(R.id.titleText_progressDlg);
mProgMessage = (TextView) findViewById(R.id.message_progressDlg);
// On below 2 lines, I get NPE.
mProgTitle.setText("Hello");
mProgMessage.setText("Good Day");
}
progressDialog.xml
<TextView android:id="@+id/titleText_progressDlg" android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginTop="10dp" android:textStyle="bold"></TextView>
<TextView android:id="@+id/message_progressDlg" android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginTop="10dp"></TextView>
LogCat :
04-06 14:54:29.087: ERROR/AndroidRuntime(379): Caused by: java.lang.NullPointerException
04-06 14:54:29.087: ERROR/AndroidRuntime(379): at orange.android.vpn.LoginDialog.init(LoginDialog.java:88) ***// THIS IS mProgTitle.setText("Hello");***
04-06 14:54:29.087: ERROR/AndroidRuntime(379): at orange.android.vpn.LoginDialog.<init>(LoginDialog.java:50) ***// THIS IS CALLING init() FROM CONSTRUCTOR***
Can anyone help me know, why am I getting this NullPointerException in init() while accessing mProgTitle and/or mProgMessage. Any help is highly appreciated.
Thanks
A:
mProgressDlg.setContentView(R.layout.progress_dialog);
mProgTitle = (TextView) findViewById(R.id.titleText_progressDlg);
should be
mProgressDlg.setContentView(R.layout.progress_dialog);
mProgTitle = (TextView) mProgressDlg.findViewById(R.id.titleText_progressDlg);
because you are accessing components in the dialog layout. just findViewById is used in as a function in activity because you: with setContentView({layout}) you set activity's layout and access components with findViewById, the same for dialog you type dialog.setContentView and you access components the samo diloag.findViewById
|
[
"stackoverflow",
"0053456462.txt"
] | Q:
Hazelcast Map Expire Listener on key, race condition
I have IMap<Long, SomeObject> on hazelcast member,
where some part of Long keys have expiration time (TTL).
For this purpose I am registering EntryExpiredListener on key using addEntryListener(MapListener, K, boolean).
Everything works fine, but I have doubts.
As documentation states:
With the above approach, there is the possibility of missing events between the creation of the instance and registering the listener. To overcome this race condition, Hazelcast allows you to register listeners in configuration.
Will I encounter 'missing events' described above, if I register EntryExpiredListener on key?
A:
If it’s on the member & you mark the listener as local ( so each member receive only local expration events) and define in the config, you wont since events will be local to each member.
If you register the listener after you create the instance, after partitions distributed & before you register the listener, its possible that some data could expire. This is why above statements says you need to define listener in the config to prevent this.
|
[
"stackoverflow",
"0005187384.txt"
] | Q:
Rails 3 - Sorting Issues
I'm trying to sort a model of mine in a view by a value that's not stored in my db but is a model method.
My Articles of a score method, that is basically just the article comments + votes_for from vote_fu. In my controller, my articles are assigned like so:
@articles = @topic.articles
@articles.sort! { |article| article.score }
But yet, when viewing my page, the articles seem to be displayed randomly on the page. In my article.rb model, score is defined as:
def score
self.comments.count + self.votes_for
end
Anyway, I have no pagination or anything of the like, it's a pretty basic app. Just wondering if anyone could give me some pointers on what I'm doing wrong trying to sort this way.
A:
You need to use .sort_by for this.
@articles = @articles.sort_by { |article| article.score }
|
[
"stackoverflow",
"0052696493.txt"
] | Q:
PIE CHART - Data Visualization With DataTables and Highcharts
I'm binding all my data in the table to a graph chart and would like to add a pie chart..
How do I add my array of data to the pie chart like it is done for the chart?
I'm trying to show a pie chart that displays countries and their populations?
Thank you!
This will put me on a good path to create more pie charts on my own
Here is my attempted code below:
var draw = false;
init();
/**
* FUNCTIONS
*/
function init() {
// initialize DataTables
var table = $("#table").DataTable();
// get table data
var tableData = getTableData(table);
// create Highcharts
createHighcharts(tableData);
// table events
setTableEvents(table);
}
function getTableData(table) {
var dataArray = [],
countryArray = [],
populationArray = [],
densityArray = [];
ageArray = [];
// loop table rows
table.rows({
search: "applied"
}).every(function() {
var data = this.data();
countryArray.push(data[0]);
populationArray.push(parseInt(data[1].replace(/\,/g, "")));
densityArray.push(parseInt(data[2].replace(/\,/g, "")));
ageArray.push(parseInt(data[3].replace(/\,/g, "")));
});
// store all data in dataArray
dataArray.push(countryArray, populationArray, densityArray, ageArray);
return dataArray;
}
function createHighcharts(data) {
Highcharts.setOptions({
lang: {
thousandsSep: ","
}
});
Highcharts.chart("chart", {
title: {
text: "Data Chart"
},
subtitle: {
text: "fsvfsvvs svsdv"
},
xAxis: [{
categories: data[0],
labels: {
rotation: -45
}
}],
yAxis: [{
// first yaxis
title: {
text: "Population (2017)"
}
},
{
// secondary yaxis
title: {
text: "Density (P/Km²)"
},
min: 0,
opposite: true
}
],
series: [{
name: "Population (2017)",
color: "#0071A7",
type: "column",
data: data[1],
tooltip: {
valueSuffix: " M"
}
},
{
name: "Med Age",
color: "#68cc72",
type: "spline",
data: data[3]
// ,
// tooltip: {
// valueSuffix: " M"
// }
},
{
name: "Density (P/Km²)",
color: "#FF404E",
type: "spline",
data: data[2],
yAxis: 1
}
],
tooltip: {
shared: true
},
legend: {
backgroundColor: "#ececec",
shadow: true
},
credits: {
enabled: false
},
noData: {
style: {
fontSize: "16px"
}
}
});
Highcharts.chart('pie', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Report Pie Chart'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: 'PErcentage',
colorByPoint: true,
data: [data[2]],
}, {
name: 'PErcentage',
colorByPoint: true,
data: [data[1]],
},
{
name: 'PErcentage',
colorByPoint: true,
data: [data[3]],
}
]
});
}
function setTableEvents(table) {
// listen for page clicks
table.on("page", function() {
draw = true;
});
// listen for updates and adjust the chart accordingly
table.on("draw", function() {
if (draw) {
draw = false;
} else {
var tableData = getTableData(table);
createHighcharts(tableData);
}
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Reports</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/no-data-to-display.js"></script>
</head>
<body>
<div class="container">
<h1>Reports</h1>
<hr>
<div class="container">
<div class="row">
<div class="col-sm-12">
<table id="table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Country</th>
<th>Population (2017)</th>
<th>Density (P/Km²)</th>
<th>Med. Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>China</td>
<td>1,409,517,397</td>
<td>150 </td>
<td>37</td>
</tr>
<tr>
<td>India</td>
<td>1,339,180,127</td>
<td>450</td>
<td>27</td>
</tr>
<tr>
<td>U.S.</td>
<td>324,459,463</td>
<td>35</td>
<td>38</td>
</tr>
<tr>
<td>Indonesia</td>
<td>263,991,379</td>
<td>146</td>
<td>28</td>
</tr>
<tr>
<td>Brazil</td>
<td>209,288,278</td>
<td>25</td>
<td>31</td>
</tr>
<tr>
<td>Pakistan</td>
<td>197,015,955</td>
<td>256</td>
<td>22</td>
</tr>
<tr>
<td>Nigeria</td>
<td>190,886,311</td>
<td>210</td>
<td>18</td>
</tr>
<tr>
<td>Bangladesh</td>
<td>164,669,751</td>
<td>1,265</td>
<td>26</td>
</tr>
<tr>
<td>Russia</td>
<td>143,989,754</td>
<td>9</td>
<td>39</td>
</tr>
<tr>
<td>Mexico</td>
<td>129,163,276</td>
<td>66</td>
<td>28</td>
</tr>
<tr>
<td>Japan</td>
<td>127,484,450</td>
<td>350</td>
<td>46</td>
</tr>
<tr>
<td>Ethiopia</td>
<td>104,957,438</td>
<td>105</td>
<td>19</td>
</tr>
<tr>
<td>Philippines</td>
<td>104,918,090</td>
<td>352</td>
<td>24</td>
</tr>
<tr>
<td>Egypt</td>
<td>97,553,151</td>
<td>98</td>
<td>25</td>
</tr>
<tr>
<td>Viet Nam</td>
<td>95,540,800</td>
<td>308</td>
<td>30</td>
</tr>
<tr>
<td>Germany</td>
<td>82,114,224</td>
<td>236</td>
<td>46</td>
</tr>
<tr>
<td>DR Congo</td>
<td>81,339,988</td>
<td>36</td>
<td>17</td>
</tr>
<tr>
<td>Iran</td>
<td>81,162,788</td>
<td>50</td>
<td>30</td>
</tr>
<tr>
<td>Turkey</td>
<td>80,745,020</td>
<td>105</td>
<td>30</td>
</tr>
<tr>
<td>Thailand</td>
<td>69,037,513</td>
<td>135</td>
<td>38</td>
</tr>
<tr>
<td>U.K.</td>
<td>66,181,585</td>
<td>274</td>
<td>40</td>
</tr>
<tr>
<td>France</td>
<td>64,979,548</td>
<td>119</td>
<td>41</td>
</tr>
<tr>
<td>Italy</td>
<td>59,359,900</td>
<td>202</td>
<td>46</td>
</tr>
<tr>
<td>Tanzania</td>
<td>57,310,019</td>
<td>65</td>
<td>17</td>
</tr>
<tr>
<td>South Africa</td>
<td>56,717,156</td>
<td>47</td>
<td>26</td>
</tr>
</tbody>
</table>
</div>
<div class="col-sm-12">
<div id="chart"></div>
</div>
<div class="col-sm-12">
<div id="pie"></div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#table').DataTable();
});
</script>
<script src="./script.js"></script>
</body>
</html>
A:
In pie series type one series means one pie chart, so you should define your data in this way:
series: [{
name: 'PErcentage',
colorByPoint: true,
data: data[1]
}]
|
[
"stackoverflow",
"0040669673.txt"
] | Q:
removing the backslashes in json string using the javascript
i have JSON response which is having backslashes and some responses are not containing the backslashes.
I need to show error message based on the response, How do i parse the JSON response using javascript?
JSON response with out backslashes,
{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}
response with backslashes,
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"}
i tried in the following way but it is working only for JSON response which is not having the backslashes.
var strj = JSON.stringify(err._body);
var errorobjs = strj.replace(/\\/g, "");
A:
Actually the problem is not with / slashs. The JSON is INVALID.
remove these " from backend server
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal
Server
Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal
Server Error"}
double quote before "{"timestamp and one after login"}"
these two highlighted and your code will work.
var data = '{"_body":{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"},"status":500,"ok":false,"statusText":"Internal Server Error"}';
var json_data = JSON.parse(data);
console.log(json_data);
You are actually wrapping body object in string at backend which is not valid.
"body" : "bodyOBJ" //Invalid
"body" : bodyObj //Valid
|
[
"stackoverflow",
"0061790856.txt"
] | Q:
Can't install sasl package in Ubuntu 18
I want to install pyHive package in ubuntu. Using this step:-
sudo apt-get install gcc
sudo apt-get install libsasl2-dev
pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive
but when i install sasl package it's given me error
Using cached sasl-0.2.1.tar.gz (30 kB)
Requirement already satisfied: six in /home/shivam_gupta/Documents/pip3-venv/lib/python3.7/site-packages (from sasl) (1.14.0)
Installing collected packages: sasl
Running setup.py install for sasl ... error
ERROR: Command errored out with exit status 1:
command: /home/shivam_gupta/Documents/pip3-venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-vokx0cvb/sasl/setup.py'"'"'; __file__='"'"'/tmp/pip-install-vokx0cvb/sasl/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-hqi5nw58/install-record.txt --single-version-externally-managed --compile --install-headers /home/shivam_gupta/Documents/pip3-venv/include/site/python3.7/sasl
cwd: /tmp/pip-install-vokx0cvb/sasl/
Complete output (32 lines):
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-3.7
creating build/lib.linux-x86_64-3.7/sasl
copying sasl/__init__.py -> build/lib.linux-x86_64-3.7/sasl
running egg_info
writing sasl.egg-info/PKG-INFO
writing dependency_links to sasl.egg-info/dependency_links.txt
writing requirements to sasl.egg-info/requires.txt
writing top-level names to sasl.egg-info/top_level.txt
reading manifest file 'sasl.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'sasl.egg-info/SOURCES.txt'
copying sasl/saslwrapper.cpp -> build/lib.linux-x86_64-3.7/sasl
copying sasl/saslwrapper.h -> build/lib.linux-x86_64-3.7/sasl
copying sasl/saslwrapper.pyx -> build/lib.linux-x86_64-3.7/sasl
running build_ext
building 'sasl.saslwrapper' extension
creating build/temp.linux-x86_64-3.7
creating build/temp.linux-x86_64-3.7/sasl
gcc -pthread -B /home/shivam_gupta/anaconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Isasl -I/home/shivam_gupta/Documents/pip3-venv/include -I/home/shivam_gupta/anaconda3/include/python3.7m -c sasl/saslwrapper.cpp -o build/temp.linux-x86_64-3.7/sasl/saslwrapper.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++
In file included from sasl/saslwrapper.cpp:254:0:
sasl/saslwrapper.h: In member function ‘void saslwrapper::ClientImpl::interact(sasl_interact_t*)’:
sasl/saslwrapper.h:437:11: warning: unused variable ‘input’ [-Wunused-variable]
char* input;
^~~~~
g++ -pthread -shared -B /home/shivam_gupta/anaconda3/compiler_compat -L/home/shivam_gupta/anaconda3/lib -Wl,-rpath=/home/shivam_gupta/anaconda3/lib -Wl,--no-as-needed -Wl,--sysroot=/ build/temp.linux-x86_64-3.7/sasl/saslwrapper.o -lsasl2 -o build/lib.linux-x86_64-3.7/sasl/saslwrapper.cpython-37m-x86_64-linux-gnu.so
unable to execute 'g++': No such file or directory
error: command 'g++' failed with exit status 1
----------------------------------------
ERROR: Command errored out with exit status 1: /home/shivam_gupta/Documents/pip3-venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-vokx0cvb/sasl/setup.py'"'"'; __file__='"'"'/tmp/pip-install-vokx0cvb/sasl/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-hqi5nw58/install-record.txt --single-version-externally-managed --compile --install-headers /home/shivam_gupta/Documents/pip3-venv/include/site/python3.7/sasl Check the logs for full command output.
My python version:- 3.7.6
What I do for installing hive in my ubuntu system?
And thrift-sasl also not installed.
A:
unable to execute 'g++': No such file or directory
You don't have GNU C++ compiler. Install it:
sudo apt-get install g++
|
[
"bicycles.stackexchange",
"0000032415.txt"
] | Q:
Shimano Claris shifter double/triple shifting up (when moving to smaller, harder cogs) on the rear derailleur
Although my rear derailleur is properly indexed it's suddenly started to double or even triple shift on an upshift - i.e. when moving to harder, smaller cogs on the cassette.
This happens whether I'm riding or even if the bike is completely stationary and I'm only moving the shifter in isolation - I can feel and see the display on the hood jump 2-3 positions. It only happens in what would be the mid positions of the cassette - the very bottom gear and the top few gears aren't affected when I shift up from them.
Downshifts to larger, easier cogs are completely unaffected.
I've tried peeling back the brake hood and giving the mechanism a good blast of penetrating lubricant but to no avail.
Is this likely to be a shifter only problem and what if anything can I do to rectify it?
A:
Check the following:
If you remove the cable tension, do you get the right number of clicks for the shifter? If not, you may have a broken pawl or gummed up pawl. If blasting with wd-40 doesn't work, you need to get a new shifter, cause taking apart a brifter and putting it back again is hard.
Is the derailleur bent? It isn't possible to adjust a bent derailleur satisfactorially. To unbend it properly, you need a special tool.
Is the chain worn? If so, get a new chain. Check with a gauge.
Is the cassette worn? If so, get a new cassette. And probably a new chain, for good measure. See this link on chain + cassette wear.
Is the derailleur adjusted properly? The cables do slip over time, and you may need to readjust them. Follow the directions here.
Is the cable slipping or have excess friction or under too much or too little tension? You can clamp down the cable and/or replace it. You can also get weird things if your frame flexes enough to pull the cable, e.g. if you have under-bottom bracket shift cable routing.
|
[
"stackoverflow",
"0057894668.txt"
] | Q:
How to define return type using keyof accessor with TypeScript?
Is it possible to create a function that uses keyof to access a property of an object, and have TypeScript infer the return value?
interface Example {
name: string;
handles: number;
}
function get(n: keyof Example) {
const x: Example = {name: 'House', handles: 8};
return x[n];
}
function put(value: string) {
}
put(get("name"));
// ^^^ Error: Argument of type 'string | number' is not assignable to parameter of type 'string'
TypeScript is merging all the allowed types together, but when the function is called with the value "name" it does not infer the type is string.
I can resolve the issue by casting the type.
put(get("name") as string);
Is there a way to do this without casting?
A:
Sure, you just have to make get generic so that it doesn't return the union of all possible output types:
function get<K extends keyof Example>(n: K) {
const x: Example = { name: "House", handles: 8 };
return x[n];
}
Now the signature is inferred to be:
// function get<K extends "name" | "handles">(n: K): Example[K]
Where the return type, Example[K], is a lookup type representing the type you get when you index into an Example with key K.
When you call it, K is inferred to be a string literal type if it can be:
get("name"); // function get<"name">(n: "name"): string
And Example["name"] is equivalent to string. So now your call works as desired:
put(get("name")); // okay
Hope that helps. Good luck!
Link to code
|
[
"stackoverflow",
"0036398165.txt"
] | Q:
I want to find the Locator type with locator content in selenium
I want to find the Locator type with locator content in selenium. The following is the function which i wrote to get the locator type by passing locator content.
When i execute Verify.java it will go for Function.java and from there it will go to Element.java find the element locator type and return to function, and in function i will do the necessary operation like sendkeys or click.
In the Verify.java i have given the Xpath of textbox and button. My intention is to go and check whether the locator content which i pass belongs to which locator.
It is stopping by checking the first if itself and not going to catch block also and not moving to else if to verify other locator type. If i comment from first if up-to Xpath if its working. It is not looping and checking.
Can anyone suggest me the solution?
(Testcase) Verify.Java
----------------------
package cm;
import org.testng.annotations.Test;
public class Verify extends Function{
@Test
public void Check(){
Browser("Chrome", "https://www.google.co.in");
Enter("//*[@id='lst-ib']", "Karthick");
Click(".//*[@id='sblsbb']");
}
}
Function.Java
-------------
package cm;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
public class Function extends Element{
public void Enter(String LocatorContent, String Value) {
FindElement(LocatorContent).sendKeys(Value);
}
public void Click(String LocatorContent) {
FindElement(LocatorContent).click();
}
}
Element.Java
------------
package cm;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
public class Element extends Browser {
public Element()
{
this.driver = driver;
}
public WebElement FindElement(String LocatorContent){
//this.driver = driver;
WebElement elemen = null;
if (driver.findElement(By.id(LocatorContent)).isDisplayed()) {
try {
elemen = driver.findElement(By.id(LocatorContent));
System.out.println("element locator is id");
} catch (Exception e) {
System.out.println("Element Not Found given with Locator Id : "+LocatorContent);
}
return elemen;
}
else if (driver.findElement(By.name(LocatorContent)).isDisplayed()) {
try {
elemen = driver.findElement(By.name(LocatorContent));
} catch (Exception e) {
System.out.println("Element Not Found given with Locator Name : "+LocatorContent);
}
return elemen;
}
else if (driver.findElement(By.className(LocatorContent)).isDisplayed()) {
try {
elemen = driver.findElement(By.className(LocatorContent));
} catch (Exception e) {
System.out.println("Element Not Found given with Locator ClassName : "+LocatorContent);
}
return elemen;
}
else if (driver.findElement(By.cssSelector(LocatorContent)).isDisplayed()) {
try {
elemen = driver.findElement(By.cssSelector(LocatorContent));
} catch (Exception e) {
System.out.println("Element Not Found given with Locator Css : "+LocatorContent);
}
return elemen;
}
else if (driver.findElement(By.xpath(LocatorContent)).isDisplayed()) {
try {
elemen = driver.findElement(By.xpath(LocatorContent));
System.out.println("It Found the element "+LocatorContent);
} catch (Exception e) {
System.out.println("Element Not Found given with Locator Xpath : "+LocatorContent);
}
return elemen;
}
else if (driver.findElement(By.linkText(LocatorContent)).isDisplayed()) {
try {
elemen = driver.findElement(By.linkText(LocatorContent));
} catch (Exception e) {
System.out.println("Element Not Found given with Locator LinkText : "+LocatorContent);
}
return elemen;
}
else if(driver.findElement(By.partialLinkText(LocatorContent)).isDisplayed()) {
{
try {
elemen = driver.findElement(By.partialLinkText(LocatorContent));
} catch (Exception e) {
System.out.println("Element Not Found given with Locator PartialLinkText : "+LocatorContent);
}
return elemen;
}
}
return elemen;
}
}
A:
Please find below updated code, hope this will work.
public WebElement FindElement(String LocatorContent) throws Exception{
this.driver = driver;
WebElement elemen = null;
try {
if (driver.findElement(By.id(LocatorContent)).isDisplayed()) {
elemen = driver.findElement(By.id(LocatorContent));
System.out.println("element locator is id");
return elemen;
}
}
catch(Exception ex){ }
try {
if (driver.findElement(By.name(LocatorContent)).isDisplayed()) {
elemen = driver.findElement(By.name(LocatorContent));
System.out.println("element locator is name");
return elemen;
}
}
catch(Exception ex){ }
try {
if (driver.findElement(By.className(LocatorContent)).isDisplayed()) {
elemen = driver.findElement(By.className(LocatorContent));
System.out.println("element locator is className");
return elemen;
}
}
catch(Exception ex){ }
try {
if (driver.findElement(By.cssSelector(LocatorContent)).isDisplayed()) {
elemen = driver.findElement(By.cssSelector(LocatorContent));
System.out.println("element locator is cssSelector");
return elemen;
}
}
catch(Exception ex){ }
try {
if (driver.findElement(By.linkText(LocatorContent)).isDisplayed()) {
elemen = driver.findElement(By.linkText(LocatorContent));
System.out.println("element locator is linkText");
return elemen;
}
}
catch(Exception ex){ }
try {
if (driver.findElement(By.partialLinkText(LocatorContent)).isDisplayed()) {
elemen = driver.findElement(By.partialLinkText(LocatorContent));
System.out.println("element locator is partialLinkText");
return elemen;
}
}
catch(Exception ex){ }
try {
if (driver.findElement(By.xpath(LocatorContent)).isDisplayed()) {
elemen = driver.findElement(By.xpath(LocatorContent));
System.out.println("element locator is xpath");
return elemen;
}
}
catch (Exception e) { }
if (elemen.equals(null))
throw new Exception("Please not found");
return elemen;
}
|
[
"stackoverflow",
"0054408883.txt"
] | Q:
How to use utf8 characters as key of object
That's what I want:
data = {}
a = 'имя'
b = 'фамилия'
data[a] = 'osman'
data[b] = 'omar'
encode('utf-8') and decode('utf-8') doesn't work. How can I achieve such result?
A:
Put this line on top of your .py file if you are using Python2:
# -*- coding: utf-8 -*-
If you are using Python3 your code works just fine.
|
[
"stackoverflow",
"0050630752.txt"
] | Q:
Create startup-script for Google GCE to create a proxy server
I want a to create proxy server while creating a new instance of Google Compute Engine that will allow information to be passed from a bot that checks out automatically on shopping websites.
I know it can be done by creating a startup-script, but I don't know how can I write a startup-script to create a proxy server on Google cloud?
Help me, please!
Thanks in Advance!
A:
You may follow the instructions in the GCP public documentation. It shows how to configure an instance as a network proxy, and use that instance as a proxy server. The tutorial in the article is well explained.
|
[
"stackoverflow",
"0039625019.txt"
] | Q:
JavaFX Boolean Binding Based on Selected Items in a TableView
I am attempting to enable a JavaFX Button depending on the aggregate of a property value in the selected rows in a TableView. The following is an example application that demonstrates the problem:
package test;
import java.util.Random;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(final String[] args) throws Exception {
launch(args);
}
private static class Row {
private final BooleanProperty myProp;
public Row(final boolean value) {
myProp = new SimpleBooleanProperty(value);
}
public BooleanProperty propProperty() { return myProp; }
}
@Override
public void start(final Stage window) throws Exception {
// Create a VBox to hold the table and button
final VBox root = new VBox();
root.setMinSize(200, 200);
// Create the table, and enable multi-select
final TableView<Row> table = new TableView<>();
final MultipleSelectionModel<Row> selectionModel = table.getSelectionModel();
selectionModel.setSelectionMode(SelectionMode.MULTIPLE);
root.getChildren().add(table);
// Create a column based on the value of Row.propProperty()
final TableColumn<Row, Boolean> column = new TableColumn<>("Value");
column.setCellValueFactory(p -> p.getValue().propProperty());
table.getColumns().add(column);
// Add a button below the table
final Button button = new Button("Button");
root.getChildren().add(button);
// Populate the table with true/false values
final ObservableList<Row> rows = table.getItems();
rows.addAll(new Row(false), new Row(false), new Row(false));
// Start a thread to randomly modify the row values
final Random rng = new Random();
final Thread thread = new Thread(() -> {
// Flip the value in a randomly selected row every 10 seconds
try {
do {
final int i = rng.nextInt(rows.size());
System.out.println("Flipping row " + i);
Thread.sleep(10000);
final BooleanProperty prop = rows.get(i).propProperty();
prop.set(!prop.get());
} while (true);
} catch (final InterruptedException e) {
System.out.println("Exiting Thread");
}
}, "Row Flipper Thread");
thread.setDaemon(true);
thread.start();
// Bind the button's disable property such that the button
// is only enabled if one of the selected rows is true
final ObservableList<Row> selectedRows = selectionModel.getSelectedItems();
button.disableProperty().bind(Bindings.createBooleanBinding(() -> {
for (int i = 0; i < selectedRows.size(); ++i) {
if (selectedRows.get(i).propProperty().get()) {
return false;
}
}
return true;
}, selectedRows));
// Show the JavaFX window
final Scene scene = new Scene(root);
window.setScene(scene);
window.show();
}
}
To test, start the above application, and select the row indicated by the text "Flipping row N", where N is in [0, 2]. When the value of the selected row changes to true...
Observed Behavior button remains disabled.
Desired Behavior button becomes enabled.
Does anyone know how to create a BooleanBinding that exhibits the desired behavior?
A:
Your binding needs to be invalidated if any of the propPropertys of the selected rows change. Currently the binding is only observing the selected items list, which will fire events when the list contents change (i.e. items become selected or unselected) but not when properties belonging to items in that list change value.
To do this, create a list with an extractor:
final ObservableList<Row> selectedRows =
FXCollections.observableArrayList(r -> new Observable[]{r.propProperty()});
This list will fire events when items are added or removed, or when the propProperty() of any item in the list changes. (If you need to observe multiple values, you can do so by including them in the array of Observables.)
Of course, you still need this list to contain the selected items in the table. You can ensure this by binding the content of the list to the selectedItems of the selection model:
Bindings.bindContent(selectedRows, selectionModel.getSelectedItems());
Here is a version of your MCVE using this:
import java.util.Random;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(final String[] args) throws Exception {
launch(args);
}
private static class Row {
private final BooleanProperty myProp;
public Row(final boolean value) {
myProp = new SimpleBooleanProperty(value);
}
public BooleanProperty propProperty() { return myProp; }
}
@Override
public void start(final Stage window) throws Exception {
// Create a VBox to hold the table and button
final VBox root = new VBox();
root.setMinSize(200, 200);
// Create the table, and enable multi-select
final TableView<Row> table = new TableView<>();
final MultipleSelectionModel<Row> selectionModel = table.getSelectionModel();
selectionModel.setSelectionMode(SelectionMode.MULTIPLE);
root.getChildren().add(table);
// Create a column based on the value of Row.propProperty()
final TableColumn<Row, Boolean> column = new TableColumn<>("Value");
column.setCellValueFactory(p -> p.getValue().propProperty());
table.getColumns().add(column);
// Add a button below the table
final Button button = new Button("Button");
root.getChildren().add(button);
// Populate the table with true/false values
final ObservableList<Row> rows = table.getItems();
rows.addAll(new Row(false), new Row(false), new Row(false));
// Start a thread to randomly modify the row values
final Random rng = new Random();
final Thread thread = new Thread(() -> {
// Flip the value in a randomly selected row every 10 seconds
try {
do {
final int i = rng.nextInt(rows.size());
System.out.println("Flipping row " + i);
Thread.sleep(10000);
final BooleanProperty prop = rows.get(i).propProperty();
Platform.runLater(() -> prop.set(!prop.get()));
} while (true);
} catch (final InterruptedException e) {
System.out.println("Exiting Thread");
}
}, "Row Flipper Thread");
thread.setDaemon(true);
thread.start();
// Bind the button's disable property such that the button
// is only enabled if one of the selected rows is true
final ObservableList<Row> selectedRows =
FXCollections.observableArrayList(r -> new Observable[]{r.propProperty()});
Bindings.bindContent(selectedRows, selectionModel.getSelectedItems());
button.disableProperty().bind(Bindings.createBooleanBinding(() -> {
for (int i = 0; i < selectedRows.size(); ++i) {
if (selectedRows.get(i).propProperty().get()) {
return false;
}
}
return true;
}, selectedRows));
// Show the JavaFX window
final Scene scene = new Scene(root);
window.setScene(scene);
window.show();
}
}
|
[
"stackoverflow",
"0048110218.txt"
] | Q:
R: Opposite to aggregate using tidytext::unnest_tokens. Multiple variables and upper case
Following up on this question, I want to perform a task opposite to aggregate (or the data.table equivalent as in the MWE below), so that I obtain df1 again, starting from df2.
The task here then is to reproduce df1 from df2. For this, I tried tidytext::unnest_tokens, but I cannot figure out how to make it work properly when more than one variable have to be "dis-aggregated" (models, countries, and years).
It would be nice to retain the original upper case of the variables as well.
Any elegant solution different from tidytext::unnest_tokens would be accepted! Thanks!
Here is the MWE:
####MWE
library(data.table)
library(tidytext)
df1 <- data.frame(brand=c(rep('A',4), rep('B',5), rep('C',3), rep('D',2),'E'),
model=c('A1','A1','A2','A3','B1','B2','B2','B2','B3','C1','C1','C2','D1','D2','E1'),
country=c('P','G','S','S','P','P','F','I','D','S','F','F','G','I','S'),
year=c(91,92,93,94,98,95,87,99,00,86,92,92,93,95,99))
df1
dd <- data.table(df1)
df2 <- as.data.frame(dd[, list(models=paste(model, collapse=' /// '),
countries=paste(country, collapse=' /// '),
years=paste(year, collapse=' /// ')),
by=list(brand=brand)])
df2
df1b <- df2 %>%
unnest_tokens(model, models, token = "regex", pattern = " /// ")
df1b
####
A:
We can use separate_rows
library(tidyverse)
res <- df2 %>%
separate_rows(models, countries, years, convert = TRUE) %>%
rename_all(funs(paste0(names(df1)))) %>% #just to make the column names same as df1
mutate(year = as.numeric(year)) #convert to numeric to match df1 column type
all.equal(res, df1 %>%
mutate_at(2:3, as.character), check.attributes = FALSE )
#[1] TRUE
|
[
"stackoverflow",
"0038495922.txt"
] | Q:
TimeSpan.ParseExact with ms
Trying to parse the following time
string time = "12:25:1197";
TimeSpan t = TimeSpan.ParseExact(time, "HH.mm.ssff", CultureInfo.InvariantCulture);
What is wrong here?
A:
First, you are using . as a separator, but your string uses :.
Second, that is a quite weird representation of seconds (which is a 60 based number) and milliseconds (which is a 100-based one), so you more likely have:
string time = "12:25:11.97" // remember the quotes
Which should be parsed with:
TimeSpan t = TimeSpan.ParseExact(time, "hh':'mm':'ss.ff", CultureInfo.InvariantCulture);
If you indeed have 12:25:1197 then you can use hh':'mm':'ssff, but that's indeed weird
Btw, if that's two digits for what you call ms, then that's hundreths of seconds, not milliseconds (which woulf be three digits)
|
[
"russian.stackexchange",
"0000014977.txt"
] | Q:
What is the logic behind "вялотекущая" attachable to an illness but not to a river?
In my understanding, "вялотекущая" means having a slow flux. This you would literally associate with rather with a river, but no -
вялотекущая шизофрения - ОK
вялотекущая река - NOT OK
Why? I understand that language can be quite irrational, but my question is - maybe in this special case there is indeed some crazy logic behind these cases?
A:
Ever heard of wholes being greater than the sums of their parts? Crazy, huh?
Вялотекущая is not the same as вяло текущая. The former is a medical term and was coined (or, if you like, glued together) as such. Вяло текущая река is fine.
|
[
"stackoverflow",
"0043829906.txt"
] | Q:
Virto Commerce Azure Empty Roles list
I am trying to install the store front directly to Azure from github. One of the required fields on the installation form is Virto Commerce Api Hmac App Id. I think the generation of this code requires the 'Use Api' role in the user manager.
My problem is that the Available Roles list is empty in my Azure installation of the platform manager.
How do I populate this list with the built in Roles ?
A:
As it appears you have installed VC platform without sample data.
Because VC storefront interacted with platform only via API you should generate new Hmac security key for frontend user and enter it in Virto Commerce Api Hmac App Id on storefront installation wizard.
For generate new Hmac security key please do follow steps.
Open Configuration-> Security-> Users-> Click on frontend user -> API keys -> Click on Frontend(Hmac)-> Generate
|
[
"stackoverflow",
"0017315370.txt"
] | Q:
Configure jboss AS7 to use multiple modules dirs
Is it possible (and if: how?) to set up JBoss AS7 to use his own modules dir and an additional custom modules.custom at the same time? If so, I would not have to mix my custom entries with the default entries.
A:
you can do that by setting JBOSS_MODULEPATH env variable to include more than just your folder.
For instance configuration like this
set JBOSS_MODULEPATH=%JBOSS_HOME%/modules;/path/to/my/modules
it would add /path/to/my/modules to path of modules. But just make sure you still keep default folder in your module path.
for more you can take a look at standalone.sh/bat and look how this variable is used.
(if you are on mac or unix, use export and colons)
export JBOSS_MODULPATH=$JBOSS_HOME/modules:/path/to/my/modules
|
[
"stackoverflow",
"0045759431.txt"
] | Q:
How to set DataGrid line color in DataTrigger?
How can I set a different grid line color for some rows in DataGrid through DataTrigger?
I tried this:
<DataGrid ...>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger
Binding="{Binding in_stock, Converter={conv:LessThan 4}}"
Value="True">
<Setter Property="BorderBrush" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
But the grid lines are all the same, default color.
A:
I haven't found a way to hide the grid line at each separate row but I bypassed it by removing all horizontal grid lines through GridLinesVisibility="Vertical" and creating one-pixel bottom border for each DataGridCell where it is desired.
|
[
"vi.stackexchange",
"0000009365.txt"
] | Q:
Mapping Esc+key (hold down escape and press another key to perform action)
I mapped my capslock key to escape but sometimes I accidentally press capslock when I meant to press shift.
Can I remap <Esc>+key to send me back to insert mode and insert the proper character?
For example I would like to press <Esc>+9 and be put back into insert mode and insert the ( character (as if I had just pressed <Shift>+9).
Possible?
A:
<Esc> is not a modifier like Shift. There's no <Esc-9> keycode, only <S-9>.
As you usually press Shift before the other key, you could approach this via a set of sequential mappings:
:inoremap <Esc>9 (
:inoremap <Esc>0 )
...
But that would introduce a noticeable delay when you really just want to leave insert mode.
|
[
"stackoverflow",
"0046633357.txt"
] | Q:
vuex store losing data on PAGE REGRESH
I am building authentication system in laravel and vuejs, I am building using JWT and storing token in lacalstorage. I am able to store user data in vuex store and yes i can see under vuex area in devtool. The problem is when i am refreshing page i am losing it . I wanna persist user's information, It should not get deleted on a page refresh . How can i achieve that
import Vue from 'vue'
import Vuex from 'vuex'
import userStore from './components/user/userStore'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
modules : {
userStore
},
strict : debug
})
A:
You can try to save your Vuex to localstorage or cookie.
There is a plugin to help save your state to localstorage https://github.com/robinvdvleuten/vuex-persistedstate
|
[
"gamedev.stackexchange",
"0000153412.txt"
] | Q:
How to simulate an elastic force, using Hinge Joint ?
I've a bucket connected to a rope.
I would like that when a ball fall in my bucket , my bucket "bounce"down and up .. like it is connected to an elastic rope.
How can i do that ?
Thanks
A:
You need to look into Spring Joint. I don't think the Hinge Join is appropriate to solve your issue.
Video Demo:
https://drive.google.com/file/d/1IpSi3Pg01kPa0mrAiemXcMs6tM--2QYb/view?usp=sharing
Unity3D documentation:
https://docs.unity3d.com/Manual/class-SpringJoint.html
|
[
"arduino.stackexchange",
"0000039859.txt"
] | Q:
Undervoltage from solar panels
So i'be been toying with the idea in my head of creating a solar powered weather station with an arduino, two 6V 2W solar panels in parallel, two 5V USB battery packs, and an adafruit module which converts voltages from 3-12V to 5V (to charge my batteries). I'm also working on using some small relays or MOSFETs for the arduino switch between batteries.
The problem: If my solar panel voltage drops below 3V, the adafruit board will supply the batteries with a n unstable voltage below 4.8V. I need some sort of circuit or sensor that is capable of detecting when the voltage from the solar panels drops below 3.3V and which will open the circuit to protect the batteries from unstable voltages.
A:
You have selected a number of things that don't go well together. It is possible to use relays or mosfets to switch between batteries, and the Arduino could be used to measure a voltage. Or you can make a circuit with a few electronic components (e.g. a comparator). However, no one does it like that. It would be unreliable.
Every solar power charging module can handle darkness as well. Some modules will also create 5V.
This Adafruit module has no 5V output, it only contains the charging part: Adafruit:USB / DC / Solar Lithium Ion/Polymer charger - v2
It is out of stock at the moment, and you need solar cells, battery, a cable, and a DC-DC converter to make 5V.
When it is dark and the battery is empty, I assume the output drops and the Arduino stops working. Adafruit made a tutorial for it that shows the DC-DC converter and also Collin shows a DC-DC converter: Youtube, Collin's Lab: Solar
There are other modules like that. For example the Sparkfun Sunny Buddy.
Take care that the batteries don't get too hot.
It is possible to run some Arduino boards directly from a battery (3.1 to 4.2V). Then you would not need the DC-DC converter.
Buy solar cells that are the best in low light conditions. With enough sunlight, the power is no problem. It is the dark winter days that could be a problem.
|
[
"stackoverflow",
"0042554447.txt"
] | Q:
focusout and click event execution order in javascript
I have defined a focusout event handler on a text box and a click handler on a button. If I focus inside the text input and then directly click the button, then both the events get fired, as expected. focusout event gets fired first and click is fired if developer toolbar is opened else its fires in vice-versa manner.
What could be actual reason behind this?
Here is the snippet for the ones asking, But I believe question itself was clear enough:
document.getElementById('myInput').addEventListener('blur', function(){ alert("Input Focused Out"); });
document.getElementById('myButton').addEventListener('click', function(){ alert("Button Clicked"); });
<input id="myInput" name="myInput" type="text" />
<button id="myButton" name="myButton" >Button</button>
A:
I think, when you are comparing order of click event and blur event, blur should always trigger before click event irrespective of debugger tool.
The reason being click involves mousedown+mouseup. It means, until mouse button is released, click event will not get triggered.
I tested in a fiddle and found that if we find such a case, we should use mousedown event instead of click event.
As I tested more, I found that order of mousedown is always before blur event so in such a case, mousedown will trigger first and then blur event will trigger.
Fiddle: https://jsfiddle.net/y3gyq93a/1/
JS:
document.getElementById('myInput').addEventListener('blur', function(){
document.getElementById("myDiv").innerHTML = document.getElementById("myDiv").innerHTML + "blur";
});
document.getElementById('myButton').addEventListener('mousedown', function(){
document.getElementById("myDiv").innerHTML = document.getElementById("myDiv").innerHTML + "mousedown";
});
document.getElementById('myButton').addEventListener('click', function(){
document.getElementById("myDiv").innerHTML = document.getElementById("myDiv").innerHTML + "click";
});
HTML:
<input id="myInput" name="myInput" type="text" />
<button id="myButton" name="myButton" >Button</button>
<div id="myDiv">
</div>
|
[
"stackoverflow",
"0038135722.txt"
] | Q:
OnItemCommand of asp:Repeater not working with validator
the function in OnItemCommand of the asp:Repeater is not working randomly. It's a normal one coded like this.
<asp:Repeater runat="server" ID="control01" OnItemCommand="control01_OnItemCommand">
<ItemTemplate>
<li><asp:LinkButton runat="server" ID="btn_button" CommandArgument='1'>Click</asp:LinkButton></li>
</ItemTemplate>
</asp:Repeater>
After some time spent on debug I found it's related a input text box on page.
<asp:TextBox ID="txt_input" runat="server"></asp:TextBox>
Only if it's correct value (validated) the function works well.
If I remove <asp:RequiredFieldValidator> and <asp:RequiredFieldValidator> on the text box here
<asp:RegularExpressionValidator ID="rvDecimal" ControlToValidate="txt_input" runat="server" ErrorMessage="Please enter a valid value" ValidationExpression="^(-)?\d+(\.\d\d)?$"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="rfd_input" runat="server" ControlToValidate="txt_input" Text="Please enter a valid value"></asp:RequiredFieldValidator>
OnItemCommand got fired and the function works well.
The question is, how can I keep the validation and make the function in OnItemCommand working?
A:
Finally I've solved the problem by adding CausesValidation="false" in the control.
<asp:LinkButton runat="server" ID="btn_button" CausesValidation="false">
This would skip the validation the trigger the function in OnItemCommand
|
[
"askubuntu",
"0001058498.txt"
] | Q:
How to deal without goto in Bash?
Bash doesn't have a goto operator. I have a simple task, and I can't figure out how to solve it without goto or adding a new proc, and that is undesireable.
I have two conditions and a block of code that should work this way:
[ condition 1 ] if true run some commands and check [ condidion 2 ]; if false exec a block of code.
[ condition 2 ] if true don't exec the same block of code; if false do execute the same block.
Is it solvable, or I have to define some proc and use exit there? I used a flag var, but I don't like it.
With goto available it would look this way:
[ cond 1 ] || goto label 1
command
...
command
[ cond 2 ] && goto label 2
:label 1
block of code
:label 2
Something like that.
A:
The typical way to work to use branching in shell scripts would be via functions declared before main block of code. However, I think the underlying issue here is the logical one, and not the goto. Obviously label 1 is repeated, so this can live as function. But also, condition 2 could be turned into a function that also calls label 1 for the sake of readability:
#!/bin/bash
label1(){
echo "label 1 function"
}
check_cond2(){
if ! [ condition2 ]; then
label1 arg1 arg2
fi
}
if [ condition1 ]; then
command
...
command
check_cond2
else
label1
fi
othercommand2
othercommand3
What I've noticed is that in both conditions you have if false exec a block of code and if false exec a block of code, so one idea would be to start at checking whether those conditions both false. However, making something like if ! [ cond1 ] || ! [ cond2 ] would change branching logic. You can still see the pseudocode version of that by seeing this posts edit history.
A:
You should put your block_of_code into a function and use some if/else:
my_function() {
block of code
...
}
if [[ condition 1 ]] ; then
command
...
command
if [[ ! condition 2 ]] ; then
# label 1
my_function
fi
else
# label 1
my_function
fi
# label 2
A:
When I moved from Windows to Linux on my desktop, I had a lot of pre-existing .BAT and .CMD files to convert and I wasn't going to rewrite the logic for them, so I found a way to do a goto in bash that works because the goto function runs sed on itself to strip out any parts of the script that shouldn’t run, and then evals it all.
The below source is slightly modified from the original to make it more robust:
#!/bin/bash
# BAT / CMD goto function
function goto
{
label=$1
cmd=$(sed -n "/^:[[:blank:]][[:blank:]]*${label}/{:a;n;p;ba};" $0 |
grep -v ':$')
eval "$cmd"
exit
}
apt update
# Just for the heck of it: how to create a variable where to jump to:
start=${1:-"start"}
goto "$start"
: start
goto_msg="Starting..."
echo $goto_msg
# Just jump to the label:
goto "continue"
: skipped
goto_msg="This is skipped!"
echo "$goto_msg"
: continue
goto_msg="Ended..."
echo "$goto_msg"
# following doesn't jump to apt update whereas original does
goto update
and I do not feel guilty at all as Linus Torvalds famously said:
From: Linus Torvalds
Subject: Re: any chance of 2.6.0-test*?
Date: Sun, 12 Jan 2003 11:38:35 -0800 (PST)
I think goto's are fine, and they are often more readable than large amounts of indentation. That's especially true if the code flow isn't actually naturally indented (in this case it is, so I don't think using goto is in any way clearer than not, but in general goto's can be quite good for readability).
Of course, in stupid languages like Pascal, where labels cannot be descriptive, goto's can be bad. But that's not the fault of the goto, that's the braindamage of the language designer.
Original source for the code (modified to make it less error prone)
The source for the quote
|
[
"stackoverflow",
"0034546716.txt"
] | Q:
How to open system camera in its normal operation after I launch it from my activity?
I am working with camera in project and provided a simple button in activity which will open camera app in my device. But the problem is after clicking one photo, it asks weather I want to keep my picture or not and after clicking yes, it return to my main activity.
But I want to operate camera in normal mode, I mean like when we click photo after photos and all that.
My code
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
following permission is used
uses-permission android:name="android.permission.CAMERA" uses-permission
I dont know why tags are not working.
Any kind of help is appreciated!
A:
To take multiple photos, you should launch the intent with this action:
Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
startActivity(intent);
|
[
"money.stackexchange",
"0000075921.txt"
] | Q:
Calculating amortisation payment amount, where first payment date differs from loan start date
I'm trying to reproduce the schedule, but I cant seem to get the same Payment and Interest for each month. The tricky part here is that the Loan start date is 9 Feb 2017 but the first payment is only due on the 31st of March, from which the schedule then begins. So there is a broken interest from 9 Feb to 28 Feb. Which also get amortized across the schedule.
My compounding is also Monthly.
So my questions are.
How do I calculate the broken interest for 9-28 Feb when using
monthly compounding?
How do I get to 14,098.74 for the payment
amount. Currently I have the payment amount as 14,029.36, but I'm
guessing I have to redistribute the broken interest between my
interests over each month which will push it up?
When calculating it with https://financial-calculators.com/ultimate-financial-calculator# I get the schedule as seen below. But I can't seem to reproduce it on my own in excel or C#.
A:
I calculated 14098.64 and 14098.74. Here are the methods.
First, what I would say is more mathematically correct.
For a loan with equal payment periods we have the standard formula below.
pv = present value of principal
c = periodic repayment amount
r = periodic interest rate
n = number of periods
With an extended first period the formula is changed like so.
The extension x is 19 days of an average month.
x = 19/(365/12)
pv = 160000
n = 12
r = 0.095/12
Rearranging the extended loan formula for c.
pv = (c (1 + r)^(-n - x) (-1 + (1 + r)^n))/r
∴ c = (pv r (1 + r)^(n + x))/(-1 + (1 + r)^n)
∴ c = 14098.64
Second method
Calculate the extended first period interest by this method, described here.
i1 = pv r + pv (1 + r) (0.095/365) 19 = 2064.16
Note this is incorrectly using the nominal rate compounded monthly as a nominal rate compounded daily, and then not even using compounding. I think the calculation of the extended first period interest should be 2062.98 which, if used in place of i1, results in the repayment calculated above.
dailyrate = (1 + 0.095/12)^(12/365) - 1 = 0.000259283
pv (1 + dailyrate)^(19 + 365/12) - pv = 2062.98
Nevertheless, continuing with i1, add it to the principal and calculate the loan with repayments starting immediately, not waiting a month.
s = pv + i1 = 162064.16
s = (c (1 + r - (1 + r)^(1 - n)))/r
∴ c = (r (1 + r)^(-1 + n) s)/(-1 + (1 + r)^n)
∴ c = 14098.74
A:
For the first month, it is for additional interest of Feb. For 19 days divided by 365 we get int of 791.23. Add this to Principal of 160,000. On this principal multiply by rate and divide by 12.
The Interest from second month onwards is 30/360. i.e outstanding balance Multiplied by Rate divided by 12.
It is difficult to directly find the EMI in such cases. The simplest way is to put this in spread sheet and use the Excel Goal->Seek function.
|
[
"stackoverflow",
"0028996223.txt"
] | Q:
CSS: width behavior change when including bootstrap
I recently noticed that CSS property width does not have the same effect when using bootstrap. Could someone know why?
I use firefox developer console to inspect box model and see actual dimensions.
Simple html code:
<div style="width=400px;height=30px;background-color:red;"></div>
Here is a fiddle with a simple div with a fixed width/height. Its sized 404*34
https://jsfiddle.net/nszvxfwq/
Here the same one including bootstrap. You can see the box size to be 400*30
https://jsfiddle.net/nszvxfwq/1/
A:
Thanks Adrift, your answert really helped me!
Because bootstrap applies box-sizing: border-box; to all elements, whereas >your example retains the initial box-sizing value of content box (which draws >padding & border outside of the specified width & height). – Adrift yesterday
|
[
"softwareengineering.stackexchange",
"0000161519.txt"
] | Q:
What is the best approach to getting to know a big system like a CMS or forum system which has no documentation?
My problem is the following; I need to get to know a totally new system, for example Wordpress, Drupal, or a framework like Symfony, or maybe a big forum system like PhpBB.
Let's suppose it has no documentation at all, but the code is good.
What I end up doing is that I start at index.php and click the first include, so this takes me to the next file. But then it requests another file and that file request another, so at the end I even forget where I started and have no clue which was the previous request.
So my question is, is there a good way to do this ? Like drawing a chart of the application flow or something. When I want to get to know a new system, at first I would like to get the "big picture" about what comes after what, and what files do what part of the system, what function get called when, things like these.
Basically all I want to do is able to write an Application flow like this when I start with a new system.
Is there a nice way tot do this without taking too much time and confusion?
Are there any software or debugging tools for this?
Are there any chart types for this situation which I can apply here?
Can you suggest small tricks or tips how you get to know big systems and what are you looking first without digging into the code too deeply wasting too much time on not-really-important-parts?
A:
This question is very broad, so just some general advice.
Is there a nice way tot do this without taking too much time and confusion ?
I know only one: ask the authors of the system if they can give you some explanation. If you cannot grasp any of the authors, you will have to start reengineering - no shortcut.
Are there any softwares or debugging tools for this ?
Just the same tools you use to debug your own programs. If the system is written mostly in PHP, for example, use your favorite PHP debugger.
Are there any chart types for this situation which I can apply here ?
You already suggested flow charts by yourself. Actually, if there is an underlying database, I would add an ER model (or utilize an UML class diagram as ERM replacement).
Can you suggest small tricks or tips how you get to know big systems and what are you
looking first without digging into the code too deeply wasting too much time on
not-really-important-parts ?
The only general hint I can give you here: start to analyse the data model (and whatever technology is used to store persistent data). But honestly, the right thing to do depends heavily on the system, and what you are trying to accomplish.
|
[
"stackoverflow",
"0054536214.txt"
] | Q:
How to define an interface/API which is used in multiple cpp files?
I get the following error:
"Symbol SBPTest multiply defined (by ../../build/typeFind.LPC1768.o and ../../build/main.LPC1768.o)."
I have declared SBPTest in common.h like this:
#ifndef COMMON_H_
#define COMMON_H_
extern RawSerial SBPTest(USBTX, USBRX);
#endif
Other files look like this...
typeFind.h:
#include "mbed.h"
#include <string>
extern unsigned int j;
extern unsigned int len;
extern unsigned char myBuf[16];
extern std::string inputStr;
void MyFunc(char* inputBuffer);
typeFind.cpp:
#include "typeFind.h"
#include "common.h"
void MyFunc(char* inputBuffer) {
inputStr = inputBuffer;
if (inputStr == "01") {
len = 16;
for ( j=0; j<len; j++ )
{
myBuf[j] = j;
}
for ( j=0; j<len; j++ )
{
SBPTest.putc( myBuf[j] );
}
}
}
main.cpp:
#include "typeFind.h"
#include "common.h"
#include "stdlib.h"
#include <string>
LocalFileSystem local("local"); // define local file system
unsigned char i = 0;
unsigned char inputBuff[32];
char inputBuffStr[32];
char binaryBuffer[17];
char* binString;
void newSBPCommand();
char* int2bin(int value, char* buffer, int bufferSize);
int main() {
SBPTest.attach(&newSBPCommand); //interrupt to catch input
while(1) { }
}
void newSBPCommand() {
FILE* WriteTo = fopen("/local/log1.txt", "a");
while (SBPTest.readable()) {
//signal readable
inputBuff[i] = SBPTest.getc();
//fputc(inputBuff[i], WriteTo);
binString = int2bin(inputBuff[i], binaryBuffer, 17);
fprintf (WriteTo, "%s\n", binString);
inputBuffStr[i] = *binString;
i++;
}
fprintf(WriteTo," Read input once. ");
inputBuffStr[i+1] = '\0';
//fwrite(inputBuff, sizeof inputBuffStr[0], 32, WriteTo);
fclose(WriteTo);
MyFunc(inputBuffStr);
}
char* int2bin(int value, char* buffer, int bufferSize)
{
//..................
}
I am programming on mbed, a LPC1768. The serial is used both in main.cpp and typeFind.cpp. I have looked on stack overflow and a common.h file is recommended, yet I get a compiler error.
A:
You musn't define the variable in the header, or else you end up defining it in all translation units that include the header, which violates the one definition rule. Only declare it:
// common.h
extern RawSerial SBPTest;
And define in exactly one source file:
// common.cpp (or any other, but exactly one source file)
RawSerial SBPTest(USBTX, USBRX);
I recommend using either list initialisation or copy initilisation, since direct initilisation grammar is ambiguous with a function declaration and may confuse anyone who doesn't know whether USBTX and USBRX are types or values:
// common.cpp (or any other, but exactly one source file)
RawSerial SBPTest{USBTX, USBRX}; // this
auto SBPTest = RawSerial(USBTX, USBRX); // or this
|
[
"mathoverflow",
"0000117633.txt"
] | Q:
A question about the limit of a sequence of pointwise convergent analytic funtions
Question: Let $\{f_n\}$ be a sequence of analytic functions on the unit disk $\Delta$ and suppose that $f_n$ converges to a continuous function $f$ on $\Delta$ pointwisely. (1) Can we say that $f$ is analytic on $\Delta$? (2) If $f$ is analytic, is the convergence $\underline{locally}$ uniform on $\Delta$? (Note: I add the words "locally" due to obvious reason.)
If we do not assume that the limit function $f$ is continuous (of course $f$ is measurable) in advance, (3) can we say that $f$ is continuous? [I number this new question by (3)]
Note that evrey measurbale functon on $\Delta$ can be the limit of a sequence of analytic functions in the Lebesgue sense (i.e. almost everywhere).
A:
These questions were investigated by Osgood, Montel and Lavrentiev, Sur les fonctions d'une variable complexe
representable par des series de polynomes, Paris 1936. (There is a Russian translation in his
selected Works available free on Internet). If you prefer German, see Hartogs and Rosenthal,
Uber Folgen analytischer Funktionen, Math Ann., 1928, 100, 212-263, and 1932, 104, 606-610.
In general, if a sequence of polynomials converges pointwise in a region $D$, then the
limit function is analytic except for a closed nowhere dense set $E$ (Osgood).
Montel proved that $E$ is a perfect set whose union with the complement of the disc is connected.
Lavrentiev completely characterized the sets $E$ that can occur, and proved that every function
of the first Baire class
which is analytic outside $E$ is a pointwise limit of polynomials.
Thus every continuous function, analytic outside $E$ can be obtained as a limit of polynomials.
Convergence outside $E$ is locally uniform.
This answers all your questions.
By the way, similar problems for harmonic functions (characterization of their pointwise limits)
is still not solved completely.
EDIT. For example, any simple curve in the unit disc, going from $0$ to $1$, satisfies the Lavrentiev
condition. Taking this curve with positive area, we can construct a continuous function $f$
in the unit disc, which is analytic outside the curve but not analytic in the unit disc.
This function will be a pointwise limit of polynomials.
|
[
"stackoverflow",
"0056474990.txt"
] | Q:
MYSQL Foreign key incorrectly formed
Have an error where my first foreign key constraint is incorrectly formed. I'm waiting to hear back from my lecturer if she can spot the issue but thought I'd ask here
My SQL query is as follows
CREATE DATABASE rugby;
USE rugby;
CREATE TABLE address(
address_ID INT AUTO_INCREMENT NOT NULL,
address_name VARCHAR(50) NOT NULL,
PRIMARY KEY (address_ID)
) ENGINE=INNODB;
CREATE TABLE team(
team_ID INT AUTO_INCREMENT NOT NULL,
team_Name VARCHAR(25) NOT NULL,
team_Year INT NOT NULL,
PRIMARY KEY(team_ID)
) ENGINE=INNODB;
CREATE TABLE person(
person_ID INT AUTO_INCREMENT NOT NULL,
name VARCHAR(30) NOT NULL,
phone INT NOT NULL,
address_ID INT NOT NULL,
email VARCHAR(50),
photo BLOB,
PRIMARY KEY(person_ID),
FOREIGN KEY(address_ID) REFERENCES address(address_ID) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=INNODB;
I have followed how we were taught but can't spot the issue.
Any help appreciated
A:
In table person you have defined address_ID as NOT NULL, but
when you define the FOREIGN KEY you set:
ON DELETE SET NULL
which contradicts the NOT NULL definition.
|
[
"webmasters.meta.stackexchange",
"0000000900.txt"
] | Q:
close question - My two questions
Question 1:
https://webmasters.stackexchange.com/questions/37917/new-standard-http-protocol
My question was closed because it is not constructive.
As I understand it or it was closed for not being constructive indeed.
Or because it would generate an extensive discussion.
I disagree with both situations
The question is constructive and can be used but can be useful for many people.
Will only generate discussion if the person answering unsure own answer.
Would like to know the real reason for the question was closed.
Thanks.
Question 2: https://webmasters.stackexchange.com/questions/37915/licensing-javascript-code
Honestly, I do not understand why my question was closed? This is not a discussion.
A:
Hopefully I can provide insight into why your questions were closed (and, in any case, meta is the best place to discuss - thank you for bringing this discussion to meta).
Question #1
Will only generate discussion if the person answering unsure own answer.
Your question stated "Why are they doing this[?]" which invites speculation. This wording is likely why it was closed as "not constructive".
Absolute URLs omitting the protocol (scheme) in order to preserve the one of the current page is approximately the same question - asked in a different way - and answered at StackOverflow over a year ago.
Question #2
I do not understand why my question was closed?
This question was closed as "off topic" because it is not covered by the topics listed in our FAQ:
If your question generally covers the operation of websites which you
control, then you’re in the right place to ask your question!
Please note that if your question is about detailed HTML, JavaScript,
or CSS coding, it might be a better fit on Stack Overflow. We prefer
questions here about problems or issues that affect entire websites.
|
[
"stackoverflow",
"0012005728.txt"
] | Q:
add linkin print icon on to my page
I would like to add tiny (10x10) facebook, linkedin, print icons next to mysite's article title to that once the user clicks it will do the the task (ie. facebook: it will add the article title as news into that user's facebook)
How can this be done ?
Thank you
A:
It seems like it is possible for you to use AddThis.
http://www.addthis.com
You can select what type of media the user can share your content on. Facebook and LinkedIn is some of the defaults.
|
[
"stackoverflow",
"0007599519.txt"
] | Q:
ALTER TABLE ADD COLUMN takes a long time
I was just trying to add a column called "location" to a table (main_table) in a database. The command I run was
ALTER TABLE main_table ADD COLUMN location varchar (256);
The main_table contains > 2,000,000 rows. It keeps running for more than 2 hours and still not completed.
I tried to use mytop
to monitor the activity of this database to make sure that the query is not locked by other querying process, but it seems not. Is it supposed to take that long time? Actually, I just rebooted the machine before running this command. Now this command is still running. I am not sure what to do.
A:
Your ALTER TABLE statement implies mysql will have to re-write every single row of the table including the new column. Since you have more than 2 million rows, I would definitely expect it takes a significant amount of time, during which your server will likely be mostly IO-bound. You'd usually find it's more performant to do the following:
CREATE TABLE main_table_new LIKE main_table;
ALTER TABLE main_table_new ADD COLUMN location VARCHAR(256);
INSERT INTO main_table_new SELECT *, NULL FROM main_table;
RENAME TABLE main_table TO main_table_old, main_table_new TO main_table;
DROP TABLE main_table_old;
This way you add the column on the empty table, and basically write the data in that new table that you are sure no-one else will be looking at without locking as much resources.
A:
I think the appropriate answer for this is using a feature like pt-online-schema-change or gh-ost.
We have done migration of over 4 billion rows with this, though it can take upto 10 days, with less than a minute of downtime.
Percona works in a very similar fashion as above
Create a temp table
Creates triggers on the first table (for inserts, updates, deletes) so that they are replicated to the temp table
In small batches, migrate data
When done, rename table to new table, and drop the other table
|
[
"stackoverflow",
"0016150131.txt"
] | Q:
Can there be more than one set of MFA questions asked during the discoverAndAddAccounts process?
I am using discoverAndAddAccountsResponse to answer the first set of MFA challenge questions, but this method only returns an AccountList.
Is there ever a situation where I should expect more MFA questions in response to the first set of MFA questions, and if so, how should I implement that process?
Thanks in advance.
A:
Yes - see this page for more information - http://docs.developer.intuit.com/0020_Aggregation_Categorization_Apps/0005_Service_Features/Multi-Factor_Authentication.
|
[
"stats.stackexchange",
"0000239618.txt"
] | Q:
Any penalized ensemble classifiers in `Scikit-learn` that result in sparse solutions?
Is there an ensemble classifier that results in sparse solutions for the feature vector like Lasso Regression? With Logistic Regression, I can choose L1 penalization from the penalty hyperparameter. Is my only option to build an ensemble with VotingClassifier to do this or is there an out-of-the-box ensemble classifier in sklearn that is known to produce sparse solutions?
A:
Yes, you can use a Logistic Regression model with L1 penalization as your ensemble classifier. We will call that your Level 1 Model. This will give a final predicted class probability for each sample. The features of this ensemble learner (Level 1) are essentially the predicted probabilities for every sample from each of your Level 0 models. In other words, each feature of the Level 1 learner is a model from Level 0. While performing CV training/test maintain the same fold assignments for each level to try and prevent overfitting. In addition, it is imperative while testing an ensemble learner to keep a validation set, or a hold out set, that the Level 0 and Level 1 models have never seen.
Not sure if there is an out of the box solution included with scikit-learn, but easy enough to write your own.
|
[
"stackoverflow",
"0010763808.txt"
] | Q:
SQL INSERT INTO select
Currently using a MySQL database
Wanting to insert a new row into a table (t_2) for every matching entry in my where condition of another table (t_1).
I also want to include a count value from a seperate table for each entry (count from table counter) and a string value 'decrease' for each entry. No idea how to put this through, this is what I have so far:
INSERT INTO t_2(count,id,val='decrease')
SELECT MAX(count) as count FROM counter
SELECT id FROM t_1 WHERE val < 0
the error I am getting is:
1064 - 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 '='decrease') SELECT count FROM counter SELECT id FROM t_1 WHERE val < 0' at line 1
I know I probably shouldn't have the val='decrease' but just wanted to illustrate I want that to be a string value inserted for each new row.
A:
Try this:
INSERT INTO t_2 (count,id,val)
SELECT
(SELECT MAX(count) FROM counter),
t1.id,
'decrease'
FROM t_1
WHERE val < 0,
A:
Is this what you're looking for?
INSERT INTO t_2(count,id,val)
SELECT (SELECT MAX(count) as count FROM counter) as count, id, 'decrease' as val
FROM t_1
WHERE val < 0
|
[
"stackoverflow",
"0016447442.txt"
] | Q:
How to access SharePoint files and folders from Win8?
I am developing a Win8 application that will interface with SharePoint (i.e. open, close, update documents).
How do I access the SharePoint files from Win8, using the Win8 Share Contract or any other method?
A:
You can use httpclient to call the rest servicrs exposed by sharepoint and consume the data. If you want to use csom you need to call csom functions from another dll and inclide the dll in your project. You cannot include csom libraries directly in store app.
Csom: client side object model
|
[
"stackoverflow",
"0011387391.txt"
] | Q:
how to call different jquery actions in responsive design
I'm at the point to convert my project into an responsive design.
What is the most handy and universal solution do you suggest to implement different jQuery-blocks for each breakpoint?
I want to keep all scripts in one file cause of number of http-requests.
That's what I've found:
breakpoint.js -> define all breakpoints doubled in CSS & JS
http://responsejs.com/ -> define breakpoints in body data-attr
OnMediaQuery -> define human-readable names for the breakpoints (IMHO better, cause you're not bound to pixels)
My problem is, they all define callbacks, but I don't know how to bind or cancel any jQuery event-listeners in these cases.
e.g. I have:
$('#selector').click( function() {
alert('selector clicked');
});
but that should only happen if in max-width of 320px.
In screen-sizes above that the click should return false or perform any other action
at the moment, I don't have a clue how to accomplish this.
A:
You can just create your own breakpoints in JS. Something like this. Adjust to your needs.
var isBreakPoint = function (bp) {
var bps = [320, 480, 768, 1024],
w = $(window).width(),
min, max
for (var i = 0, l = bps.length; i < l; i++) {
if (bps[i] === bp) {
min = bps[i-1] || 0
max = bps[i]
break
}
}
return w > min && w <= max
}
// Usage
if (isBreakPoint(480)) { ... } // Breakpoint between 320 and 480
A:
$('#selector').click(function() {
if (parseInt($(window).width()) < 320) {
...
}
});
|
[
"stackoverflow",
"0024633325.txt"
] | Q:
Rethrow Exception and Catch Again
I am using C# and wondered if it was possible to rethrow an exception from a try/catch and have a later catch statement recatch it?
try {
// 1. Try some operation
//Failed operations
// 2. Throw an exception
throw new IOException("I tried my best");
} catch(IOException) {
// 3. Try some specific recovery operation
//Failed operations
//4. Rethrow and try again
throw;
}
... Some more specific exception handlers
} catch(Exception) {
// 5. Re-caught here as a last-ditch effort, generic recovery operation
//Process here
} finally {
//...
}
A:
Only if your catch statement throws to another try/catch, for example:
try{
...
try{
...
}
catch(ExceptionA a)
{
throw;
}
catch(Exception e)
{
//will not not catch ExceptionA (rethrow or not)
}
}
catch(ExceptionA a)
{
//this would catch the re-throw
}
catch( Exception e)
{
}
Instead why don't you catch the general Exception and then case the exception types?
try{
...
}
catch(Exception e)
{
if (e is ExceptionA){
...
}
}
Or put logic on the finally
System.Exception thrownException = null;
try{
...
}
catch( ExceptionA a)
{
thrownException = a;
... // do special handling...
}
catch( ExceptionB b)
{
thrownException = b;
... // do special handling...
}
catch(Exception e)
{
...
}
finally{
if ( thrownException != null ) {
... //case the type here or use some other way to identify..
}
}
|
[
"stackoverflow",
"0030440127.txt"
] | Q:
Python Executable "Opened With..." (Windows)
I've made a little Python (3.x) script and compiled it to a *.exe file using Py2Exe.
What I would like is to click on a random file in explorer and "open it with..." (using the right mouse button) my executable. My program can then use the path of the selected file.
I know such information is typically passed into 'argv[...]', however, it is not working. I only get one argument, the full path of the .exe file.
For now the program only creates a *.txt file with all the passed arguments.
Could anyone help me out?
Thanks in advance.
The full code:
import sys
filename = "Test.txt"
file = open(filename, 'w')
file.write('Number of arguments: ' + str(len(sys.argv)) + ' arguments.\n')
file.write('Argument List: ' + str(sys.argv))
file.close()
A:
I now tried adding an input line at the end of my script to prevent it from closing instantly and I noticed an error in the panel: "ImportError: No module named 'ctypes'". Some searching showed this is a bug in py2exe: How to stop Python program compiled in py2exe from displaying ImportError: No Module names 'ctypes'
The mentioned solution solved the error and after rebuilding the *.exe passing in the file path works! So it was a py2exe bug all along...
|
[
"superuser",
"0000447528.txt"
] | Q:
Change default color of Firefox when opening links in a new tab
I'm using Stylish addon for Firefox with a default dark css. I also have changed the default Window colors in Windows registry. This has changed the about:blank page's color to a dark one. But when I open a link on a new tab, before the page loads, Firefox is showing a blank page with white background. I wonder how can I change this white color to a different one.
A:
Create a folder named "Chrome" in this location: C:\Users\[user]\AppData\Roaming\Mozilla\Firefox\Profiles\[profile]\chrome
and created an empty userChrome.css file with this line:
browser { background-color: #373739 !important; }
It worked fine for me.
|
[
"stackoverflow",
"0034538083.txt"
] | Q:
SSAS Multidimensional - Table Value Function as a Query for Partition
@GregGalloway was able to answer the question I should have asked. I am adding a more concise question here, while maintaining the original lengthy text
How do I use a table valued function as the query for a partition, when the function is in separate database from my fact and referenced dimensions?
Overview: I am building a SSAS multidimensional cube that is built off of a single fact table in our application's data warehouse, and want to use the result set from a table valued function as my fact table's partition query. We are using SQL Server (and SSAS) 2014
Condition: For each environment (Dev,Tst,Prd) there are 2 separate databases on the same server, one for the application data warehouse [DW_App], the other for custom objects [DW_Custom]. I cannot create any objects in [DW_App], but have a lot of freedom in [DW_Custom]
Background info: I have not been able to find much information on using a TVF and partitions in this way. My thinking is that it will help streamline future development by giving me a single place to update the SQL if/when I modify the fact table.
So in testing out my crazy idea of using a TVF as the query for my partitions I have run into a bit of a conundrum. I am able to use my TVF when I explicitly state the Database in my FROM clause.
SELECT * FROM [DW_Custom].[dbo].[CubePartition](@StartDate, @EndDate)
However, that will not work, because the cube will be deployed in multiple environments before production, and it needs to point to different DBs for each. So I tried adding a new data source, setting my partition query to point to the new data source, and then remove the database name. IE:
SELECT * FROM [dbo].[CubePartition](@StartDate, @EndDate)
I get an error that
The SQL syntax is not valid. The relational database returned the following error message: Deferred prepare could not be completed. Invalid object name 'dbo.CubePartition'
If I click through this error and the subsequent warnings about the cube not being able to process if I continue I am able to build and deploy the cube. However I cannot process it, because I get an error that one of my dimensions does not exist.
Looking into the query that was generated and it is clear that it is querying my dimensions as well as fact, which do not exist inside of '[DW_Custom]' which explains that error perfectly fine.
So I guess 2 questions:
Is it possible to query another DB (on the same server) from inside of an SSAS partition query?
If not, is there any way I can use a variable as the database name in the query, and update that variable based on the project configuration (Dev,Tst,Prd)
Bonus question: Is the reason that I can not find much about doing it this way because it is an obviously bad idea that I am overlooking, and if so why?
A:
How about creating a second SSAS Data Source pointing to the DW_Custom database (or whatever it's called in the particular environment you're deploying to)? Then when you deploy from Dev to Prod, you need only change that connection string. When you create your partitions, then specify the DW_Custom data source and then specify the query without database name:
SELECT * FROM [dbo].[CubePartition](@StartDate, @EndDate)
As long as the query plan for that table-valued function is efficient compared to a plain SELECT statement, then I don't see a problem with that.
|
[
"rpg.stackexchange",
"0000021687.txt"
] | Q:
Are my vassals ripping me off?
Consider the following points:
In ACKS, a character can only directly manage one domain, and the maximum size of a domain is fixed at 16 6-mile hexes. In order to control more land, a character has to assign management of additional domains to their henchmen.
A henchman managing a domain is normally expected to pay 20% of his domain's revenue in taxes to his lord, i.e.: the character who assigned him the task of managing the land.
Characters managing domains gain experience for the task, provided that the net income from the land exceeds their campaign experience threshold. The campaign experience threshold is dependent on the level of the character managing the domain; Thus, a low-level henchman assigned a domain will gradually increase in level until their income from the domain is less than their campaign experience threshold.
Henchmen must be paid a monthly salary commensurate with their level.
Individually, each of these points is straightforward, but together they confuse me, since they mean that a domain with a given income is liable to level a henchman until the salary owed to them exceeds the taxes they need to pay to their lord, meaning that they effectively keep more than 100% of their domain's income - and are charging their lord the extra.
For example, if I assign a henchman a domain that grants a monthly net income before taxes of 10,000 gp, that henchman will owe me 2,000 gp in taxes each month - but that same domain will level the henchman up to level 8, at which point their monthly salary will be 3,000 gp.
I strongly suspect I'm missing something. I think it might be that henchmen who manage domains take domain income in lieu of a salary, but I can't find anything in the rules to confirm my guess. (Or am I wrong, and the game requires me to run some sort of pyramid scheme in order to stay in the black?) Could anyone clear this up for me?
A:
Once a henchman is given a domain, they're no longer a henchman, they're a vassal.
Think about it this way. Ser John the Great gives his loyal spear-carrier Walden a title over the Barony of Thicke. Lord Walden of Thicke becomes a peer of another Baron who was never Ser John's henchman, Baron Gwynedd. Baron Gwynedd has income, land, peasants, and all kinds of nice stuff… and then sees that Baron Thicke, his equal is being paid an additional 1000 gold pieces every month! It's an outrage! A slight against his worth and honor! It's… base bribery being paid to Baron Thicke! And What is he being bribed to do, or not do? Perhaps treachery lies ahead and action must be taken to keep my land and title…
Does that sound like a stable feudal realm? No, it does not.
When a henchman is given a domain, they gain a different relationship with their lord. They owe allegiance, but it is not absolute. They owe taxes, but only as much as is reasonable. Their land is theirs and does not belong to their lord any longer – it has been given to them at the price of vassalage, not rented to them – that's just stewardship. Giving someone an actual title and lands means it is theirs now. Paying them to be your vassal is either redundant, or is a bribe for something.
At which point, sure, you can continue to buy their loyalty, but bribes don't make for loyalty to you, only your gold, and it can cause envy between your vassals and resentment to you from those you've overlooked with your largess.
Henchmen are paid in exchange for their coming on adventures. Vassals are given title and lands in exchange for being bound by duty to pay taxes, and to raise their levies when you call them to battle. In one you are their employer, and the other you are their lord. A lord does not buy their vassals with gold, but rather attempts to ensure their loyalty with titles, honour, prestige, justice in their quarrels with your other vassals, and respecting their own lordship over their domain.
This is one of those things that isn't said in the book, because it's overlooked and assumed to be just common knowledge. ACKS gives you rules for running a feudal system, but it doesn't walk you through all the nuts and bolts of what feudalism is and how it works, just like it doesn't explain that a sword is a pointy bit of metal and a club is a length of sturdy wood. Every game has to assume a huge range of things to be known by the players, and in ACKS the incompatibility with being a paid henchman and being a landed, titled vassal is one of them. Granted, it's probably something that should have been explained because it touches so closely on how to use the rules presented, but it's not a fatal oversight. If one has enough background on the real-world system the rules are modelling, the moment someone wonders at the same thing you did, the very fact that it would be a problem if it worked that way provides, all by itself, the answer that it probably isn't supposed to work that way.
A:
Vasals probably do not get paid a fee. It doesn't say this, but does say they pay the liege.
Note that the example on page 146 does not show Vassals as an expense, only as income.
However, also note that the GP Threshold is almost always higher than the fee for the current level. If the character levels up, he's below the cap, and perhaps below his fee, but he's not levelling up again until he's making more than his own current "fee"...
Lv HF GPT
1 25 25
2 50 75
3 100 150
4 200 300
5 400 650
6 800 1,250
7 1,600 2,500
8 3,000 5,000
9 7,250 12,000
10 12,000 18,000
11 35,000 40,000
12 60,000 60,000
13 145,000 150,000
14 350,000 425,000
|
[
"stackoverflow",
"0047184507.txt"
] | Q:
Groupby and weighted average
I have a data frame:
import pandas as pd
import numpy as np
df=pd.DataFrame.from_items([('STAND_ID',[1,1,2,3,3,3]),('Species',['Conifer','Broadleaves','Conifer','Broadleaves','Conifer','Conifer']),
('Height',[20,19,13,24,25,18]),('Stems',[1500,2000,1000,1200,1700,1000]),('Volume',[200,100,300,50,100,10])])
STAND_ID Species Height Stems Volume
0 1 Conifer 20 1500 200
1 1 Broadleaves 19 2000 100
2 2 Conifer 13 1000 300
3 3 Broadleaves 24 1200 50
4 3 Conifer 25 1700 100
5 3 Conifer 18 1000 10
I want to group by STAND_ID and Species, apply a weighted mean on Height and Stems with Volume as weight and unstack.
So i try:
newdf=df.groupby(['STAND_ID','Species']).agg({'Height':lambda x: np.average(x['Height'],weights=x['Volume']),
'Stems':lambda x: np.average(x['Stems'],weights=x['Volume'])}).unstack()
Which give me error:
builtins.KeyError: 'Height'
How can i fix this?
A:
Your error is because you can not do multiple series/column operations using agg. Agg takes one series/column as a time. Let's use apply and pd.concat.
g = df.groupby(['STAND_ID','Species'])
newdf = pd.concat([g.apply(lambda x: np.average(x['Height'],weights=x['Volume'])),
g.apply(lambda x: np.average(x['Stems'],weights=x['Volume']))],
axis=1, keys=['Height','Stems']).unstack()
Edit a better solution:
g = df.groupby(['STAND_ID','Species'])
newdf = g.apply(lambda x: pd.Series([np.average(x['Height'], weights=x['Volume']),
np.average(x['Stems'],weights=x['Volume'])],
index=['Height','Stems'])).unstack()
Output:
Height Stems
Species Broadleaves Conifer Broadleaves Conifer
STAND_ID
1 19.0 20.000000 2000.0 1500.000000
2 NaN 13.000000 NaN 1000.000000
3 24.0 24.363636 1200.0 1636.363636
|
[
"computergraphics.stackexchange",
"0000000421.txt"
] | Q:
Ray Tracing with Cones: coverage, overlapping and abutting triangles
In his classic paper Ray Tracing with Cones, John Amanatides describes a variation on classical ray tracing. By extending the concept of a ray by an aperture angle, making it a cone, aliasing effects (including those originating from too few Monte Carlo samples) can be reduced.
During cone-triangle intersection, a scalar coverage value is calculated. This value represents the fraction of the cone that is covered by the triangle. If it is less than $1$, it means that the triangle doesn't fully cover the cone. Further tests are required. Without the usage of more advanced techniques however, we only know how much of the cone is covered, but not which parts.
Amanatides states:
Since at present only the fractional coverage value is used in mixing
the contributions from the various objects, overlapping surfaces will
be calculated correctly but abutting surfaces will not.
This does not make sense to me. From my point of view it is the other way around. Let's take an example: We have two abutting triangles, a green and a blue one, each of which covers exactly 50% of our cone. They are at the same distance from the viewer.
The green triangle is tested first. It has a coverage value of 0.5, so the blue triangle is tested next. With the blue one's coverage value of 0.5 our cone is fully covered, so we're done and end up with a 50:50 green-blue mixture. Great!
Now imagine that we kill the blue triangle and add a red one some distance behind the green one - overlapping. Greeny gives us a coverage value of 0.5 again. Since we don't have the blue one to test anymore we look further down the cone and soon find the red one. This too returns some coverage value greater than 0, which it shouldn't because it is behind the green one.
So, from this I conclude that abutting triangles work fine, while overlapping triangles would need some more magic like coverage masks to be correct. This is the opposite of what Amanatides says. Did I misunderstand something or is this a slip in the paper?
A:
I did implement a ray tracer based on Amantides' work but, as that was years ago, my memory of the paper is a little rusty.
However, ignoring this particular case, in general when it comes to working with fractional coverage e.g. Alpha compositing, (see "A over B") my understanding is that the usual assumption is that the items being composited are uncorrelated.
Thus if A with X% coverage is on top of B with Y% coverage and C in the background, then it's assumed that one will see
X%*A + (100-X%)*Y% * B + (100-X%)(100-Y%)*C
Does that make sense? Obviously this will give "leaks" in the case where A and B are strongly correlated.
I think I might have put a small bit mask on the rays to avoid these problems, but it was a very long time ago.
|
[
"stackoverflow",
"0048283886.txt"
] | Q:
Python type-hinting, indexable object
My function needs to accept an object, from which data can be extracted by index, viz. a List or an instance with defined __getitem__ method.
Which type can I use for type hinting this argument?
Update:
As I understand there are presently no such type, I tried to make one myself:
class IndexableContainer(Generic[int, ReturnType]):
def __getitem__(self, key: int) -> ReturnType:
...
But I get the following error:
File "indexable_container.py", line 22, in IndexableContainer
class IndexableContainer(Generic[int, ReturnType]):
File ".../lib/python3.6/typing.py", line 682, in inner
return func(*args, **kwds)
File ".../lib/python3.6/typing.py", line 1112, in __getitem__
"Parameters to Generic[...] must all be type variables")
TypeError: Parameters to Generic[...] must all be type variables
How should I do it?
A:
There are several different ways you can do this.
If you're ok with using only custom classes (that you can write) as indexable containers, all you need to do is to adapt your code and remove that 'int' type parameter:
class IndexableContainer(Generic[ReturnType]):
def __getitem__(self, key: int) -> ReturnType:
...
class MyCustomContainer(IndexableContainer[ReturnType]):
def __getitem__(self, key: int) -> ReturnType:
# Implementation here
def requires_indexable_container(container: IndexableContainer[ReturnType]) -> ReturnType:
# Code using container here
The issue is, of course, that if you wanted to pass in a plain old list into the function, you wouldn't be able to do so since list doesn't subclass your custom type.
We could maybe special-case certain inputs via clever use of the @overload decorator and unions, but there's a second, albeit experimental, way of doing this known as Protocols.
Protocols basically let you express "duck typing" in a sane way using type hints: the basic idea is that we can tweak IndexableContainer to become a protocol. Now, any object that implements the __getitem__ method with the appropriate signature is counted as a valid IndexableContainer, whether or not they subclass that type or not.
The only caveat is that Protocols are currently experimental and (afaik) only supported by mypy. The plan is to eventually add protocols to the general Python ecosystem -- see PEP 544 for the specific proposal -- but I haven't kept track of the discussion/don't know what the status of that is.
In any case, to use protocols, install the typing_extensions module using pip. Then, you can do the following:
from typing_extensions import Protocol
# ...snip...
class IndexableContainer(Protocol, Generic[ReturnType]):
def __getitem__(self, key: int) -> ReturnType:
...
def requires_indexable_container_of_str(container: IndexableContainer[str]) -> None:
print(container[0] + "a")
a = ["a", "b", "c"]
b = {0: "foo", 2: "bar"}
c = "abc"
d = [1, 2, 3]
# Type-checks
requires_indexable_container_of_str(a)
requires_indexable_container_of_str(b)
requires_indexable_container_of_str(c)
# Doesn't type-check
requires_indexable_container_of_str(d)
A:
It seems that the closest we can get is:
Mapping[int, Any]
Although it's not quite what I wanted, it's close enough.
|
[
"serverfault",
"0000314094.txt"
] | Q:
Can Apache generate W3C extended format access logs, identical to IIS?
Is is possible to configure Apache to reliably generate access logs in W3C extended format idential to that generated by IIS? I can't seem to track down a detailed description of specifics like delimiters, field formats, etc. No doubt there is an apache log format string that can do it, but I don't have enough info to create or even know for sure if it can write the data in the correct format.
I am using a web access log analyzer (SmarterStats) that does not support custom log file formats - it only supports Common Log Format, or W3C extended format. Unfortunately CLF has only very limited data, so doesn't allow particularly interesting analysis.
A:
The W3C Extended Log File Format lets you define a set of fields in metadata at the top of the log. The defaults for IIS 6 seem to be:
#Fields: date time c-ip cs-username s-ip s-port cs-method cs-uri-stem cs-uri-query sc-status cs(User-Agent)
You should check your IIS log to see that this is the case (and what your parser expects) - look for the #Fields line at the top.
You can generate an Apache log in this format using a LogFormat line something like this:
LogFormat "%{%Y-%m-%d %H:%M:%S}t %a %u %A %p %m %U %q %>s \"%{User-agent}i\"" w3c_extended
CustomLog /var/log/apache2/extended_access_log w3c_extended
(I can't test this at present: please edit the post or comment if you try it).
Check Apache's custom log formats to see how I derived that.
|
[
"stackoverflow",
"0059741084.txt"
] | Q:
Calling a singular Logic app from multiple steps in a pipeline
I have created an ADF pipeline which has several components to in it; execute a stored procedure, perform a copy data task. There are 14 in total (7 pair) and I want to trigger a failure that will send out an email with the error message.
I've gone and created a logic app to send an email as described in this link
http://microsoft-bitools.blogspot.com/2018/03/add-email-notification-in-azure-data.html
In the 'Web Activity' component-> Settings-> Body, I have the following:
"DataFactoryName":
"@{pipeline().DataFactory}",
"PipelineName":
"@{pipeline().Pipeline}",
"ErrorMessage":
"@{activity('Execute Package').error.message}",
"EmailTo":
"@{pipeline().parameters.EmailTo}"
}
The 'Execute Package' is the name of the Stored Procedure or Copy Data activity.
The problem is that it only works for the named activity 'Execute Package'. I haven't been able to find anywhere that it can dynamically get where it is coming from.
Is there any way to just have a singular web activity? I don't want to create 14 more things in my pipeline each to handle a different possible failure.
The call to SendCompletionEmail works fine with the logic app since only one thing is calling it.
A:
I'd like to take a moment to point out that after solving the immediate issue (how to get the error out of multiple sources), there is another issue you will face: The FailureSendEmail activity will not run when you expect.
First issue (how to get error of whichever is failing):
Assuming that your pipeline is linear, and you only expect one activity to fail, and all subsequent to not run, I recommend you use the coalesce function. Coalesce grabs the first non-null argument. Here is an example I worked out using 2 stored procs:
@string(coalesce(activity('Stored Procedure1').Error,activity('Stored Procedure2').Error))
Coalesce takes an arbitrary number of arguments, so you can expand this as you like.
The other issue is all the 'on failure' connections. While what you built makes sense, please let me explain. When an activity has multiple dependency connections coming into it, it will not execute unless all the dependencies report in. These are AND'ed, not OR'ed.
Fortunately, you do not need a direct connection in order to reference the activity outputs/errors. An indirect connection is all you need. If your pipeline logic is linear, then you already have this. Remove all the lines going into FailureSendEmail. Then add an 'on failure' and a 'skipped' dependency connection from your last 'Copy Data' activity. The logic goes like this:
Assuming all the activities in your 'happy path' are connected by success dependencies,
If one activity fails early in the pipeline, then the subsequent activities are skipped. This fulfills the skipped dependency.
If the last copy activity fails, this fulfills the failure dependency.
|
[
"opensource.stackexchange",
"0000000990.txt"
] | Q:
How can I get my program into a Linux distribution (Debian)?
Assume I have programmed a cool application and released it as open source. But not many people are using it, as most install their programs through their distribution of choice.
Can I somehow add my program to a distribution, specifically Debian? What have I to do to be accepted?
You can assume Debian in all cases this is different between distributions in your answer. So you can explain this specific to Debian, but I would like it, if it is mentioned which part is general for all/most distributions.
A:
For Debian you can proceed as follows:
Post an Intent to Package (ITP) bug report to the Debian Bug
Tracking system (https://www.debian.org/Bugs/). Or if an existing
RFP (Request for Packaging) bug report for the software already
exists, you can assign it to yourself.
Create the packaging for the software.
Upload the software and the packaging to http://mentors.debian.net/.
Wait for a sponsor (a Debian Developer who is interested in
uploading your package to Debian) to show up and people (mentors) to
critique your packaging. Possibly also post to the debian-mentors
mailing list about your package.
Improve your packaging to the point that a sponsor is willing to
upload it to the Debian NEW queue. If such a person doesn't show up
within a certain period of time, you are out of luck, but can try
again later. Note that your package will eventually be automatically
removed from http://mentors.debian.net/.
If a sponsor has uploaded it to the Debian NEW queue, wait and see
if the FTP masters, who are Debian's gatekeepers, accept or reject
your package. If they reject it they will normally give a reason,
and you can try to fix the package and resubmit it.
If you happen to know a Debian developer who is willing to upload your package for you, you can skip steps 3 and 4. Note also that the #debian-mentors IRC channel on OFTC is a useful resource for packaging help.
A:
@FaheemMitha already gave a perfect answer for Debian, but I wanted to add the process for Ubuntu. If a package is included in Debian, it will automatically be included in Ubuntu shortly down the road:
Ubuntu regularly incorporates source packages from Debian, so it is encouraged to upload a package to Debian first to automatically have it in Ubuntu in due time. In addition to that your package will reach a much broader audience if it is in Debian and all of its derivatives.
You are also recommended to file a bug with Ubuntu's LaunchPad to move the process along faster.
Packages that have recently been added to Debian unstable will be automatically synced into Ubuntu prior to the Debian Import Freeze (DIF). After the Debian Import Freeze, you will have to file a bug with the summary field "Please sync from debian " where is the package you would like to see. Find the date for Debian Import Freeze on the release schedule page.
Fedora's process also involves filing a ticket. For CentOS, the process is here and is done primarily through a mailing list.
For OpenSUSE, see this guide.
Amazon does not seem to provide a guide for Amazon Linux, but getting it into CentOS and Fedora should get Amazon to pick it up after a while.
Last but not least, don't forget about FreeBSD (and NetBSD, and OpenBSD)!
|
[
"stackoverflow",
"0013500753.txt"
] | Q:
How to enter date/time for the datatype XMLGregorianCalendar
Possible Duplicate:
java.util.Date to XMLGregorianCalendar
I have a Java method with a parameter from the type XMLGregorianCalendar, but I don't know how to set Date/Time:
XMLGregorianCalendar startDateTime = ???
Thank you very much, for helping...
A:
import javax.xml.datatype.DatatypeFactory;
// ...
XMLGregorianCalendar xc = DatatypeFactory.newInstance().newXMLGregorianCalendar(
int year,
int month,
int day,
int hour,
int minute,
int second,
int millisecond,
int timezone)
there are other versions of newXMLGregorianCalendar(), eg newXMLGregorianCalendar(GregorianCalendar cal).
|
[
"stackoverflow",
"0058318927.txt"
] | Q:
Code for calculating the perimeter of any polygon using classes (python)
So i have here my main program (which i absolutely can't make any changes because this is how our instructor wants it to be run):
from class_point import Point
from class_polygon import Polygon
pt1 = Point(0,0)
pt2 = Point(0,4)
pt3 = Point(3,0)
polygon1 = Polygon([pt1,pt2,pt3]) #yes, the class Polygon will be initialized using a list
print(polygon1.get_perimeter())
So basically, i have two separate files containing the definitions of class Polygon and class Point.
This is my code for class Point which has the function for calculating the distance between two given points:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, second):
x_d = self.x - second.x
y_d = self.y - second.y
return (x_d**2 + y_d**2) **0.5
And this is my code for class Polygon which will use the defined points and the distance function to calculate the perimeter of my polygon:
class Polygon():
def __init__(self, points):
self.points = points
def __len__(self):
len_points = len(self.points)
return len_points
def get_perimeter(self,points,len_points):
perimeter = 0
for i in range(0, len_points):
pt1 = self.points[i]
pt2 = self.points[i+1]
perimeter += pt1.distance(pt2)
if i + 1 == len_points:
perimeter += points[-1].distance(points[0])
else:
continue
return perimeter
But whenever i try to run the code, i get the error:
File "C:/Users/Dust/Desktop/polygon_trial.py", line 8, in <module>
print(polygon1.get_perimeter())
TypeError: get_perimeter() missing 2 required positional arguments: 'points' and 'len_points'
A:
This should work
class Polygon():
def __init__(self, points):
self.points = points
def __len__(self):
return len(self.points)
def get_perimeter(self):
perimeter = 0
for i in range(0, len(self.points)):
pt1 = self.points[i]
pt2 = self.points[i+1]
perimeter += pt1.distance(pt2)
if i + 1 == len(self.points):
perimeter += self.points[-1].distance(self.points[0])
else:
continue
return perimeter
|
[
"stackoverflow",
"0060466712.txt"
] | Q:
Change color in specific columns w/ multiple series
I have two series each with its color and I want to be able to define a different color for both series in a specific column.
How can I display the first 3 columns in grey? https://jsfiddle.net/Kagebi/omcqrzsu/
Highcharts.chart('container', {
chart: {
type: 'column',
},
plotOptions: {
column: {
grouping: false
}
},
tooltip: {
shared: true // true breaks series highliting on hover
},
xAxis: {
categories: ['24-02', '25-02', '26-02', '27-02', '28-02', '29-02', '01-03', '02-03', '03-03', '04-03', '05-03']
},
series: [
{
name: 'Expected',
data: [180, 140, 180, 140, 180, 140, 180, 140, 180, 140, 180],
color: '#b2dbff',
},
{
name: 'Current',
data: [99, 197, 165, 80, 144, 80, 144, 80, 144, 80, 144],
color: '#1d94fa'}
],
events:{
load: function() {
var point = this.series[0].points[1];
point.update({
color: 'black'
});
}
},
}
)
A:
You can specify the color of each entry in a serie like that:
data: [{
name: 'Point 1',
color: '#00FF00',
y: 0
}, {
name: 'Point 2',
color: '#FF00FF',
y: 5
}]
See the documentation here : https://www.highcharts.com/docs/chart-concepts/series (point n°3).
I've updated your jsfiddle here with the first three columns in grey: https://jsfiddle.net/0mhnck5L/
|
[
"stackoverflow",
"0001925438.txt"
] | Q:
What do $this->escape() in zend framework actually do?
I need help in understanding the actual actions of a helper function in Zend Framework.
I need someone to explain to me what $this->escape($string) actually does to the string passed to it before printing the string into the template.
A:
$this->escape() escapes a string according to settings you can provide with $this->setEscape('functionname'), by default it is PHP's htmlspecialchars function.
http://framework.zend.com/manual/en/zend.view.scripts.html
A:
It calls the htmlspecialchars PHP function.
The translations performed are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"'
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
|
[
"stackoverflow",
"0046772237.txt"
] | Q:
What will be the heapdump size if I set the Max Heap size = 2 Gb?
I have set my max heap size to 2 GB on my Websphere server console. I want to know what will be size of my heapdump files created during Out of Memory errors. Will they be greater than 2GB or equal to 2GB or less than 2GB?
A:
It depends on the type of the dump. Accordingly with the article provided by IBM:
1) PHD dump takes about 20 percent of Java heap size
2) HPROF dump takes about the same as Java heap size
3) IBM system dumps - about Java heap size + 30 percent
Source: https://www.ibm.com/developerworks/library/j-memoryanalyzer/
Normally you will get PHD with Javacore on OutOfMemoryError, so you can expect it to be about 20% of heap. But you have to keep in mind that OutOfMemoryError could be thrown several times within rather short timeframe, so several dumps could be created.
|
[
"mathematica.stackexchange",
"0000002519.txt"
] | Q:
How do I call a 32-bit DLL using .NET/Link and a 64-bit version of Mathematica?
The .NET/Link tutorial shows how to call functions defined in DLLs. The example uses the GetTickCount Win32 API function
<< NetLink`
InstallNET[]
getTickCount = DefineDLLFunction["GetTickCount", "kernel32.dll", "int", {}]
getTickCount[]
(* ==> 91226108 *)
Unfortunately this does not work by default when usign a 64-bit version of Mathematica to call a function defined in a 32-bit DLL. Let's use the 32-bit version of kernel32.dll to test:
getTickCount =
DefineDLLFunction["GetTickCount", "c:\\windows\\SysWOW64\\kernel32.dll", "int", {}]
getTickCount[]
NET::netexcptn: A .NET exception occurred: System.BadImageFormatException:
An attempt was made to load a program with an incorrect format.
(Exception from HRESULT: 0x8007000B)
at Wolfram.NETLink.DynamicDLLNamespace.DLLWrapper15.GetTickCount().
How can I call a 32-bit DLL from a 64-bit Mathematica?
A:
The solution is forcing .NET/Link to load its 32-bit executable instead of the 64-bit one. Since Mathematica communicated with the .NET/Link process through MathLink, it does not matter if the Mathematica kernel is 64 bit and the .NET/Link executable is a 32 bit version. They are separate processes. However, the .NET/Link executable must match the DLL that is being loaded.
There is an undocumented option to force loading the 32-bit version of .NET/Link:
UninstallNET[]
InstallNET["Force32Bit" -> True]
Now 32-bit DLLs can be loaded through .NET/Link, but 64-bit ones cannot.
A:
Or simply use
ReinstallNET["Force32Bit" -> True]
which is a convenience function that calls
UninstallNET[]
InstallNET["Force32Bit" -> True]
|
[
"stackoverflow",
"0030627371.txt"
] | Q:
Unable to initialize class variables using LINQ to XML
I have large XML file that contains many node & sub node.
I am trying to get particular details & save it.
I paste code as follows.
XML is
<?xml version="1.0"?>
<CLabelContainer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Labels>
<LabelList>
<CLabel>
<VehicleLabel>
<ImageName>image1.bmp</ImageName>
<BoundingRect>
<X>433</X>
<Y>205</Y>
<Width>39</Width>
<Height>42</Height>
</BoundingRect>
</VehicleLabel>
</CLabel>
.
& So on...
.
<CLabel>
<VehicleLabel>
<ImageName>image20.bmp</ImageName>
<BoundingRect>
<X>425</X>
<Y>305</Y>
<Width>30</Width>
<Height>46</Height>
</BoundingRect>
</VehicleLabel>
</CLabel>
</LabelList>
</Labels>
</CLabelContainer>
Here is target XML
class cROI
{
public Int16 iX { get; set; }
public Int16 iY { get; set; }
public Int16 iWidth { get; set; }
public Int16 iHeight { get; set; }
public cROI(Int16 iX, Int16 iY, Int16 iWidth, Int16 iHeight)
{
this.iX = iX;
this.iY = iY;
this.iWidth = iWidth;
this.iHeight = iHeight;
Console.WriteLine("{3}, {1}, {2}, {0}", this.iX, this.iY, this.iWidth, this.iHeight);
}
public cROI()
{
// TODO: Complete member initialization
}
}
LINQ to XML in main function.....
class Program
{
static void Main(string[] args)
{
XDocument xXmlDoc = XDocument.Load("C:/Users/User1/Desktop/abc.xml");
var m_cROI = from ROI in xXmlDoc.Descendants("CLabelContainer") select new cROI
{
iX = Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("X").Value),
iY = Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("Y").Value),
iWidth = Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("iWidth").Value),
iHeight = Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("iHeight").Value),
};
I get no output. (Press any key to continue....)
Note : is it possible to create a list of cROI & fill all 20 image bounding rectangle elements ?? Above, as test purpose, i am trying with one element only.
Edit : I tried to call with parameterised constructor, instead of " select new ROI {....}", "Select new ROI( {....} )". No result
A:
You are calling the parameterless constructor of the cRoi class, and using property initializers to populate the class. This way, you won't hit the Console.WriteLine code in the constructor that takes parameters.
To call the constructor, use this syntax
var m_cROI = from ROI in xXmlDoc.Descendants("CLabelContainer") select new cROI
(
iX = Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("X").Value),
iY = Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("Y").Value),
iWidth = Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("iWidth").Value),
iHeight = Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("iHeight").Value),
);
You could remove the parameterless constructor to avoid making the same mistake again. This way, the compiler will complain if you try to use it.
A:
You are expecting to see the Console.WriteLine(... output from the public cROI(Int16 iX, Int16 iY, Int16 iWidth, Int16 iHeight) constructor, but you are not, for the following reasons:
You are not calling this constructor. Instead, you are calling the parameterless constructor, then filling in the properties with an object initializer.
Linq queries are lazy. Thus results are not actually evaluated until requested.
You have the wrong names for the width and height elements in the XML. They are <Width>30</Width> and <Height>46</Height> whereas your code expects <iWidth>30</iWidth> and <iHeight>46</iHeight>. (With the wrong names, your code will throw a NullReferenceException.)
Putting these together, the following should produce the console output you expect:
var m_cROI = from ROI in xXmlDoc.Descendants("CLabelContainer")
select new cROI
( // Use the explicit constructor
Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("X").Value),
Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("Y").Value),
Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("Width").Value),
Int16.Parse(ROI.Element("Labels").Element("LabelList").Element("CLabel").Element("VehicleLabel").Element("BoundingRect").Element("Height").Value)
);
var result = m_cROI.ToList(); // Actually evaluate the query.
Update
To get all VehicleLabel bounding rectangles, you can use XPathSelectElements to find all BoundingRect nodes.
if CLabelContainer is the root document node (which it is in your example), then the most efficient query would be:
var query = from rect in xXmlDoc.XPathSelectElements("/CLabelContainer/Labels/LabelList/CLabel/VehicleLabel/BoundingRect")
select new cROI
(
Int16.Parse(rect.Element("X").Value, NumberFormatInfo.InvariantInfo),
Int16.Parse(rect.Element("Y").Value, NumberFormatInfo.InvariantInfo),
Int16.Parse(rect.Element("Width").Value, NumberFormatInfo.InvariantInfo),
Int16.Parse(rect.Element("Height").Value, NumberFormatInfo.InvariantInfo)
);
var AllBoundingRect = query.ToList();
if CLabelContainer is not the root document node, you can do:
var query = from rect in xXmlDoc.XPathSelectElements("//CLabelContainer/Labels/LabelList/CLabel/VehicleLabel/BoundingRect")
select new cROI
(
Int16.Parse(rect.Element("X").Value, NumberFormatInfo.InvariantInfo),
Int16.Parse(rect.Element("Y").Value, NumberFormatInfo.InvariantInfo),
Int16.Parse(rect.Element("Width").Value, NumberFormatInfo.InvariantInfo),
Int16.Parse(rect.Element("Height").Value, NumberFormatInfo.InvariantInfo)
);
var AllBoundingRect = query.ToList();
Where the "//" string means "search recursively throughout the document for the following chain of nodes". It is equivalent to:
var query = from rect in xXmlDoc.Descendants("CLabelContainer").Elements("Labels").Elements("LabelList").Elements("CLabel").Elements("VehicleLabel").Elements("BoundingRect")
select new cROI
(
Int16.Parse(rect.Element("X").Value, NumberFormatInfo.InvariantInfo),
Int16.Parse(rect.Element("Y").Value, NumberFormatInfo.InvariantInfo),
Int16.Parse(rect.Element("Width").Value, NumberFormatInfo.InvariantInfo),
Int16.Parse(rect.Element("Height").Value, NumberFormatInfo.InvariantInfo)
);
var AllBoundingRect = query.ToList();
Note I am parsing the numbers using the invariant culture (i.e. not localized to a specific language or country) which is almost always the correct way to parse data exchange files such as XML.
|
[
"magento.stackexchange",
"0000010906.txt"
] | Q:
how to upgrade magento enterprise edition
How to upgrade magento enterprise edition. Unlike community edition enterprise edition does not have facility to upgrade from one version to another version using from Magento Connect. In Magento community edition we can upgrade from one version to newer version using magento connect and check for updates. If any updates found we simply check those modules and go for update.
In Enterprise edition if I choose check for updates in magento connect, nothing is coming out even though newer version is available.
So please let me know how to upgrade magento enterprise edition from older version to newer version.
Thanks in advance
A:
Copy the files in-place over top of your local development server's copy. Hopefully you're using version control software so you can commit your changes for deployment at a later date after your testing phase.
On Linux:
cp -R ./Magento_Enterprise_1.13.1.0/ /var/www/vhosts/yourmagentoinstalllocation/webroot
On Mac OSX
This is a little trickier because the target will be replaced entirely, no merging will happen. Because of this, instead of using CP, use Ditto:
ditto ./Magento_Enterprise_1.13.1.0/ /var/www/vhosts/yourmagentoinstalllocation/webroot
On PC just copy and paste over top, choosing to replace duplicate filenames.
Upgrading to EE 1.13+
You will need to prepare your URLs prior to upgrade, and there are various tools provided to do this. You can download those toolkits from the Magento Partner portal and run against your database in-place. Obviously before you do any of the above you should backup and test your backup to ensure the safety of your installation.
http://www.magentocommerce.com/knowledge-base/entry/ee113-later-release-notes#ee113-11302-patches
|
[
"stackoverflow",
"0038894488.txt"
] | Q:
Dropping 'nan' with Pearson's r in scipy/pandas
Quick question: Is there a way to use 'dropna' with the Pearson's r function in scipy? I'm using it in conjunction with pandas, and some of my data has holes in it. I know you used to be able suppress 'nan' with Spearman's r in older versions of scipy, but that functionality is now missing.
To my mind, this seems like a disimprovement, so I wonder if I'm missing something obvious.
My code:
for i in range(len(frame3.columns)):
correlation.append(sp.pearsonr(frame3.iloc[ :,i], control['CONTROL']))
A:
You can use np.isnan like this:
for i in range(len(frame3.columns)):
x, y = frame3.iloc[ :,i].values, control['CONTROL'].values
nas = np.logical_or(x.isnan(), y.isnan())
corr = sp.pearsonr(x[~nas], y[~nas])
correlation.append(corr)
|
[
"stackoverflow",
"0055418108.txt"
] | Q:
How to stop python printing more than one line?
I have a small function to check if a number is prime or not. It works fine apart from one small detail - it prints out more than one print line on the program end.
n = int(input("Enter a number to find if it is prime: "))
def is_prime():
for i in range(2, n):
if n % i == 0:
print("Not prime")
break
else:
print("The number {} is prime".format(n))
is_prime()
If I enter the number 2 for e.g. when the program runs, it prints:
the number 2 is prime
the number 2 is prime
the number 2 is prime
It only needs to print the line once, so why is this?
A:
Your else is in the wrong position. You have it on the if, but you actually want it on the for.
It might not be well known, but you can have a else on for-loops and it will execute if no break was executed during the loops.
n = int(input("Enter a number to find if it is prime: "))
def is_prime():
for i in range(2, n):
if n % i == 0:
print("Not prime")
break
else:
print("The number {} is prime".format(n))
is_prime()
|
[
"stackoverflow",
"0006415067.txt"
] | Q:
Is there a maximum length for json in Java?
I'm getting an output of the classes that students saw through all the university career.
this is an example of the output
{
"HISTORICOP": [
{
"MATERIA": "PROCESOS DEL LENGUAJE ",
"NOTA": "7 ",
"ANIO": "2000",
"PERIODO": "001",
"ENEMENOSUNO": "0 "
},
{
"MATERIA": "RAZONAMIENTO BASICO FG ",
"NOTA": "13 ",
"ANIO": "2000",
"PERIODO": "001",
"ENEMENOSUNO": "0 "
},
{
"MATERIA": "DESARROLLO DE COMPETENCIAS ",
"NOTA": "8 ",
"ANIO": "2000",
"PERIODO": "001",
"ENEMENOSUNO": "n-1 "
}
]
}
these are 3 of the results
but the whole output are 91 results,
when I run it on a emulator the blackberry is not able to read it
but when I try with less results he can read it!
Is there a maximum json length size so it can be read in java?
this is how I retrieve the info! from SAP
try {
$conn = new sapnwrfc($config);
$fds = $conn->function_lookup("ZCM_GET_HORARIO");
$parms = array('CEDULA' => '16814224');
$results = $fds->invoke($parms);
echo "[".json_encode($results)."]";
$conn->close();
} catch (Exception $e) {
echo "Connection Failed 3";
}
A:
There is no absolute limitation in JSON. In Java there is a limit to the length of a String, which is 2^31-1 or over 2 billion characters long. But given the snippet of code you showed us you are not actually using Java (Java doesn't have "$" before variable names).
There may be a limitation in whatever library you are using which is not a fundamental limitation of the data format or the language.
But if you are having problems with just 91 items (not 91 thousand or 91 million) then it is far more likely that you problem is NOT due to a fundamental size limitation. If you post more about what actual errors you saw you might get a more useful response.
|
[
"stackoverflow",
"0053756605.txt"
] | Q:
Android Workmanger PeriodicWorkRequest API work only once?
Am Using androidx Work manager API, in Work manager am using PeriodicWorkRequest to trigger the Work for every 4 hours. But it works only once after run the application.
PeriodicWorkRequest Coding:-
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
PeriodicWorkRequestpendingCampaignWork = new PeriodicWorkRequest.Builder(PendingCampaignWorker.class, 4, TimeUnit.HOURS)
.setConstraints(constraints)
.build();
Work Manger Code to Enqueue the Request:-
WorkManager.getInstance().enqueueUniquePeriodicWork(LATEST_CAMPAIGN_WORK, ExistingPeriodicWorkPolicy.KEEP, pendingCampaignWork);
For testing am change System time Manually to 4 hours after run the application in emulator to trigger the Work.
Is there any issue in my code help me to solve the issue.
Update:-
Work Manager is working fine, its not working based on System time as m.hassan said in answer section. Am test to trigger the work for every 20 minutes, its working fine.
A:
Work Manager Not not based on system time. You can make a periodic work request of 15 minutes. This way you can test your code.
here's an example:
My Periodic Work Request:
private static final String TAG = "PeriodicWorkTag";
private static final int PERIODIC_WORK_INTERVAL = 15;
public static void schedulePeriodicWork() {
androidx.work.PeriodicWorkRequest periodicWorkRequest = new androidx.work.PeriodicWorkRequest.Builder(PeriodicWorkRequest.class, PERIODIC_WORK_INTERVAL,
TimeUnit.MINUTES)
.addTag(TAG)
.build();
WorkManager.getInstance().enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP, periodicWorkRequest);
}
public static void cancelPeriodicWork() {
WorkManager.getInstance().cancelAllWorkByTag(TAG);
}
My Worker Class:
public static final String CHANNEL_ID = "VERBOSE_NOTIFICATION" ;
public PeriodicWorkRequest(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
showNotification(getApplicationContext());
return Result.SUCCESS;
}
private void showNotification(Context context) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My notification")
.setContentText("ddd")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("ddd"))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Channel_name";
String description = "description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(100, mBuilder.build());
}
|
[
"stackoverflow",
"0043794980.txt"
] | Q:
Inject HTML from function
I following the 'Quick tour of Polymer' and there is a section that explain us how to repeat element based on an array, but it only show us how to do it with a template repeater, and I don't really know how its work from behind. I tried to do my own repeater but Polymer inject my code as a string, like unescape characters.
code:
<dom-module id="employee-list">
<template>
[[employe()]]
</template>
<script>
class EmployeeList extends Polymer.Element {
static get is () {
return 'employee-list'
}
constructor () {
super()
this.employees = [
{first: 'Bob', last: 'Li'},
{first: 'Ayesha', last: 'Johnson'},
{first: 'Fatma', last: 'Kumari'},
{first: 'Tony', last: 'Morelli'}
]
}
employe(employees = this.employees) {
let template = '<div>Employee List</div>'
template += employees.map((currentEmployee, id) => {
return `<div>Employee ${id}, FullName : ${currentEmployee.first + ' ' + currentEmployee.last}</div>`
})
return template
}
}
customElements.define(EmployeeList.is,EmployeeList)
</script>
</dom-module>
result:
<div>Employee List</div><div>Employee 0, FullName : Bob Li</div>,<div>Employee 1, FullName : Ayesha Johnson</div>,<div>Employee 2, FullName : Fatma Kumari</div>,<div>Employee 3, FullName : Tony Morelli</div>
And I would like to know if its a form of inject unescape characters / html in Polymer@2
A:
You can use a querySelector within your function to make that happen
html
<template>
<div id="employee-list"></div>
</template>
js
this.querySelector("#employee-list").innerHTML = template
As mentioned by Jordan, you should use dom-repeat
<div> Employee list: </div>
<template is="dom-repeat" items="{{employees}}">
<div>First name: <span>{{item.first}}</span></div>
<div>Last name: <span>{{item.last}}</span></div>
</template>
If you are doing it the way you are to get an id there is an alternative using dom-repeat. You could use the attribute index-as to do that.
<template is="dom-repeat" items="{{employees}}" index-as="id">
You can find out more about dom-repeat here: https://www.polymer-project.org/1.0/docs/api/dom-repeat
|
[
"superuser",
"0000925569.txt"
] | Q:
How to mod/create a loginui.exe (Login Screen)
How can I modify my current Windows 7 Login Screen?
I'm really bored with that default red OEM screen. A registry key, or a place where the images are- may be useful.
Please point out more than one methods if possible and mark the best/safest one.
NOTE:- I want to change not only the wallpaper but the whole design.
A:
XP used GINA (Graphical Identification and Authentication) based logon architecture, so you could build your own custom version to replace LogonUI.exe.
From Vista onwards Winlogon is the Windows module that performs interactive logon for a logon session. Winlogon behaviour can be customised by implementing and registering a Credential Provider. The relevant shell interfaces are listed here.
More information to get you started:
Create Custom Login Experiences With Credential Providers For Windows Vista
How to Build Custom Logon UIs in Windows Vista
|
[
"stackoverflow",
"0049475943.txt"
] | Q:
Javascript - check if lat long coordinates are within a boundary
I have created an array named coordsArray shown beneath. I have cut off the ongoing elements within the arrays as its confidential.
I have this for loop that is supposed to go through each element within the array and look if the coordinates in index values [ 1 ] and [ 2 ] are within a bounding box for London.
var cityL = "ldn";
for (var i = 0; i < coordsArray.drugs.length; i++) {
if(cityL == "ldn"){
if( 51.50408 <= coordsArray.drugs[i][1] && coordsArray.drugs[i][1] <= 51.42548 && -0.326542 <= coordsArray.drugs[i][2] && coordsArray.drugs[i][2] <= 0.0463) {
console.log("test");
}
}
}
This is not working at all, I was wondering if it had something to do with the coordinates within the arrays possibly being of type string? I am unsure as to how I would go about altering this. I am sure that the if statement that checks if the values (coordsArray.drugsi and [2]) are within the bounding box is all correct. Thanks for any guidance, I just wish to view the coordinates that fall within London, thanks!
A:
You're right that your data is stored as a string and you're testing it against numbers. What you need is parseFloat().
if( 51.50408 <= parseFloat(coordsArray.drugs[i][1]) ) {
...
}
|
[
"stackoverflow",
"0004600885.txt"
] | Q:
Rails - Ability to Enable/Disable Links on a View?
I have a UserMailer View that has several link_to's like so:
<%= link_to('XXXXXXXX Link Title', item_url(@item, :only_path => false), :style => 'color:#5196E3;text-decoration:underline;') %>
The page has several different links. I'd like to know if there is a way to globally set in the view to enable or disable the links.
If enabled, the above would run like normal, if not the block above would just show the text (XXXXXXXX Link Title) and not be linked?
Any ideas other than wrapping every link_to inside a IF statement?
Thanks
A:
Rails already provides a link_to_if helper...
So, define @some_boolean in the controller class, or if you want a true global, then set $some_boolean appropriately. Then use the link_to_if :
<%= link_to_if(@some_boolean, "Link Title", <url etc..>) %>
Documentation
A:
you can create a helper method that takes your link parameters and returns the value that you want. which means you will only implement one IF statement.(which will be in the helper.)
great comment by Sean Hill: helpers should be in helper files :)
ApplicationHelper:
helper_method :conditional_link
def conditional_link(string,url)
if true_condition
return link_to string, url
else
return string
end
in your view:
<%= conditional_link string, url %>
|
[
"stackoverflow",
"0024587925.txt"
] | Q:
SwipeRefreshLayout trigger programmatically
Is there any way to trigger the SwipeRefreshLayout programmatically? The animation should start and the onRefresh method from the OnRefreshListener interface should get called.
A:
if you are using the new swipeRefreshLayout intoduced in 5.0
As the image shown above you just need to add the following line to trigger the swipe refresh layout programmatically
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
}
});
if you simply call
mSwipeRefreshLayout.setRefreshing(true);
it won't trigger the circle to animate, so by adding the above line u just make a delay in the UI thread so that it shows the circle animation inside the ui thread.
By calling mSwipeRefreshLayout.setRefreshing(true) the OnRefreshListener will NOT get executed
In order to stop the circular loading animation call mSwipeRefreshLayout.setRefreshing(false)
A:
In order to trigger SwipeRefreshLayout I tried this solution:
SwipeRefreshLayout.OnRefreshListener swipeRefreshListner = new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
Log.i(TAG, "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
loadData();
}
};
Now key part:
swipeLayout.post(new Runnable() {
@Override public void run() {
swipeLayout.setRefreshing(true);
// directly call onRefresh() method
swipeRefreshListner.onRefresh();
}
});
|
[
"math.stackexchange",
"0001065870.txt"
] | Q:
In a triangle ABC , $a\cos(B-C)+b\cos(C-A)+c\cos(A-B)$ is equal to...
In a triangle ABC, prove that $a\cos(B-C)+b\cos(C-A)+c\cos(A-B)$ is equal to $\frac{abc}{R^2}$, where $a$, $b$, and $c$ are sides of the triangle and $R$ is the circumradius.
My work:-
By expanding Cosines equation becomes,
$a(\cos B \cos C+\sin B \sin C)+b(\cos C \cos A+\sin C \sin A)+c(\cos A \cos B+\sin A \sin B)$
using, $\frac{a}{\sin A}=\frac{b}{\sin B}=\frac{c}{\sin C}=2R$
$a(\cos B \cos C+\frac{bc}{4R^2})+b(\cos C \cos A+\frac{ca}{4R^2})+c(\cos A \cos B+\frac{ab}{4R^2})$
after saturation,
$\frac{3abc}{4R^2}+(a\cos B \cos C+b\cos C \cos A+c\cos A \cos B)$
I have no idea what to do next. There is no relation between Cos, abc and R to convert that term in bracket to abc and R.
A:
As $a=2R\sin A$
and $\sin A=\sin[\pi-(B+C)]=\sin(B+C)$
$\implies a\cos(B-C)=2R\sin(B+C)\cos(B-C)=R[\sin2B+\sin2C]$
$\implies\sum a\cos(B-C)=2R[\sum\sin2A]$
Now use Prove that $\sin(2A)+\sin(2B)+\sin(2C)=4\sin(A)\sin(B)\sin(C)$ when $A,B,C$ are angles of a triangle
|
[
"stackoverflow",
"0001287252.txt"
] | Q:
MySQL - insert japanese from PHP - Encoding Troubles
I'm trying to insert some japanese words in a mysql table!
If I insert 'こんにちは' using phpMyAdmin, the word is displayed fine from phpMyAdmin.
But if I try to insert it through php, as follow:
mysql_connect($Host, $User, $Password);
mysql_select_db($Database);
$qry = "INSERT INTO table VALUES (0 , 'こんにちは')";
echo mysql_query($qry);
In phpMyAdmin i see "ã“ã‚“ã«ã¡ã¯" ... why?
And if I try to fetch from the database:
$arr = mysql_fetch_array(mysql_query("SELECT * FROM table where id = 1"));
echo $arr[1];
The browser shows nothing!!!
How can I solve?
Thank you in advance for your help!!!
~EDIT~
My database collation is setup to utf8_general_ci
~EDIT 2~
I don't need to display the output on an HTML page, but the japanese words are printed on a XML page whose encoding is setup to UTF-8.
$plist = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$plist .= "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n";
$plist .= "<plist version=\"1.0\">\n";
$plist .= "<array>\n";
$plist .= "\t<dict>\n";
$plist .= "\t\t<key>test</key>\n";
$plist .= "\t\t<string>".$arr[1]."</string>\n";
$plist .= "\t</dict>\n";
$plist .= "</array>\n";
$plist .= "</plist>";
echo $plist;
the output of this code is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>test</key>
<string></string>
</dict>
</array>
</plist>
So, there is no value for the key "test" ... what can I do? Thanks!
~ SOLVED ~
Problems solved using the function mysql_set_charset() after connecting to the database!
A:
try this before the insert query
mysql_query("SET NAMES utf8");
Also not sure if you set the proper charset of the database, and of the web page.
Charset in HTML Head section?
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
and/or something like
header( 'Content-Type: text/html; charset=utf-8' );
Followings will help you get more ideas how to do it .. if something doesnt work commment back.
check more here on SO
Storing and displaying unicode string (हिन्दी) using PHP and MySQL
How to make MySQL handle UTF-8 properly
setting utf8 with mysql through php
PHP/MySQL with encoding problems
|
[
"stackoverflow",
"0055504189.txt"
] | Q:
How to sequence of MFCC coefficients vectors for speaker recognition?
The project is to use SVM for speaker recognition using MFCC as a feature set. Usually MFCC coefficients are created with a window size in terms of mill second. However, since a speaker speaks for few seconds at least one can use a sequence of MFCC in SVM. The question is how it can be done. Generally, SVM or any kernel takes a vector as an input, but in this case we can use several vectors or matrix to increase robustness. How SVM can learn matrices rather them vectors?
A:
The conventional approach is to use specialized mathematical model to analyze factors in MFCC sequence and extract the speaker vector. You drop the variability in the MFCC related to actual words, you drop the variability related to intonation and leave just the factor related to the speaker. The speaker vector can be later analyzed with SVM. You can check details from i-vector tutorial.
More advanced research uses neural network to extract speaker vectors, so-called d-vectors.
Then you use SVM to classify d-vectors.
|
[
"stackoverflow",
"0044397118.txt"
] | Q:
How to convert Java code (base64 varint decoding) to PHP?
Edit: Solved it, answer below.
In the past week I've been trying to convert some Java code to PHP without any luck.
It's a Hearthstone (card game) deck code decoding code (sounds weird...). The code is a base64 string, which uses a lot of varint arrays.
More information here: https://hearthsim.info/docs/deckstrings/
Only Java and C# code is available. Anyone could give some insights on how to convert java code to php?
Any help would be greatly appreciated!
A:
The solution to get it working, is to use https://wzrd.in/.
In the module, write "deckstring", "latest" version is fine, you get a nice JS file and that's what is needed.
|
[
"stackoverflow",
"0014322008.txt"
] | Q:
cocos2d png transparency issues
This question was asked before but the solutions did not work on my side.
My png for a simple ball looks like this:
I saved it without the white bg and with a transparent bg.
Why is the white showing up in the corners?
A:
Check how your are initializing your EAGLView. To support alpha transparency you should use a pixelFormat like kEAGLColorFormatRGBA8. Your code could look like:
EAGLView* glView = [EAGLView viewWithFrame:[window bounds]
pixelFormat:kEAGLColorFormatRGBA8
depthFormat:GL_DEPTH_COMPONENT16_OES
preserveBackbuffer:NO
sharegroup:nil
multiSampling:NO
numberOfSamples:0];
You could try and use this png file instead of your own just to check if it might be a problem related to the png:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.