qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
2,824,982 | I want to capture keystrokes when the focus in on a panel in java. What should i do?
I am using Netbeans as the IDE. I tried adding keyTyped event but it doesnot work.
Here goes my code
```
import com.lanadmin.Interface.ClientInterface;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.rmi.Naming;
import java.util.logging.Level;
public class RemoteViewer extends javax.swing.JInternalFrame {
public RemoteViewer() {
initComponents();
rdpanel.setFocusable(true);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
rdpanel = new javax.swing.JPanel();
setFocusable(true);
rdpanel.setToolTipText("Remote Desktop");
rdpanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
rdpanelMouseClicked(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
rdpanelMousePressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
rdpanelMouseReleased(evt);
}
});
rdpanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
rdpanelMouseMoved(evt);
}
});
rdpanel.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
rdpanelFocusGained(evt);
}
});
rdpanel.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
rdpanelKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
rdpanelKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
rdpanelKeyTyped(evt);
}
});
javax.swing.GroupLayout rdpanelLayout = new javax.swing.GroupLayout(rdpanel);
rdpanel.setLayout(rdpanelLayout);
rdpanelLayout.setHorizontalGroup(
rdpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 679, Short.MAX_VALUE)
);
rdpanelLayout.setVerticalGroup(
rdpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 626, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(rdpanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(rdpanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void rdpanelMouseMoved(java.awt.event.MouseEvent evt) {
double xScale = Toolkit.getDefaultToolkit().getScreenSize().getWidth() / rdpanel.getWidth();
double yScale = Toolkit.getDefaultToolkit().getScreenSize().getHeight() / rdpanel.getHeight();
try {
String current = Login.handler.currentClientAddress.getHostAddress();
ClientInterface client = (ClientInterface) Naming.lookup("rmi://" + current + "/lan");
client.mousemove((int) (evt.getX() * xScale), (int) (evt.getY() * yScale));
} catch (Exception ex) {
Log2File.logger.log(Level.SEVERE, null, ex);
Log2File.fileHandler.flush();
}
}
private void rdpanelKeyPressed(java.awt.event.KeyEvent evt) {
System.out.println("keypressed");
}
private void rdpanelKeyTyped(java.awt.event.KeyEvent evt) {
System.out.println("aaa");
}
private void rdpanelKeyReleased(java.awt.event.KeyEvent evt) {
System.out.println("keyreleased");
}
private void rdpanelFocusGained(java.awt.event.FocusEvent evt) {
rdpanel.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
rdpanelKeyPressed(evt);
}
@Override
public void keyReleased(java.awt.event.KeyEvent evt) {
rdpanelKeyReleased(evt);
}
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
rdpanelKeyTyped(evt);
}
});
}
public javax.swing.JPanel rdpanel;
}
``` | 2010/05/13 | [
"https://Stackoverflow.com/questions/2824982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322897/"
] | Don't forget to invoke [`setFocusable(true)`](http://java.sun.com/javase/6/docs/api/java/awt/Component.html#setFocusable(boolean)), as discussed in [*How to Write a Key Listener*](http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html). | Depending on what you want to achieve, you could maybe also find help here: <http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html> |
6,601,898 | I am trying to configure my WCF (.NET 4.0) service so that it can be tested using soapUI. I am using wsHttpBinding with message security. My goal is to expose the service on a public test endpoint and try to load-test it with loadUI which uses soapUI tests. For this to work the endpoint needs to be secure and since my production endpoint will use message security I figure my test one should also use it in order to achieve close to production load test results.
I can't seem to be able to configure soapUI to successfully call the service. I have tried a number of combinations of signing and encrypting input and output with the client and server certificate. Has anybody managed to achieve a successful message security configuration of WCF and soapUI?
The following are exerpts from my configuration:
*Binding:*
```
<wsHttpBinding>
<binding name="MessageSecurity">
<security mode="Message">
<message clientCredentialType="Certificate" negotiateServiceCredential="false"/>
</security>
</binding>
</wsHttpBinding>
```
*Behavior*
```
<behaviors>
<serviceBehaviors>
<behavior name="customBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True"/>
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerTrust"/>
</clientCertificate>
<serviceCertificate findValue="MyWebServicesCertificate" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
```
*Service:*
```
<service behaviorConfiguration="customBehavior" name="MyService">
<!-- Service Endpoint -->
<endpoint name="Production" address="" binding="wsHttpBinding" bindingConfiguration="MessageSecurity" contract="IMyService">
<identity>
<dns value="web_services_svr"/>
</identity>
</endpoint>
<host>
<baseAddresses>
<add baseAddress="http://web_services_svr/MyService.svc" />
</baseAddresses>
</host>
</service>
``` | 2011/07/06 | [
"https://Stackoverflow.com/questions/6601898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/753034/"
] | You might want to check for few things.
1) Set negotiateServiceCredential="false"
```
<wsHttpBinding>
<binding name="wsHttpSecure">
<security mode="Message">
<message clientCredentialType="UserName" negotiateServiceCredential="false"
establishSecurityContext="false" algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
```
2) Also make sure in SOAP UI you check mark "Add default WSA To"
Check this link
<http://ddkonline.blogspot.com.br/2012/10/wcf-45-host-unreachable-when-calling.html>
3) For passing client certificate check following link
<http://www.soapui.org/SOAP-and-WSDL/applying-ws-security.html>
I hope that helps. | There is an issue with SoapUI in a network where there is a web proxy. You must configure the proxy settings in SoapUI to get this to work, assuming there was no other problem. |
1,396,458 | Starting with the following (using `gcc version 4.0.1`):
```
namespace name {
template <typename T>
void foo(const T& t) {
bar(t);
}
template <typename T>
void bar(const T& t) {
baz(t);
}
void baz(int) {
std::cout << "baz(int)\n";
}
}
```
If I add (in the *global* namespace)
```
struct test {};
void bar(const test&) {
std::cout << "bar(const test&)\n";
}
```
then, as I expected,
```
name::foo(test()); // produces "bar(const test&)"
```
But if I just add
```
void bar(const double&) {
std::cout << "bar(const double&)\n";
}
```
it can't seem to find this overload:
```
name::foo(5.0) // produces "baz(int)"
```
What's more,
```
typedef std::vector<int> Vec;
void bar(const Vec&) {
std::cout << "bar(const Vec&)\n";
}
```
doesn't appear either, so
```
name::foo(Vec());
```
gives a compiler error
```
error: cannot convert ‘const std::vector<int, std::allocator<int> >’ to ‘int’ for argument ‘1’ to ‘void name::baz(int)’
```
Is this how the lookup is supposed to work? (Note: if I remove the namespace `name`, then everything works as I expected.)
How can I modify this example so that any overload for `bar` is considered? (I thought that overloads were supposed to be considered *before* templates?) | 2009/09/08 | [
"https://Stackoverflow.com/questions/1396458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112/"
] | I assume you added the `double` version to the global namespace too, and you call `foo` from main after everything is defined. So this is basically two phase name lookup. Looking up an unqualified function name that is dependent because an argument in the call is dependent (on its type) is done in two phases.
The first phase does a unqualified and argument dependent lookup in the definition context. It then freezes the result, and using the instantiation context (the sum of the declarations at the point of instantiation) does a second argument dependent lookup *only*. *No* unqualified lookup is done anymore. So for your example it means:
* The call `bar(t)` within `foo<test>` looks up `bar` using argument dependent lookup at the instantiation context (it doesn't find it using unqualified lookup, because `foo` is declared `above` the bar template). Depending on whether you define the global `bar` before or after the `foo` template, it will find the global `bar` declaration using argument dependent lookup already in the first phase (it's defined in `test`'s namespace). Then the call in main will instantiate `foo<test>` and it will possible find `bar` in this phase (if you declared it after you declared the template).
* The call `bar(t)` within `foo<int>` doesn't do argument dependent lookup (or rather, the result for the lookup is an empty declaration set), because `int` is a fundamental type. So, unqualified lookup at the definition context will find nothing either, because the matching `bar` template is declared `after` the `foo` template. The call would be ill-formed, and the standard says about this situation at `14.6.4.2/1`
>
> If the call would be ill-formed [...] then the program has undefined behavior.
>
>
>
You should therefor consider this as a "i did a dirty thing and the compiler chose not to slap me" case, i think :)
* The call `bar(t)` within `foo<Vec>` will do the lookups again, and will look for bar in `std::` (because that's where `std::vector` is defined). It doesn't find a `bar` there, neither in the definition context. So it decides to go by undefined behavior again, and uses the `bar` template, and which in itself again does undefined behavior by using the `baz` declared after it and which cannot be found by neither ADL nor unqualified lookup from the definition context.
If the vector were a `vector<test>`, then lookup for `bar` would be done at global scope too, because argument dependent lookup will not only use the argument type directly, but also the type of the template arguments in them, if there are any.
---
If you use GCC, then don't rely entirely on its behavior. In the following code, it claims the call is ambiguous, although the code is perfectly fine - the `f` in `afake` should not be a candidate.
```
namespace aname {
struct A { };
void f(A) { }
}
namespace afake {
template<typename T>
void g(T t) { f(t); }
void f(aname::A) { }
}
int main() { aname::A a; afake::g(a); }
```
If you want to test your snippets against conformance, best use the [comeau online compiler](http://www.comeaucomputing.com/tryitout/) with the strict settings. | Do a google on "c++ koenig lookup"
That should give you enough information on the template lookup rules.
Herb Sutter has a good article on the subject:
<http://www.gotw.ca/gotw/030.htm> |
149,738 | I'm (still) trying to make another submission to the [Largest Number Printable](https://codegolf.stackexchange.com/q/18028) question, and I've got the following bit of code:
```
f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[c-c]?[[b,c,f[d]],~-c,b]:b:$n}
h=[],$n=?~.ord,[]
h=f[h]until h==p($n+=$n)-$n
```
Ungolfed:
```
f=->{b,c,d=a
if b
if a==b # a is not an array
return a-1
elsif a==a-[0] # a does not contain 0
t = [b,c,f[d]]
return [t,c-1,b]
else # a is an array containing 0
return b
end
else # if a == []
return $n
end}
$n = 126
h = [[],n,[]]
until h==0 do
$n += $n
p $n
h = f[h]
end
```
The conditions I'm working with:
* Maximum 100 bytes.
* No digits allowed in my code.
My code is currently at 108 bytes, but I can't figure out how to golf it further.
The `h==p($n+=$n)-$n` may be replaced with `h==0`, but I can't use digits and I still need to print `$n` and apply `$n+=$n` in the `until` loop.
I'm also satisfied with code that replaces `$n+=$n` with `$n+=1`, but I can't use digits unfortunately.
Any suggestions? | 2017/12/02 | [
"https://codegolf.stackexchange.com/questions/149738",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/58880/"
] | JavaScript (ES6), ~~345~~ 342 bytes
===================================
*Saved 2 bytes thanks to @StephenLeppik*
```js
n=>[...'lmnopqsuvwxyz{}~'].reduce((s,c)=>(x=s.split(c)).join(x.pop()),` p{{yyvu{ xvs${(n&&n<60?n+'':(k=n||new Date/6e4|0,k/60%(n?k:12)|0||(n?0:12))+':'+('0'+k%60).slice(-2)).padEnd(9)}xoup__uuxx{~zzn1s2s3wn4s5s6wn7s8s9wuuq 0sStartmy_~ { oxp__zxllx{|x
|p{_|{y_|qox}}}uzs}uuuuu {yyy__z|u y___s|wm|y~zzv
|}}}}xu sx q~|p{{{ox
znzq m qy|ylx}|xv`)
```
### Test cases
```js
let f =
n=>[...'lmnopqsuvwxyz{}~'].reduce((s,c)=>(x=s.split(c)).join(x.pop()),` p{{yyvu{ xvs${(n&&n<60?n+'':(k=n||new Date/6e4|0,k/60%(n?k:12)|0||(n?0:12))+':'+('0'+k%60).slice(-2)).padEnd(9)}xoup__uuxx{~zzn1s2s3wn4s5s6wn7s8s9wuuq 0sStartmy_~ { oxp__zxllx{|x
|p{_|{y_|qox}}}uzs}uuuuu {yyy__z|u y___s|wm|y~zzv
|}}}}xu sx q~|p{{{ox
znzq m qy|ylx}|xv`)
O.innerText = [100, 59, 60, 120, 59999999, 1, 0].map(f).join('\n');
```
```html
<pre id=O></pre>
``` | C#, 701 bytes
=============
[Try it Online!](https://tio.run/##jVJdS8MwFH3PrwhlsITW0s5NYbVTUXxSEDfwYYzStVmXsaXSZIq0@e3zttlwOqcGbnN77rnfSeRJkhdss5ZcZHj4LhVbBShZxlLilxJJFSue4Necp/gh5oJQVKK7tUguuFCOVAV4DfAMABziDYlpOCjBghehF3ynTUOSgF2wN2wQAup4UvqO5xjZaY2uxwvbngy8y3bU7rdx20loYPwwC60Kw2k@f5wtsbKcWchsK4qiaicAHhSZhfNwwOyWhcu5Br9ybvvbu6ObOEHB1LoQrSugTMmZTzWqQOn2qIZcoPkAQco9FNzrrm9jxUZ8xYhH3es0HbIkF6mEobmjfGgmYq1WfSkt6j7G6RPP5or4XhMBmV4h5GmvDm@agl9cp6sJJdPbdo0AkpG6unKmfzZ2fzOeHxjxzgiIB9pQxYXaIduZRmauptqmvFMzlyZE9HnwMVL1ZXdH@v4PZy9Ztb@NekP1bQV6E6CbXMh8ydzngit2zwUj9WMmfsejNEAa6c0H)
```
(a)=>{int j=0;Func<int,string>b=(c)=>new string(new[]{1,0,1,0,1,1,0,1,0,0,1,1}[j++]>0?'_':' ',c);string e="| | | | |",f=e+"___|___|___| |";Func<int,string>g=h=>e+$" {h} | {h+1} | {h+2} | |";return$@" {b(61)}
|{b(45)}| {b(11)} |
|{b(45)}| | {new DateTime(0).AddSeconds(a).ToString("mm:ss").PadRight(10)}| |
| {b(35)} | |{b( 11)}| |
{e} | | | |
{g(1)}
{f}
{e} | | | |
{g(4)}
{f}
{e} | | | |
{g(7)}
{f}
{e} | | |
{e} 0 | Start | |
{e}___|_______| |
| |{b( 35)}| | ___________ |
| |{b( 35)}| | | | |
| {b(35)} | | | |
| {b(35)} | |___________| |
|{b(45)}|{b(15)}|";}
``` |
3,054,093 | How can i do below without assign null value "Tex=null"?
```
static void Main(string[] args)
{
FileInfo f = new FileInfo("C:/temp/Arungg.txt");
StreamWriter Tex;
Tex = null;
if (!f.Exists)
{
f.CreateText();
}
else
{
Tex = f.AppendText();
}
Tex.WriteLine("Test1");
Tex.WriteLine("Test2");
Tex.Write(Tex.NewLine);
Tex.Close();
Console.WriteLine(" The Text file named Arungg is created ");
}
``` | 2010/06/16 | [
"https://Stackoverflow.com/questions/3054093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/52420/"
] | You need to make sure that `Tex` is assigned in every code path.
```
if (!f.Exists)
{
Tex = f.CreateText();
}
```
Note that the `AppendText` method will create the file if it doesn't exist.
Therefore, you don't need the `if` statement at all. | If you don't instantiate your StreamWriter, it's going to bomb on you. You need to assign a value to get it to compile, but without an instance, it's not going to do what you think it will do.
Perhaps simplify and [consider using File.WriteAllText](http://msdn.microsoft.com/en-us/library/ms143375.aspx)? |
34,662,803 | I have this in the `<head>` of my base.html.
```
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "myStyleSheet.css" %}">
```
and I get error **Invalid block tag: 'static'**
Within INSTALLED\_APPS I've included
```
'django.contrib.staticfiles',
```
and I've included within settings.py
```
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(__file__), "static/")
```
Why do I get the load error? | 2016/01/07 | [
"https://Stackoverflow.com/questions/34662803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2740177/"
] | the actual problem here, I'm very sorry to say, was that within my app.yaml file I had specified a different directory for the static files and it seemed to be overriding everything else. Once removed, all sorted. | Do you have the `django.core.context_processors.static` context processor in your `TEMPLATE` settings? Here's a sample:
```
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.static',
],
},
},
]
```
You can add it there or use `{ %load static %}` in your template. |
3,089 | I would like to disallow certain address location types on Organization contacts—for example I don't want to allow "Home" addresses on an Organization.
I would also like to disallow "Main" address type on the Individual contact types.
Anybody try this before? | 2015/06/08 | [
"https://civicrm.stackexchange.com/questions/3089",
"https://civicrm.stackexchange.com",
"https://civicrm.stackexchange.com/users/17/"
] | Frankly, CiviCRM core should disable the Home address location for Organizations, and the Work address location for Households. | If the solution suggested by Coleman does not work, you will have to create a little extension that removes some of the options based on contact type in a buildForm hook? Or alternatively validates the selected location type against the contact type in a validateForm hook |
31,120,553 | I am new to android development.
I am using webview to display HTML pages in android, but only the text shows up.
Can you please help me with the problem.
thank you in advance, would be very helpful.
```
WebView view = (WebView) this.findViewById(R.id.webView);
try{
InputStream stream = this.getAssets().open("Capacitor Code Calculator.html");
int streamsize = stream.available();
byte[] buffer = new byte[streamsize];
stream.read(buffer);
stream.close();
String html = new String(buffer);
view.loadData(html,"text/html", "utf-8");
}
catch (Exception e){
e.printStackTrace();
```
Does it have to do something with "text/html" in view.loadData(html,"text/html", "utf-8");
I have my html and image file both in assets folder. | 2015/06/29 | [
"https://Stackoverflow.com/questions/31120553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4699944/"
] | I find the `sequence` function to be helpful in this case. If you had your data in a structure like this:
```
(info <- data.frame(start=c(1, 144, 288), len=c(6, 6, 6)))
# start len
# 1 1 6
# 2 144 6
# 3 288 6
```
then you could do this in one line with:
```
sequence(info$len) + rep(info$start-1, info$len)
# [1] 1 2 3 4 5 6 144 145 146 147 148 149 288 289 290 291 292 293
```
Note that this solution works even if the sequences you're combining are different lengths. | From [R >= 4.0.0](https://stat.ethz.ch/pipermail/r-announce/2020/000653.html), you can now do this in one line with `sequence`:
```r
sequence(c(6,6,6), from = c(1,144,288))
[1] 1 2 3 4 5 6 144 145 146 147 148 149 288 289 290 291 292 293
```
The first argument, `nvec`, is the length of each sequence; the second, `from`, is the starting point for each sequence.
As a function, with `n` being the number of intervals you want:
```r
f <- function(n) sequence(rep(6,n), from = c(1,144*1:(n-1)))
f(3)
[1] 1 2 3 4 5 6 144 145 146 147 148 149 288 289 290 291 292 293
``` |
15,757,105 | I just wanted a fast/easy/simple way to check for existing ID on a specific element (div in this case)..
Can't seem to find code sample for this..im using jquery but i dont think i need to do jquery on this one, just basic getElement.. but i need to isolate the search inside a div block.. because the id does exist in other elements on the page but i need to know if it exist in a specific area/div.
so instead of just
```
document.getElementById(target_id);
```
i need something like:
```
divName.getElementById(target_id);
```
or
```
$("document.divName").getElementById(target_id);
```
or
```
$(".divName").document.getElementById(target_id);
```
Can't seem to find something that works. | 2013/04/02 | [
"https://Stackoverflow.com/questions/15757105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797947/"
] | IDs are supposed to be **unique** and no two elements in page should have same id. You may search some element with some class in div with specific ID.
```
$('#divId .someClass')
```
or using [**find()**](http://api.jquery.com/find/)
```
$('#divId').find('.someClass')
```
or using [**context**](http://api.jquery.com/jQuery/), `jQuery( selector [, context ] )`
```
$('.someClass', $('#divId'))
``` | According to my understanding on your question, You have used two id's with same name when u execute, It takes only first ID so you are asking to take id from the specific div, well that is bad type of coding to use two id for same name instead go for class if want to use same name.
solution for your question is -this ->
```
var someDiv = document.getElementsByClassName("divName");
var someId = someDiv[0].getElementById("target_id");
``` |
12,096,016 | I have written the following Java source file (`Hello.java`):
```
package com;
public class Hello {
public static void main(String[] args) {
System.out.println("Hello!");
}
}
```
I save this to `C:/tmpjava/Hello.java`.
From the command line, I navigate to that directory and run `javac Hello.java`. Then I run `dir`:
* `Hello.class`
* `Hello.java`
Then, from the same directory that I just ran `javac` from, I run `java Hello.class` and get:
```
Exception in thread "main" java.lang.NoClassDefFoundError: Hello/class
Caused by: java.lang.ClassNotFoundException: Hello.class
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: Hello.class. Program will exit.
```
What's going on here?!? How can `javac` run fine, but not `java`? | 2012/08/23 | [
"https://Stackoverflow.com/questions/12096016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892029/"
] | Your class `Hello` belongs to the package `com`. So the fully qualified name of your class is `com.Hello`. When you invoke a program using java on the command-line, you should supply the fully-qualified class name of the class that contains your `main` method and omit the *.class*, like so:
```
java com.Hello
```
The java program needs this fully-qualified class name to understand which class you are referring to.
But you have another problem. The java program locates packages, sub-packages, and the classes that belong to them using the filesystem. So if you have a package structure like `com.Hello`, the java program expects to find a class file named *Hello.class* in a directory named *com*, like this: *com/Hello.class*. In fact you can observe this behavior in the `Exception` that you see; you've incorrectly used *Hello.class*, which java is interpreting as a *package* named `Hello`, and a *class* named `class`, and is looking for the directory structure *Hello/class*:
>
> java.lang.NoClassDefFoundError: Hello/class
>
>
>
But the compiler javac **doesn't** set up this directory structure by default. See the [documentation for javac](http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/javac.html), but the important bit is this: when you do your compiles, you can specify a destination directory using the `-d` flag:
>
> -d directory
>
>
> Set the destination directory for class files. The destination directory must already exist; javac will not create the destination directory. If a class is part of a package, javac puts the class file in a subdirectory reflecting the package name, creating directories as needed. For example, if you specify -d c:\myclasses and the class is called com.mypackage.MyClass, then the class file is called c:\myclasses\com\mypackage\MyClass.class.
>
>
> **If -d is not specified, javac puts the class file in the same directory as the source file.**
>
>
>
The last bit in bold is the source of much confusion for beginners, and is part of your own problem.
So you have two alternatives:
1. In your case, it's fine if you supply the current directory as the destination directory, like so (the period `.` means *current directory*):
```
javac -d . Hello.java
```
If you invoke the compiler like this, it will create the *com* directory for you, and put your compiled class file in it, the way that the java program expects to find it. Then when you run java as above, from *c:\tmpJava*, your program should execute.
2. You could set up your source code using a directory structure that mirrors your package structure: put your source file *Hello.java* inside a directory called *com*, in your case: *c:\tmpJava\com\Hello.java*. Now, from *c:\tmpJava* you can run your javac compile like this:
```
javac com\Hello.java
```
You haven't supplied the `-d` flag, but that's fine, because you've created the directory structure yourself, and quoting again from the documentation above:
>
> If -d is not specified, javac puts the class file in the same directory as the source file.
>
>
>
Again, when you run java as above, your program should execute.
Note that this second alternative is one that is commonly employed by java programmers: the source code files are organized in a directory structure that mirrors the package structure.
In this explanation we've ignored the concept of the *classpath*. You'll also need to understand that to write java programs, but in your case of simply compiling a program in the current directory - if you follow one of the two alternatives above when compiling your class - you can get away without setting a classpath because, by default, the java program has the current directory as a classpath. Another quote, this one from the [documentation for java](http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html):
>
> -cp classpath
>
>
> Specify a list of directories, JAR archives, and ZIP archives to search for class files. Class path entries are separated by semicolons (;). Specifying -classpath or -cp overrides any setting of the CLASSPATH environment variable.
>
>
> **If -classpath and -cp are not used and CLASSPATH is not set, the user class path consists of the current directory (.).**
>
>
>
Note that when you use an IDE like Eclipse to run your java code, this is mostly handled for you, but you'll still run into classpath issues. | The class should be in `C:\tmpjava\com\Hello.class`
And you should run from `C:\tmpjava`: `java -cp . com.Hello`
When you put a class in a package it defines the file structure of the class. I.e. your class which in package `com` should be in folder `com` |
743,183 | SQL Server developers consider Cursors a bad practise , except under some circumstances. They believe that Cursors do not use the SQL engine optimally since it is a procedural construct and defeats the Set based concept of RDBMS.
However, Oracle developers do not seem to recommend against Cursors. Oracle's DML statements themselves are implicit cursors.
Why this difference in approach? Is it because of the way these 2 products are made, or does this advice apply to both products? | 2009/04/13 | [
"https://Stackoverflow.com/questions/743183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49189/"
] | I have always been told that cursors where evil, but always by MS SQL Server gurus, because of it's bad performance. Regarding Oracle's PL/SQL [I found this saying when to *use* cursors](http://www.dba-oracle.com/t_top_reasons_poor_performance.htm):
>
> Not using cursors results in repeated parses. If bind variables are not used, then there is hard parsing of all SQL statements. This has an order of magnitude impact in performance, and it is totally unscalable. Use cursors with bind variables that open the cursor and execute it many times. Be suspicious of applications generating dynamic SQL.
>
>
>
As [cursors are implicitly created](http://www.exforsys.com/tutorials/oracle-9i/oracle-cursors.html) [on every operation](http://www.dbapool.com/articles/090706.html), it doesn't seem so performance-punishing to use them when needed :)
Remember that Oracle's implementation is closer to Postgres than to Sybase (Genesis of MS SQL Server), so performance will be different for each on different tasks.If you can, avoid the hustle of tweak for performance on systems that can swap able back-ends, go for least common denominator if you need to work with both. /tangential\_topic | The other answers correctly point out the performance issues with cursors, but they don't mention that SQL and relational databases are best at set-based operations and cursors are fundamentally for iterative operations. There are some operations (in the broader sense) that are easier to perform using cursors, but when working with SQL you should always be thinking about working with sets of data. Cursors are often misused because the coder didn't grasp how to perform the task using set-based operations. |
137,598 | I try to solve the differential equation
```
DSolve[{3*y[x] + 2*x*y[x]^2 + (2*x + 3*x^2*y[x])*y'[x] == 0, y[1] == 1/2}, y[x], x]
```
This produces some error messages as
>
> DSolve::bvnul: For some branches of the general solution, the given
> boundary conditions lead to an empty solution.
>
>
>
It also produces:
$$y(x)\to \text{Root}\left[-8 \text{$\#$1}^5+\frac{40 \text{$\#$1}^4}{x}-\frac{80 \text{$\#$1}^3}{x^2}+\text{$\#$1}^2 \left(\frac{80}{x^3}-\frac{1}{x^2}\right)-\frac{40 \text{$\#$1}}{x^4}+\frac{8}{x^5}\&,1\right]$$
I know this DEQ is solvable because I did it by hand (see implicit solution: <https://math.stackexchange.com/questions/2140226/exact-de-y2xy3dxx3xy2dy-0/2140279#2140279>) and verified it using [*WA*](http://www.wolframalpha.com/input/?i=(2xy%5E2%2B3y)%2B(3x%5E2y%2B2x)y%27+%3D0,+y(1)+%3D+1%2F2).
Is there any way to coax *Mathematica* to produce that result using `DSolve` in spite of that nasty IC?
I am using Windows 7, MMA version $11.0.1.0$. | 2017/02/12 | [
"https://mathematica.stackexchange.com/questions/137598",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/36141/"
] | Here is a refinement of @xzczd's [`Trace`](http://reference.wolfram.com/language/ref/Trace) idea (originally posted as an answer to question [(174383)](https://mathematica.stackexchange.com/q/174383/45431)):
```
Quiet @ Trace[
DSolve[{3*y[x]+2*x*y[x]^2+(2*x+3*x^2*y[x])*y'[x]==0,y[1]==1/2},y[x],x],
Solve[e_, y[x]] -> (eqn = e),
TraceInternal->True
];
eqn
```
>
> 3 Log[x] + 2 Log[y[x]] - 5 Log[1 - x y[x]] == C[1]
>
>
>
This produces the implicit equation that the OP referenced in his linked question. | **Maple**
I tried the same ode in Maple and it also produces the solution in terms of `RootOf`, the maple routine "a placeholder for representing all the roots of an equation in one variable". But there is also an option which is self explanatory `remove_RootOf`.
Thus, maple was able to produce an implicit solution to the problem in a much more simplified form.
```
restart:with(plots):
ode:=3*y(x) + 2*x*y(x)^2 + (2*x + 3*x^2*y(x))*diff(y(x),x)= 0;
sol:=dsolve({ode,y(1)=1/2});
```
[](https://i.stack.imgur.com/rkEty.jpg)
Now to get rid of the `RootOf` we need to load the package `DEtools` first,
```
DEtools:-remove_RootOf(sol);
```
[](https://i.stack.imgur.com/H2P6k.jpg)
Now comparing the two different forms of the same solution,
```
p1:=plot(rhs(sol),x=1..10,color=green,axes=boxed,linestyle=3):
p2:=implicitplot(-8+8*(y)^5*x^5-40*(y)^4*x^4+80*(y)^3*x^3+(x-80)*(y)^2*x^2+40*y*x=0,x=1..10,y=0..1,color=red,axes=boxed,linestyle=1):
display({p1,p2});
```
[](https://i.stack.imgur.com/Fi0sP.jpg)
***Mathematica***
You can get the desired result in *MMA* too.
[](https://i.stack.imgur.com/2gnrF.jpg)
Now plugin `y[x]` for `#1`
[](https://i.stack.imgur.com/xEZTR.jpg)
>
> -(8/x) + 40 y[x] - 80 x y[x]^2 + x^2 y[x]^2 + 80 x^2 y[x]^3 -
> 40 x^3 y[x]^4 + 8 x^4 y[x]^5 == 0
>
>
> |
3,293,785 | Is there any specific example/instance of DI being applied as an architectural principle or design pattern **in the .NET Framework itself**? Do any (or many) of the types in the framework/BCL conform to IoC?
The type names and a brief illustration/explanation based in C# would be great!
This would compund the need for DI infused design principle as a best-practice...as it is gleaned from the base framework itself.
I reiterate, I am not looking for IoC/DI Frameworks **BUT** for IoC/DI **IN** the framework.
**EDIT:** Just wanted to get more instances/examples ... hence the bounty! | 2010/07/20 | [
"https://Stackoverflow.com/questions/3293785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190037/"
] | Both the StreamReader and StreamWriter could be seen as examples of IoC/DI.
Each allow you to inject a different Stream object (or one of its derivatives) for reading/writing respectively.
```
FileInfo fi = new FileInfo(@"C:\MyFile.dat");
StreamWriter sw = new StreamWriter(fi.Open());
```
Or:
```
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
```
Would both allow:
```
sw.Write("Hello world!");
```
The same way, no matter what kind of Stream you injected in the call to the constructor. | Sure - the [IServiceProvider](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.ole.interop.iserviceprovider.aspx) interface has been part of the Framework since 1.0. This isn't DI as it is typically discussed here (using a "kernel"), but it is IoC using the Service Locator pattern.
If you dig into any of the Windows Forms Designer code, you'll see it peppered liberally with lines like this one:
```
IDesignerOptionService service =
(IDesignerOptionService)this.GetService(typeof(IDesignerOptionService));
```
If you're working with a [Component](http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx), then you get access to this via the [Site](http://msdn.microsoft.com/en-us/library/system.componentmodel.component.site.aspx) property. It's quite common and practically required knowledge when creating custom controls.
This is Service Location, textbook example. You've got a generic `IServiceProvider` that hands out abstract services you request by service type. If you ever want to create custom designers - smart tags and so on - then you need to know all of this. It's similar for ASP.NET as well.
---
P.S. Please don't *use* `IServiceProvider` in new code. It's a very old, non-generic interface. If you are creating reusable libraries that require an IoC container in order to work, you should use the [Common Service Locator](http://commonservicelocator.codeplex.com/) instead. But don't even use *that* unless you absolutely require that your library be agnostic of the DI library used at the application tier; most of the implementation-specific containers/kernels offer much richer APIs that you'll miss out on if you nail yourself to the CSL. |
4,507,628 | How to determine wifi network interface name in java? | 2010/12/22 | [
"https://Stackoverflow.com/questions/4507628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550982/"
] | Since you said that you are developing on Android use this:
```
WifiManager wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
System.out.println(wifiInfo.getSSID());
```
This will return the name of your WIFI.
You have to add this permission to your manifest.
```
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
``` | Try:
[NetworkInterface.getNetworkInterfaces();](http://download.oracle.com/javase/6/docs/api/java/net/NetworkInterface.html#getNetworkInterfaces%28%29)
which will return all the interfaces present on your machine. |
5,383,609 | I am trying to figure out how to use git in my project workflow, and I have an existing Xcode project that I want to put into the repository. I think I have the repository set up correctly under organizer, but the Source Control menu is grayed out.
Apparently, it's easy to do if you start a new project, but how do I import an existing project with snapshots and everything?
I'm using Xcode 4 and git 1.7.4
Also, if there are any good walkthroughs on git configuration and best practices, that would be nice. I'm a little late to the game, so anything that can get me up to speed would be cool. | 2011/03/21 | [
"https://Stackoverflow.com/questions/5383609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356438/"
] | Xcode 7 (and 8)
===============
If you were starting a new project you would just check **Create Git repository** during the setup. (Then skip down to the Commit part below.)
[](https://i.stack.imgur.com/cq2lF.png)
But it you are working with an existing project, go to **Xcode** > **Preferences...** > **Source Control** and check the **Enable Source Control** box.
[](https://i.stack.imgur.com/rNYbh.png)
Then in the main **Source Control** menu choose **Create Working Copy...**.
[](https://i.stack.imgur.com/G2Qs6.png)
(If you get a "Please tell me who you are" error the see [this question/answer](https://stackoverflow.com/questions/32598660/git-commit-works-with-xcode-beta-but-not-with-normal-version) or one of the other linked questions there.)
When that has finished, make any change to one of your Xcode project files. Then go back to the **Source Control** menu and choose **Commit**.
[](https://i.stack.imgur.com/hMPD2.png)
And write a commit message and click the **Commit** button. (If the commit button is disabled, then make any minor change to your project and try again.)
[](https://i.stack.imgur.com/LpTfx.png)
In Github sign in and [create a new repository](https://github.com/new).
[](https://i.stack.imgur.com/8Tk07.png)
Call it whatever you want, but *don't* add a README or .gitignore or license yet. You can add those things later. Doing so now will make the syncing more difficult.
[](https://i.stack.imgur.com/BoZwU.png)
Copy the link to your repository.
[](https://i.stack.imgur.com/QSFIp.png)
Go to **Source Control** > *your branch name* > **Configure**.
[](https://i.stack.imgur.com/QBpCQ.png)
Click the **Remotes** tab > "**+**" button > **Add remote...**.
[](https://i.stack.imgur.com/5n0dZ.png)
Enter the github repository name and paste in the address.
[](https://i.stack.imgur.com/25ewZ.png)
After adding the remote, click **Push** in the **Source Control** menu. Enter your github user name and password. That's it. You project should be copied to github now.
(I had some trouble getting my username and password accepted at first. If that happens to you go to **Xcode** > **Preferences...** > **Accounts** > *your new repository*. Enter your user name and password there and then try the **Push** again.)
[](https://i.stack.imgur.com/a3HxM.png)
You can add a README and other files, but if you do it from the web, you will have to do **Source Control** > **Pull** in Xcode before you con commit other changes.
Now any time you make changes in Xcode, all you have to do is **Commit** and **Push**.
I learned this method mostly from [here](https://medium.com/@0xben/using-github-with-xcode-6-8208b92c7a60).
See also
========
* [The Basics of Git and GitHub](https://www.youtube.com/watch?v=U8GBXvdmHT4)
* [How to add a *.gitignore* file for Swift in Xcode](https://stackoverflow.com/a/33688681/3681880) | Check out my post on this topic [Setting up a git repository in XCode for a pre-existing project](https://stackoverflow.com/q/11021626/1224762). The above is correct, but it will include UserInterfaceState in your changes as you commit and this could be annoying because this file updates everytime you do anything in xcode, even if it is as simple and navigating through files or folders in your project. |
28,448,029 | ```
int[] numbers = new int[10];
numbers[0] = 20;
```
At first I thought I was so far off in syntax (I'm more of a C++ programmer), that It wouldn't work. But I whipped out the good ole' Java book and this would be correct.
Is there any obvious reason why Android Studio isn't recognizing this? The first line declaring the array appears to work properly, but the line where I set 20 as the first block is giving me the red squigglies and `Unknown Class 'numbers'` error. | 2015/02/11 | [
"https://Stackoverflow.com/questions/28448029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4535064/"
] | Your second line needs to be inside a method (function).
```
class Foo
{
int numbers[] = new int[10];
Foo()
{
numbers[0] = 20;
}
}
``` | If you are coding for Android then ArrayList is more preferable and easy to use too,
As simple as
ArrayList numbers=new ArrayList();
numbers.add(20); |
6,125 | I played guitar since age of 12, but haven't really played for the last 5 years and would like to start again.
However, when I used to play I rarely used the pinky finger because I have big hands (not an excuse, but this is how it happened).
Now that I almost forgot how to play after a long absence I thought, "Why don't I start training the pinky from scratch?"
What are the best exercises/techniques to train the pinky? | 2012/05/01 | [
"https://music.stackexchange.com/questions/6125",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/2319/"
] | Minor Pentatonic scale
```
$6 2 5 $5 2 4 $4 2 4 $3 2 4 $2 2 5 $1 2 5 $3 ...or: 2 4 / 6 $2 5 7 $1 5 7 / 9
```
Try a G chord with Ring- Middle- and a Pinky-barre.
```
%3/3.2/2.0/0.0/0.3/4.3/4
```
In fact, all of the CAGED shapes will work your pinky if you use the "barre" fingerings: don't use the index (1) at all and form the shape with middle (2), ring (3) and pinky (4).
Also the usual *folksy* chord embellishments will serve as exercise: D-Dsus4-D, A-Asus4-A, G-Gadd9-G, C-Cadd9-C.
And from any of these "suspended" notes, you can *slide up* with the pinky to the next chord tone, and re-form the chord in the new position (and/or inversion). | A John petrucci training exercise I used a while back helps a lot with finger dexterity
You start off with a basic chord of :
1
2
3
4
X
X
Then move your index up a fret and switch positions with the middle finger like so:
2
1
3
4
X
X
Then you move up the whole 4 strings you are fretting with the index
When you're done you should have:
4
1
2
3
X
X
Then you start moving your middle finger same pattern
Go through the last two fingers including the pinky to reach the first chord again:
1
2
3
4
X
X
The idea is to keep all your fingers on the fret board except the ones that are being switched
It will start off as being clumsy but then it will really strengthen your fingers and give you dexterity in all of the fingers and finger independence
If you don't understand what I mean I'll make a more detailed answer
The pattern ends with the same starting chord so rinse and repeat |
1,236 | How have experts estimated the amount of oil that was shooting out of that pipe in the Gulf? I bet there's some neat math or physics involved here, and some interesting assumptions considering how little concrete data are available. | 2010/07/30 | [
"https://math.stackexchange.com/questions/1236",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/41/"
] | One interesting fact told to me by my father, a chem engineer, is that if you have a high pressure gas leaking into a low pressure gas through a small hole, there is a upper limit to the rate of flow. That is, no matter how high the pressure gets on the high pressure side, the rate of flow does not surpass some finite limit. I suppose this relates to the speed of sound, but I don't know. I also don't know if there a corresponding phenomenon with liquids. | The following page should be of some help:
<http://en.wikipedia.org/wiki/Diffusion> |
24,212,667 | I've read that methods and member variables are public by default in PHP, yet many of the code examples I look at have the `public` keyword in front. For example:
```
class SomeClass {
public $data;
public function someFunction() {
}
}
```
Is there any reason to use the `public` keyword before method and member variable names in PHP, or is clarity the only reason some people do it? | 2014/06/13 | [
"https://Stackoverflow.com/questions/24212667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1101095/"
] | >
> Is there any reason to use the `public` keyword before method and
> member variable names in PHP, or is clarity the only reason some
> people do it?
>
>
>
The reason is clarity.
Humans are coding this stuff. Humans need to read this stuff. And if a human cannot quickly decipher what is happening, lack of clarity can cause more issues.
It’s part of the reason that we also indent & properly format code. The language interpreter will eat up any code as long as the syntax is correct. Anything else—including comments—are placed there so us pieces of meat in front of a keyboard can actually make some sense of what is happening.
Using your pseudo-code example:
```
class SomeClass {
public $data;
public function someFunction() {
}
}
```
Look at how easy it is to read that and understand how it works! In comparison, look at this:
```
class cName { $d; function fName() {} }
```
Technically speaking both pieces of code should work the same. But what is `$d`? And what is `cName`? And what is `fName`? The code would work in both cases, but who wants to spend any time untangling the second example. I mean, it works, right?
Clarity is the real key to good coding & development. This world programming & computer work is invisible—and sometimes—obtuse enough as-is. No reason to obscure how something works by just ignoring the fact that humans—not machines—create code. | My personal opinion is that it is better to be explicit. No ambiguity. I also think that all member variables should be either protected or private with the appropriate getters/setters.
It also aids in the documentation of your code - such as DOxygen |
33,487,146 | I am building a select option dynamically. I am selecting from the select option, one value. (values for list come from php
How can I pass that selected value to PHP?
```
<select id ="s1" name="swimopt" class="so">
<?php echo $options; ?>
</select>'
```
THe $options are coming from a MySQL and populating the dropdown
When I select a value, and try
`echo $_POST['swimopt'];`
does not show selected value
Please help
```
<form id="swimdata" method="POST" action="save.php">
<input type="radio" style="font-size: 16px;font-weight: bolder" name="gender" class ="gender" value="boys">BOYS
<input type="radio" style="font-size: 16px;font-weight: bolder" name="gender" class ="gender" value="girls">GIRLS
<table id="meetTable" style="width:auto">
<tr>
<th>EVENT:</th>
<th>NAME:</th>
<th>LANE:</th>
<th>TIME:</th>
<th>PLACE:</th>
<th>SCORE 1:</th>
<th>SCORE 2:</th>
<th>PLACE:</th>
<th>TIME:</th>
<th>LANE:</th>
<th>NAME:</th>
</tr>
</table>
<input type="submit" name="formSubmit" value="Submit" />
<input type="hidden" name="action1" value="addSwimmer" id="action1">
</form>
```
This is my PHP getting the $options from mySQL
```
if ($result->num_rows > 0) {
$options= '';
// output data of each row
while($row = $result->fetch_assoc()) {
$options .= "<tr><td>" . $row["swimmer_id"]. "</td><td>" . $row["first_name"]. " " . $row["last_name"]. " </td><td> " . $row["school_name"]. "</td></tr>";
}
} else {
echo "0 results";
}
echo $options;
$conn->close();
```
ScreenShots:
[](https://i.stack.imgur.com/88Iy3.png)
[](https://i.stack.imgur.com/iguBI.png)
Options echoed into select box:
```
<select id ="s1" name="swimopt" class="so">
<?php echo $options; ?>
</select>'
```
PHP file code
```
$sql = "select first_name, last_name from swimming where gender='m'";
$results = mysqli_query($link,$sql);
if ($results->num_rows > 0) {
$options = '';
// output data of each row
while($row = $results->fetch_assoc()) {
$fname=$row["first_name"];
$lname=$row["last_name"];
$options .= "<option value= >" . $row["first_name"] . " " . $row["last_name"]."</option>";
}
} else {
echo "0 results";
}
echo $options;
$link->close();
?>
``` | 2015/11/02 | [
"https://Stackoverflow.com/questions/33487146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5451365/"
] | Try:
```
library(cgwtools)
res <- seqle(which(df<0))
sum(res$lengths[res$lengths>=6])
[1] 13
``` | you can always define your own function and call it.
```
NegativeValues <- function(x) {
count <- 0
innercount <- 0
for (i in c(x, 0)) {
if (i < 0) {
innercount <- innercount + 1
}
else {
if (innercount >= 6)
count <- count + innercount
innercount <- 0
}
}
return(count)
}
NegativeValues(df$Values)
``` |
9,008,176 | I am building a site for my professor and am trying not to repeat my code, because i will be failed for this.
I have the following .getJson call that I would like to use in multiple locations so that i do not have to repeat code superfluously.
```
function GetJSON()
{
var a = $.getJSON("/controller_name/action", null, function (z) {})
.success(function (z) {
//Success Action
})
.error(function (z) {
//Error Action
})
.complete(function (z) {
//Complete Action
});
}
```
I could pass in variables the success, error, and complete events, but I thought that this way has the potential to get very messy. Is there a way to set this up so that I do not have to have the same function GetJSON all over my site. | 2012/01/25 | [
"https://Stackoverflow.com/questions/9008176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/981190/"
] | If your professor is up to date with current paradigms, you should be *returning* `a` (the returned value of `$.getJSON`).
It's a *deferred* object, and you can attach handlers to it any time you please, and don't have to attach them within your own `GetJSON()` function.
If you have common actions that you *always* want to happen, put those inside the `GetJSON()` function, and use the externally bound handlers for actions that are unique:
```
function GetJSON()
{
var a = $.getJSON("/controller_name/action", null, function (z) {
...
});
// bind functions that you always want to happen here
a.fail(function(z) {
console.log("something bad happened");
});
return a;
}
var d = GetJSON();
// bind additional functions here
d.done(
// Success Action
})
.fail(function (z) {
// Error Action
})
.always(function (z) {
// Complete Action
});
```
Note that jQuery 1.7 has deprecated `.success`, `.error` and `.complete` in favour of the functions used above, for consistency with other Deferred objects. | I wouldn't say that's repeating code actually IMHO (unless you make the same request and update the same elements everytime). If the callbacks en request url are different everytime there isn't really a need to write a 'wrapper' for it IMHO.
The way I see it as a 'native' function. E.g. `console.log()` for example. You don't want to write a function which wraps around that do you?
That being said if you really need / want to do it you would just have to pass all params / callbacks to the function. |
2,905 | If you're now living in a new country and have a US passport, and decide to take on the citizenship of said new country - sometimes you're unable to have dual citizenship. In this case, let's say you've giving up your US citizenship; what must you do with your US passports? Do they remain active until they run out? | 2014/09/11 | [
"https://expatriates.stackexchange.com/questions/2905",
"https://expatriates.stackexchange.com",
"https://expatriates.stackexchange.com/users/97/"
] | When United States citizens renounce their citizenship, the consular officer will punch holes in your passport just like when they void an old passport when giving you a new one.
There was an article in the Korea Herald about this several years ago.
>
> Herald: In 1997, you gave up your U.S. citizenship and became a
> full-fledged Korean. What made you decide to do that?
>
>
> Robert Holley: That's a long story. Actually, the first time I saw Lee
> Han-woo on TV, my wife told me he had Korean citizenship. [Imitates
> wife] "Isn't that wonderful!" I remember thinking, "What kind of crazy
> guy would give up his citizenship to stay in Korea?!" So I got into
> broadcasting and I was running into all sorts of problems working and
> I had been in Korea for the longest time. My wife said one day, "Why
> don't you think about changing your citizenship?" So I started to
> think about it seriously and I sat down with these others (Lee,
> Daussy, et al.) and said, "How do you feel about this?" They said,
> "Look. This is where we live. This is where we work. Don't you want to
> enjoy the full rights of all the Koreans you live with? This is where
> you are. If you didn't want to be here, you wouldn't be." My biggest
> problem with changing my citizenship was that I love America. I love
> being American. I also heard this horror story about a woman who gave
> up her citizenship. **She said you have to sign this vow and they take
> your passport away and they punch holes in it.** They say, "You
> shouldn't do this. You should reconsider this. You may never go to the
> States again. We don't have to give you a visa, you know." It scared
> me to death. Eventually I found out it was possible to get a U.S. visa
> after giving up your citizenship. So I did it and I've never had any
> problems.
>
>
>
(Emphasis mine, story archived [here](http://www.ldskorea.net/chch59.html).)
You get to keep the canceled passport. This is important because it contains visas that were issued to you that may still be important -- even if not valid. The People's Republic of China requests all of the previous visas they have issued you when granting you another visa. | Generally the passport is considered void. The US does report cancelled/voided passports to International databases - that's how they attempted to trap Snowden in Hong Kong (he managed to pass HK border control minutes/hours before the State Department reported that his passport was revoked). Most, if not all, countries check the validity of the passport during border crossing.
If you get stuck in a foreign country using such a revoked passport you may get into trouble and your "new" country may not be able to help you (since you've effectivelly illegally entered the country you got caught at and didn't use your new passport. Some countries only allow consulates to represent their citizens only if they used that countries' passports to enter). |
31,858,560 | How to write the following code so that it will not return the error object reference not set ....
Below is the code.
```
Private Quantity As String
Public Property Quantity1() As String
Get
Return Quantity.ToString()
End Get
Set(ByVal value As String)
Quantity = value
End Set
End Property
``` | 2015/08/06 | [
"https://Stackoverflow.com/questions/31858560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1664336/"
] | The variable `jsonResult` is an array of dictionaries, so you can loop through the array with
```
for anItem in jsonResult as! [Dictionary<String, AnyObject>] { // or [[String:AnyObject]]
let personName = anItem["name"] as! String
let personID = anItem["id"] as! Int
// do something with personName and personID
}
```
In **Swift 3** the unspecified JSON type has been changed to `Any`
```
for anItem in jsonResult as! [Dictionary<String, Any>] { ... // or [[String:Any]]
``` | ```
let jsonResult: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.AllowFragments,
error:&parseError)
``` |
950,674 | Is $a^{p^n-1}=1\mod p$ where $p$ is prime number and $1\lt a\lt p-1$?
When $n=1$ by little fermats theorem theorem it is true. But i can't justify generaly whether it is correct or not. But when i give number for $p=5$ and $a=3$ , it is working. | 2014/09/29 | [
"https://math.stackexchange.com/questions/950674",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/174756/"
] | There are now quite a few excellent ones, but most of these are pitched at fairly sophisticated readers-graduate students or professional mathematicans. The thinking according to such textbooks, of course,is that the readers are very far along in thier mathematical training and are ready to use that mathematics to learn physics at a very high level. Whether or not that's true is debatable. In any event, here's a list to get you started:
*Lectures on Quantum Mechanics for Mathematics Students* by L. D. Faddeev and O. A. Yakubovskii: Really the only one for undergraduates-a beautiful and justly famous Russian treatment now in English. But even this beginning text requires a good knowledge of differential equations, real and complex analysis, linear algebra and group theory.
*Quantum Mechanics for Mathematicians* by Leon A. Takhtajan : One of several such texts for second year graduate students, most of which need at least first year graduate courses in analysis,differential geometry and topology. Excellently written,though.
*Physics for Mathematicians, Mechanics I* by Michael Spivak : Awesome book by the master. Perfect follow up to his 5 volume opus on graduate differential geometry and shows in depth what all that beautiful manifold theory was good for. Let's hope he finishes the projected other 3 volumes.
*Quantum Theory for Mathematicians* by Brian C. Hall A recent addition to the list I haven't seen. But if it's as good as his Lie groups book, it'll be well worth checking out.
*Mathematical Methods in Quantum Mechanics* by Gerald Teschl : This book is really more about the methods of quantum theory then the science itself. That being said,it's by a master and presents the material beautifully for second year graduate students.
*Quantum Field Theory* by Gerald B. Folland: Another terrific textbook by Folland, covering everything about QFT that can be made rigorous at this point,which sadly isn't as much as we'd like. You better have your graduate analysis chops on before tackling this one.
*Semi-Riemannian Geometry With Applications to Relativity* by Barrett O'Neill : Exactly what the title says it is. A classic,one of the best books on relativity theory for mathematicians. The book to read after Spivak.
*Modern Geometric Structures and Fields* by S. P. Novikov and I. A. Taimanov: An incredible and completely unorthodox beginning graduate course in differential geometry by one of the premier mathematicians in the world that completely interweaves the careful theory with virtually the entire modern structure of physics-from basic mechanics through relativity theory through the beginnings of string theory and quantum field theory.A good working knowledge of rigorous calculus of one and several variables and linear algebra is all you need to tackle this one. An absolute must have if you're interested in the relationship between mathematics and physics. I DO wish it had more exercises.
**UPDATE: I've added a few more in response to some of the other posts here:**
*Foundations of Mechanics 2nd edition* by Ralph Abraham and Jerrold E. Marsden: A remarkable and careful text for both physicists and mathematicians giving one of the first detailed presentations of classical mechanics from the modern differential geometric point of view. **Very** advanced, really for strong graduate students in mathematics or **very** strong graduate students in physics. A good follow up to Spivak's mechanics book and a first year graduate mathematics course sequence.
*Introduction to Mechanics and Symmetry: A Basic Exposition of Classical Mechanical Systems* by Jerrold E. Marsden and Tudor S. RatiuL A very mathematical first year graduate course in classical mechanics,again from the moder geometric point of view and emphasizing symmetry. Can act as the preliminary text for the text immediately preceding this one. About the same level as Spivak,but it's not as rigorous and focuses more on advanced physics then geometry. Very good collateral reading to that text.
*Symplectic Techniques in Physics* by Victor Guillemin and Shlomo Sternberg: I've never seen this book, but I've heard good things about it. It's by 2 masters,so that by itself makes it worth checking out.
*Ordinary Differential Equations* by V.I. Arnold: A terrific intermediate level course emphasizing the role of linear transformations and manifolds in the study of linear ODEs. A strong course in linear algebra and geometry is needed; this beautiful text is a must for students interested in the geometry of differential equations and physics.
*Geometrical Methods in the Theory of Ordinary Differential Equations* by V.I. Arnold: Graduate level follow up to the preceding text. An introduction to ordinary differential equations and dynamical systems emphasizing thier role in chaos theory and physics. A very difficult and sometimes mystifying book, but the sheer richness of the ideas and the interplay of math and physics makes it worth the effort.
I'll also mention in passing at the end the wonderful physics textbooks by Walter Griener. Not only are they concise,wide ranging and extremely clear, they have more solved examples then any physics book I've ever seen. They're written by a master. If you can get them in the original German and can read those,that would be even better as some errors creeped in in translation.
Hope that gets you started. Good luck! | Here is another bunch of texts. Like the ones suggested by Mathemagician1234, they are not general texts. The level of formality is variable.
**Classical mechanics**
F. Scheck, *Mechanics*, Springer, 2010. Although not specifically geared toward mathematicians, it makes use of mathematically advanced tools. I consider it the best book on classical mechanics currently available, much superior to Goldstein.
A. Fasano, S. Marmi, *Analytical Mechanics*, Oxford University Press, 2006. Thorough and complete textbook, strongly mathematically oriented (at undergraduate level).
N. M. J. Woodhouse, *Introduction to analytical dynamics*, Springer, 2009.
**Quantum mechanics:**
S. J. Gustafson and Israel, *Mathematical concepts of quantum mechanics*, Springer, 2011.
F. A. Berezin and M. A. Shubin, *The Schroedinger equation*, Kluwer, 1991.
F. A. Berezin, *The method of second quantization*, Academic Press, 1966.
**Special relativity**
G. L. Naber, *The geometry of Minkowski spacetime*, Springer, 2010. This is superbly written. There are also two other books from the author on gauge theories.
N. M. J. Woodhouse, *Special relativity*, Springer, 2003.
**Statistical mechanics**
F. A. Berezin, *Lectures on statistical physics*, [Online](http://www2.math.su.se/~mleites/books/berezin-2009-lectures.pdf)
R. A. Minlos, *Introduction to Mathematical Statistical Physics*, American Mathematical Society, 2000.
---
*Last but not the least* I'd like to suggest two (wonderful) calculus books which, instead, are full of examples taken from physics:
V. A. Zorich, *Mathematical Analysis I and II*, Springer, 2004. |
24,535,883 | I've had this design problem for the third time and I have a feeling there is a solution out there that I simply can't figure out. I am not satisfied with the way I solved it previously, so here is where you come in.
Let's say I'm designing a (C#) library that is agnostic in which system it gets used in. So I have the following classes:
```
public interface IAction
{
void Execute();
}
public class Trigger
{
private List<IAction> actions;
public void CheckConditions()
{
if (AllConditionsMet())
{
ExecuteAllActions();
}
}
private void ExecuteAllActions()
{
foreach (IAction action in actions)
{
action.Execute();
}
}
protected abstract bool AllConditionsMet();
}
public class BigBulkySystem
{
private List<Trigger> triggers;
public void CheckAllTriggers()
{
foreach (Trigger trigger in triggers)
{
trigger.CheckConditions();
}
}
}
```
So far so good. We have a list of triggers in the BigBulkySystem which we check ever so often their conditions. If the conditions are met, the trigger takes care of executing its list of actions.
The issue I'm having now is that I want to implement a layer that is specifically designed for [Unity](https://unity3d.com/). In Unity, you use [coroutines](http://docs.unity3d.com/Manual/Coroutines.html) in order to be able to wait a few frames before continuing the execution of a method. This is exactly what I'd want for the Trigger.ExecuteAllActions method. I want to wait for each action to finish executing before moving to the next. In order to do that, I would need to have different signatures for the Trigger and IAction. Here is how this would have been in Unity:
```
public interface IAction
{
IEnumerator Execute();
}
public class Trigger
{
private List<IAction> actions;
public void CheckConditions()
{
if (AllConditionsMet())
{
StartCoroutine(ExecuteAllActions());
}
}
public IEnunmerator ExecuteAllActions()
{
foreach (IAction action in actions)
{
yield return StartCoroutine(action.Execute());
}
}
}
```
Notice that a couple of methods now return IEnumerator instead of void, which is the way you define a coroutine in Unity.
Here is an example of a Unity action that moves a player object from position (0,0,0) to (1,1,1) in 5 seconds after a 3 second delay:
```
public class MovePlayerAction : IAction
{
public GameObject playerObject;
public IEnumerator Execute()
{
yield return StartCoroutine(WaitFor(3)); // Wait 3 secs
float animDuration = 5.0f;
Vector3 initialPos = Vector3.zero;
Vector3 finalPos = Vector3.one;
float t = 0;
while (t < animDuration)
{
playerObject.transform.position = Vector3.Lerp(initialPos, finalPos, t / animDuration); // Lerp between initial and final
yield return null; // Wait a frame
t += Time.deltaTime;
}
}
private IEnumerator WaitFor(float secs)
{
float t = 0;
while (t < secs)
{
yield return null; // Wait a single frame
t += Time.deltaTime;
}
}
}
```
So, my question is: **is there a way to design the system in such a way that I can keep the non-Unity layer free from IEnumerator but also have the Unity layer use them?**
I have a feeling that there is some sort of middle layer, but even so, I couldn't figure out how IAction can have simultaneously `void Execute()` and `IEnumerator Execute()`.
Thanks! | 2014/07/02 | [
"https://Stackoverflow.com/questions/24535883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | When you're consuming a class with a different interface to the one you need, you want the adapter pattern. There are a couple of variations on this, but a simple one for your case would look something like this:
```
public interface IAction
{
void Execute();
}
public interface IUnityAction
{
IEnumerator Execute();
}
public class UnityActionAdapter : IUnityAction
{
private readonly IAction Action;
public UnityActionAdapter(IAction action)
{
Action = action;
}
public IEnumerator Execute()
{
Action.Execute();
yield break; //Or whatever you need to yield here
}
}
```
**UPDATE**
In your case it looks like you'd be adapting in the other direction, so:
```
public class UnityActionAdapter : IAction
{
private readonly IUnityAction UnityAction;
public UnityActionAdapter(IAction unityAction)
{
UnityAction = action;
}
public void Execute()
{
StartCoroutine(UnityAction.Execute()); //If I'm correctly understanding how you'd execute an action here
}
}
```
Then you'd have `MovePlayerAction` implement `IUnityAction`, and instead of directly passing a `MovePlayerAction` up to your other layer, you'd wrap it in a `UnityActionAdapter` and pass that along instead.
This is assuming that you actually need to maintain the `IEnumerator` form in an interface in your Unity layer. You might be able to achieve the same thing without the need for adapters by doing something like:
```
public class MovePlayerAction : IAction
{
public GameObject playerObject;
private IEnumerator Coroutine()
{
yield return StartCoroutine(WaitFor(3)); // Wait 3 secs
float animDuration = 5.0f;
Vector3 initialPos = Vector3.zero;
Vector3 finalPos = Vector3.one;
float t = 0;
while (t < animDuration)
{
playerObject.transform.position = Vector3.Lerp(initialPos, finalPos, t / animDuration); // Lerp between initial and final
yield return null; // Wait a frame
t += Time.deltaTime;
}
}
public void Execute()
{
StartCoroutine(Coroutine());
}
private IEnumerator WaitFor(float secs)
{
float t = 0;
while (t < secs)
{
yield return null; // Wait a single frame
t += Time.deltaTime;
}
}
}
``` | What if you use Task Parallel Library ?
Sample code of Trigger where I see we can implement this (considering your Non-IEnumerator code):
```
public class Trigger
{
private readonly List<Task> TaskActions = new List<Task>();
public void AddAction(IAction action)
{
TaskActions.Add(new Task(()=>{action.Execute();})
}
public void CheckConditions()
{
if (AllConditionsMet())
{
ExecuteAllActions();
}
}
private void ExecuteAllActions()
{
foreach(Task task in TaskActions)
{
task.Start();
}
Task.WaitAll(TaskActions);
}
protected abstract bool AllConditionsMet();
}
```
Regards |
48,458,696 | I need to remove the key from the underscore.js result.
I grouped an array,this is the result I got for underscore.js:
```
{ '20': [ { Employee: 'ved', id: 20 }, { Employee: 'p', id: 20 }],
'25': [ { Employee: 'ved', id: 25 } ] }
```
I tried this \_.without method , but it won't work .
From the above result object, I need to remove the keys, i.e. `20` and `25`.
I should look like:
```
[ [ { Employee: 'ved', id: 20 },
{ Employee: 'p', id: 20 }
],
[
{ Employee: 'ved', id: 25 }
]
]
``` | 2018/01/26 | [
"https://Stackoverflow.com/questions/48458696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9002667/"
] | You can use [`Object.values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values)
```js
var data = { '20': [ { Employee: 'ved', id: 20 }, { Employee: 'p', id: 20 }],'25': [ { Employee: 'ved', id: 25 } ] },
result = Object.values(data);
console.log(result);
``` | `Object.values()` is what you need to use, like this:
```js
let input = { '20': [ { Employee: 'ved', id: 20 }, { Employee: 'p', id: 20 }], '25': [ { Employee: 'ved', id: 25 } ] };
console.log(Object.values(input));
``` |
57,167,958 | //I am trying to learn/understand to create a one-dimensional array which contains, in exact order, the array indices used to access a given number within a multi dimensional array
```
var multiDimensionalArray = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, [13, 14, [15]]]]]];
```
// to access 15...
```
fifteen = multiDimensionalArray[3][3][3][3][2][0];
```
// Define the variable 'indexArray' here:
```
indexArray = fifteen.join();
```
//join method does not work for me. I have tried concat, slice, indexOf methods. Can't seem to be able to find the solution for this part. HELP!
// This will log your variables to the console
```
console.log(fifteen); //15
```
console.log(indexArray); //[3, 3, 3, 3, 2, 0] | 2019/07/23 | [
"https://Stackoverflow.com/questions/57167958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11772136/"
] | I had a similar situation, and I deleted `ansible_python_interpreter=/usr/bin/python3` from my inventory and it worked. | To fix, I added `ansible_python_interpreter=/usr/bin/python3` to the host in my hosts file.
eg.
```
[web]
123.4.5.6
```
became:
```
[web]
123.4.5.6 ansible_python_interpreter=/usr/bin/python3
``` |
16,156,959 | I have PhotoView class (subclass of UIButton) and I would like that when I press any button that is class of PhotoView, same action should be triggered.
I tried something like:
```
- (void)didSelectButton:(PhotoView *)sender
{
// do something
}
``` | 2013/04/22 | [
"https://Stackoverflow.com/questions/16156959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1832330/"
] | There are 3 scenarios in which a message could be *thought of* as being sent or posted to a process:
1. I can "send" or "post" a [window] message to a specific process by sending it to the first enumerated window in that process
2. I can "post" a [thread] message to a specific process by posting it to the first enumerated thread in the process.
3. I can "post" a [thread] message to a specific process by posting it to the thread that owns the first enumerated window of that process.
Approach 1 may be too specific, since it targets a specific but arbitrary window.
Approach 2 may be not specific enough, since the first enumerated thread is arbitrary and may not have a message loop.
Approach 3 is a hybrid approach that first identifies a window, but then posts a thread message to that window's thread, so it is not targetted at a specific window (i.e. it's a "thread message") but it is targetted at a thread that is likely to have a message loop since the thread owns at least one window.
The following is an implementation that supports all three approaches and both methods "send" and "post". Approach 1 is encompassed by the methods SendMessage and PostMessage below. Approach 2 and 3 are encompassed by the method PostThreadMessage below, depending on whether you set the optional parameter `ensureTargetThreadHasWindow` (true = approach 3, false = approach 2).
```
public static class ProcessExtensions
{
private static class Win32
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
public static extern bool PostThreadMessage(uint threadId, uint msg, IntPtr wParam, IntPtr lParam);
public delegate bool EnumThreadDelegate (IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
public static extern bool EnumThreadWindows(uint dwThreadId, EnumThreadDelegate lpfn, IntPtr lParam);
[DllImport("user32.dll", SetLastError=true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
}
//Sends a message to the first enumerated window in the first enumerated thread with at least one window, and returns the handle of that window through the hwnd output parameter if such a window was enumerated. If a window was enumerated, the return value is the return value of the SendMessage call, otherwise the return value is zero.
public static IntPtr SendMessage( this Process p, out IntPtr hwnd, UInt32 msg, IntPtr wParam, IntPtr lParam )
{
hwnd = p.WindowHandles().FirstOrDefault();
if (hwnd != IntPtr.Zero)
return Win32.SendMessage( hwnd, msg, wParam, lParam );
else
return IntPtr.Zero;
}
//Posts a message to the first enumerated window in the first enumerated thread with at least one window, and returns the handle of that window through the hwnd output parameter if such a window was enumerated. If a window was enumerated, the return value is the return value of the PostMessage call, otherwise the return value is false.
public static bool PostMessage( this Process p, out IntPtr hwnd, UInt32 msg, IntPtr wParam, IntPtr lParam )
{
hwnd = p.WindowHandles().FirstOrDefault();
if (hwnd != IntPtr.Zero)
return Win32.PostMessage( hwnd, msg, wParam, lParam );
else
return false;
}
//Posts a thread message to the first enumerated thread (when ensureTargetThreadHasWindow is false), or posts a thread message to the first enumerated thread with a window, unless no windows are found in which case the call fails. If an appropriate thread was found, the return value is the return value of PostThreadMessage call, otherwise the return value is false.
public static bool PostThreadMessage( this Process p, UInt32 msg, IntPtr wParam, IntPtr lParam, bool ensureTargetThreadHasWindow = true )
{
uint targetThreadId = 0;
if (ensureTargetThreadHasWindow)
{
IntPtr hwnd = p.WindowHandles().FirstOrDefault();
uint processId = 0;
if (hwnd != IntPtr.Zero)
targetThreadId = Win32.GetWindowThreadProcessId( hwnd, out processId );
}
else
{
targetThreadId = (uint)p.Threads[0].Id;
}
if (targetThreadId != 0)
return Win32.PostThreadMessage( targetThreadId, msg, wParam, lParam );
else
return false;
}
public static IEnumerable<IntPtr> WindowHandles( this Process process )
{
var handles = new List<IntPtr>();
foreach (ProcessThread thread in process.Threads)
Win32.EnumThreadWindows( (uint)thread.Id, (hWnd, lParam) => { handles.Add(hWnd); return true; }, IntPtr.Zero );
return handles;
}
}
```
To use this extension method on a Process object:
```
Process process = Process.Start( exePath, args );
IntPtr hwndMessageWasSentTo = IntPtr.Zero; //this will receive a non-zero value if SendMessage was called successfully
uint msg = 0xC000; //The message you want to send
IntPtr wParam = IntPtr.Zero; //The wParam value to pass to SendMessage
IntPtr lParam = IntPtr.Zero; //The lParam value to pass to SendMessage
IntPtr returnValue = process.SendMessage( out hwndMessageWasSentTo, msg, wParam, lParam );
if (hwndMessageWasSentTo != IntPtr.Zero)
Console.WriteLine( "Message successfully sent to hwnd: " + hwndMessageWasSentTo.ToString() + " and return value was: " + returnValue.ToString() );
else
Console.WriteLine( "No windows found in process. SendMessage was not called." );
``` | I just answered a very similar question (with sample code) [here](https://stackoverflow.com/a/61603909/420400).
The quick answer is `PostThreadMessage()`. |
3,842,507 | In Axler's proof of the dimension of sum formula (page 47 of Linear Algebra Done Right), there is a step that requires showing that $u\_1,...,u\_m,v\_1,...,v\_j,w\_1,...w\_k$ is a basis of $U\_1+U\_2$.
Now, I understand that first I have to show that this set of vectors spans $U\_1+U\_2$. However, he says:
"Clearly span($u\_1,...,u\_m,v\_1,...,v\_j,w\_1,...w\_k$) contains $U\_1$ and $U\_2$, and hence equals $U\_1+U\_2$."
Why does that chain of logic lead to $U\_1+U\_2 =$ span($u\_1,...,u\_m,v\_1,...,v\_j,w\_1,...w\_k$)? Isn't it supposed to lead to $U\_1+U\_2 \subseteq $ span($u\_1,...,u\_m,v\_1,...,v\_j,w\_1,...w\_k$)? What about showing that span($u\_1,...,u\_m,v\_1,...,v\_j,w\_1,...w\_k$) $\subseteq$ $U\_1+U\_2$? What does it exactly mean to say that $u\_1,...,u\_m,v\_1,...,v\_j,w\_1,...w\_k$ spans $U\_1+U\_2$? | 2020/09/27 | [
"https://math.stackexchange.com/questions/3842507",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/829617/"
] | I'll add a little more. You are right that one technically has to show both inclusions.
The since every vector $u\_{i}$, $v\_{j}$, $w\_{k}$ is in $U\_{1}+U\_{2}$, the span of them is in $U\_{1}+U\_{2}$ because it's a vector subspace (closed under vector addition and scalar multiplication). Now every vector $v\in U\_{1}+U\_{2}$ is the sum $v\_{1}+v\_{2}$ for $v\_{i}\in U\_{i}$. Now the $u\_{i}$ with the $v\_{j}$ give a basis for $V\_{1}$ so $v\_{1}=\sum a\_{i}u\_{i} +\sum b\_{j}v\_{j}$ and similarly, $v\_{2} = \sum\tilde{a}\_{i}u\_{i}+\sum\tilde{b}\_{i}w\_{j}$. Puting these together yeilds
$$
\begin{align}v&=\sum a\_{i}u\_{i} +\sum b\_{j}v\_{j}+ \sum\tilde{a}\_{i}u\_{i}+\sum\tilde{b}\_{i}w\_{j}\\
&=\sum (a\_{i}+\tilde{a}\_{i})u\_{i}+\sum b\_{j}v\_{j}+\sum\tilde{b}\_{i}w\_{j}
\end{align}
$$
So you have the reverse inclusion as well. | Equality is pretty clear, from the definitions of span and the sum of two vector spaces. That is, the latter is just the set of all sums.
There couldn't be anything in the span of the given vectors (though you didn't say what they are) that isn't a sum of elements of $U\_1$ and $U\_2$. This follows if all the basis vectors are elements of $U\_1$ or $U\_2$.
Axler evidently thought the other inclusion a little more difficult, and that's understandable. |
11,608,238 | Consider the following list comprehension
```
[ (x,f(x)) for x in iterable if f(x) ]
```
This filters the iterable based a condition `f` and returns the pairs of `x,f(x)`. The problem with this approach is `f(x)` is calculated twice.
It would be great if we could write like
```
[ (x,fx) for x in iterable if fx where fx = f(x) ]
or
[ (x,fx) for x in iterable if fx with f(x) as fx ]
```
But in python we have to write using nested comprehensions to avoid duplicate call to f(x) and it makes the comprehension look less clear
```
[ (x,fx) for x,fx in ( (y,f(y) for y in iterable ) if fx ]
```
Is there any other way to make it more pythonic and readable?
---
**Update**
Coming soon in python 3.8! [PEP](https://www.python.org/dev/peps/pep-0572/#syntax-and-semantics)
```
# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]
``` | 2012/07/23 | [
"https://Stackoverflow.com/questions/11608238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/463758/"
] | Nothing says you must use comprehensions. In fact most style guides I've seen request that you limit them to simple constructs, anyway.
You could use a generator expression, instead.
```
def fun(iterable):
for x in iterable:
y = f(x)
if y:
yield x, y
print list(fun(iterable))
``` | Map and Zip ?
```
fnRes = map(f, iterable)
[(x,fx) for x,fx in zip(iterable, fnRes) if fx)]
``` |
4,335,576 | $X\sim N(0,1)$, find probability density function of $Y=e^X$.
Define $\psi:=e^X$, since $\psi$ is a monotonic continues function then $\frac{f\_X(X)}{|\psi'(X)|}=f\_{\psi(X)}(X)=f\_Y(Y)$.
$\frac{\frac{1}{\sqrt{2\pi}}e^\frac{-x^2}{2}}{ln(y)y}=f\_Y
$
I am not sure that i can use this theorem.
Is it correct ?
Thanks! | 2021/12/16 | [
"https://math.stackexchange.com/questions/4335576",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/960082/"
] | No it is not correct
$$f\_Y(y)=\frac{1}{y\sqrt{2\pi}}e^{-\log^2(x)/2}$$
It's a LogNormal density | The cumulative probability function of $Y$ is :
$$P(Y\leq t) =P(e^X\leq t)=P(X\leq \ln(t))=\int\_{-\infty}^{\ln(t)}f\_X(u)du$$
since $f\_Y (t) = \frac{d}{dt} P(Y\leq t)$, by the FTC and the chain rule you get:
$$f\_Y(t)=\frac{f\_X(\ln(t))}{t}$$
Using that $X\sim N(0,1)$
$$f\_Y(t)=\frac{1}{t\sqrt{2\pi}}e^{-\frac{\ln(t)^2}{2}}$$ |
1,765,010 | **Input**:
I have the following data;
| | C | D |
| --- | --- | --- |
| 1 | $1 | ABC |
| 2 | $2 | ABC |
| 3 | $3 | DEF |
| 4 | $4 | ABC |
I want to create another table in the same sheet where I want to add the values in Column `C` based on the keys in Column `D`.
**Output**:
| | G | H |
| --- | --- | --- |
| 1 | ABC | $7 |
| 2 | DEF | $3 |
Here $7 is the sum of values corresponding to ABC and $3 is the sum of values corresponding to DEF.
So I need something like `"= Sum of values in Column C corresponding to Key in G1 found in Column D"` in H1 and so on...
What's the best way to achieve this instead of adding the values manually?
Thank you for your help. | 2023/01/26 | [
"https://superuser.com/questions/1765010",
"https://superuser.com",
"https://superuser.com/users/773310/"
] | There's really no way of doing this that I know of. If you want performance, you could probably change the console scrollback and all that stuff, but the change is going to be small. Killing all unneeded processes will likely have the largest effect. You can mass kill processes with these commands (make sure cmd is open in administrator mode):
**tasklist** (so you can see the processes you don't need, or you could just use task manager, whatever suits you)
**taskkill /im** {insert process name here. You can use wildcard here, eg: a\* would kill anything starting with a, and {wildcard}a{wildcard} (it made it italic if I had both surrounding the letter) would kill anything with a in it, and I think you get the idea about \*a by now.} **/F** (forces it to be killed) | The bug-report
[Slow reponse to scroll and typing #107016](https://github.com/microsoft/vscode/issues/107016)
is about this very problem.
There are no solutions for the problem, just workarounds, since a real
solution must come from the VScode team.
Most workarounds seem to indicate that VScode is very inefficient on using
the GPU.
The following switches were reported as improving the performance:
* `--disable-gpu`
* `--disable-gpu-compositing`
For NVIDIA, one user solved the problem in the NVIDIA Control Panel by
creating an NVIDIA profile for `code.exe` which has in it only
the one setting `0x10B135FE` with the value of `0x00000000`.
This setting is said to remove the default framerate limit
from VScode.
With this profile, the issue was solved on his computer. |
2,964 | It is a bit late into this new year, being that we're already in the second month, but we are now cycling the Community Promotion Ads for 2017!
### What are Community Promotion Ads?
Community Promotion Ads are community-vetted advertisements that will show up on the main site, in the right sidebar. The purpose of this question is the vetting process. Images of the advertisements are provided, and community voting will enable the advertisements to be shown.
### Why do we have Community Promotion Ads?
This is a method for the community to control what gets promoted to visitors on the site. For example, you might promote the following things:
* interesting apple related open source apps
* the site's twitter account
* script packs or power tools
* cool events or conferences
* anything else your community would genuinely be interested in
The goal is for future visitors to find out about *the stuff your community deems important*. This also serves as a way to promote information and resources that are *relevant to your own community's interests*, both for those already in the community and those yet to join.
### Why do we reset the ads every year?
Some services will maintain usefulness over the years, while other things will wane to allow for new faces to show up. Resetting the ads every year helps accommodate this, and allows old ads that have served their purpose to be cycled out for fresher ads for newer things. This helps keep the material in the ads relevant to not just the subject matter of the community, but to the current status of the community. We reset the ads once a year, every December.
The community promotion ads have no restrictions against reposting an ad from a previous cycle. If a particular service or ad is very valuable to the community and will continue to be so, it is a good idea to repost it. It may be helpful to give it a new face in the process, so as to prevent the imagery of the ad from getting stale after a year of exposure.
### How does it work?
The answers you post to this question *must* conform to the following rules, or they will be ignored.
1. All answers should be in the exact form of:
```
[![Tagline to show on mouseover][1]][2]
[1]: http://image-url
[2]: http://clickthrough-url
```
Please **do not add anything else to the body of the post**. If you want to discuss something, do it in the comments.
2. The question must always be tagged with the magic [community-ads](/questions/tagged/community-ads "show questions tagged 'community-ads'") tag. In addition to enabling the functionality of the advertisements, this tag also pre-fills the answer form with the above required form.
### Image requirements
* The image that you create must be 300 x 250 pixels, or double that if high DPI.
* Must be hosted through our standard image uploader (imgur)
* Must be GIF or PNG
* No animated GIFs
* Absolute limit on file size of 150 KB
* If the background of the image is white or partially white, there must be a 1px border (2px if high DPI) surrounding it.
### Score Threshold
There is a **minimum score threshold** an answer must meet (currently **6**) before it will be shown on the main site.
You can check out the ads that have met the threshold with basic click stats [here](https://apple.meta.stackexchange.com/ads/display/2964). | 2017/02/02 | [
"https://apple.meta.stackexchange.com/questions/2964",
"https://apple.meta.stackexchange.com",
"https://apple.meta.stackexchange.com/users/8994/"
] | [](http://iot.stackexchange.com) | [](http://twitter.com/askdifferent) |
2,518,816 | I know that it's OK for a pure virtual function to have an implementation. However, why it is like this? Is there conflict for the two concepts? What's the usage? Can any one offer any example? | 2010/03/25 | [
"https://Stackoverflow.com/questions/2518816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233254/"
] | Was addressed in [GotW #31](http://www.gotw.ca/gotw/031.htm). Summary:
>
> There are three main reasons you might
> do this. #1 is commonplace, #2 is
> pretty rare, and #3 is a workaround
> used occasionally by advanced
> programmers working with weaker
> compilers.
>
>
> Most programmers should only ever use #1.
>
>
>
... Which is for pure virtual destructors. | That way you can provide a working implementation but still require the child class implementer to explicitely call that implementation. |
7,496,816 | [A previous question](https://stackoverflow.com/questions/5640369/ienumerablet-null-coalescing-extension) discusses IEnumerable and the convention of using empty collections instead of null valued ones. It is a good practice as it does away with many mistake-prone null checks.
But the answers don't quite address one of the cases. Many times I'm *forced* to deal with null values, specifically when arrays are returned from foreign methods. An example:
```
(foreignObj.GetPeople() ?? Enumerable.Empty<Person>())
.Where(p => p.Name != "John")
.OrderBy(p => p.Name)
.Take(4);
```
I've written a helper method which does improve readability somewhat.
```
public class SafeEnumerable
{
public static IEnumerable<T> From<T>(T[] arr)
{
return arr ?? Enumerable.Empty<T>();
}
}
```
Resulting in:
```
SafeEnumerable.From(foreignObj.GetPeople())
.Where(p => p.Name != "John")
.OrderBy(p => p.Name)
.Take(4);
```
I don't mind this, but I'm looking for better ideas. It seems like I'm adding something that should be there already. | 2011/09/21 | [
"https://Stackoverflow.com/questions/7496816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421455/"
] | The problem locates where you got the collection(`IEnumerable<T>`). If you are always busy with checking for `null` values of a collection, you should consider to modify the source. For example:
```
public User GetUser(long id) { }
public List<User> GetUsers(long companyId) { }
```
The first method makes sense if it returns a `null` when no user is found, a `null` return value means *not found*. But the second method, in my opinion, should never return a `null` in any normal circumstance. If no users found, an empty list should be returned, instead of a `null` value, which means **something of the program is incorrect**. And the given example in your question, I don't believe `directoryInfo.GetFiles("*.txt")` returns null if no `txt` file is found, instead it should return an empty collection. | Unfortunately I don't think that there is anything built-in for this. Unless you repeat yourself:
```
foreach(var item in (GetUsers() ?? new User[0])) // ...
```
A slightly 'better' implementation (taking example from what the C# compiler generates for the `yield return` sytnax), which is **marginally** less wastefuly with memory:
```
class SafeEnumerable<T> : IEnumerable<T>, IEnumerator<T>
{
private IEnumerable<T> _enumerable;
public SafeEnumerable(IEnumerable<T> enumerable) { _enumerable = enumerable; }
public IEnumerator<T> GetEnumerator()
{
if (_enumerable == null)
return this;
else
return _enumerable.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
public T Current { get { throw new InvalidOperationException(); } }
object System.Collections.IEnumerator.Current { get { throw new InvalidOperationException(); } }
public bool MoveNext() { return false; }
public void Reset() { }
public void Dispose() { }
}
``` |
11,611,850 | I've installed a database on an instance of SQL Server Express. My client application runs and succesfully connects with the database when I run the app from the server machine. However the application will not connect to the database when I run it on other PCs on the same network. I keep getting the error message:
>
> A network-related or instance specific error occurred while establishing a connection to SQL Server . . . . . error 26 - Error Locating Server / Instance Specified
>
>
>
When I have had this error in the past it was because the SQL Browser service was not running. However when I look for SQL Browser in services on the server, it simply isn't there.
Any ideas would be appreciated. | 2012/07/23 | [
"https://Stackoverflow.com/questions/11611850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1109750/"
] | Generally these errors occurred when you call a region in your `page.tpl.php` file that doesn't exist in the theme's `.info` file.
In your `page.tpl.php`:
```
$page['footer_firstcolumn'];
```
In your theme's `.info`:
```
regions[footer_firstcolumn] = Footer first column
```
After rechecking all regions, don't forget to `flush the cache`. | If you want to create a fresh theme best practice is to use something like [Zen](http://drupal.org/project/zen/). It's blank and fully customizable.
As long as you follow the prescribed instructions, you will avoid nasty errors like the ones you have above |
38,432,993 | i m pretty new in angular2 and i have a question.
Is there a way to add more content in a component.ts that was imported from an external file ?
I have a page-header.component in multiple pages that are all the same except i change some titles like this.
```
<page-header [headerLinks]="['link1', 'link2', 'link3']"></page-header>
```
page-header.component.html looks like this:
```
<div class="page-header-links">
<a *ngFor="let headerLink of headerLinks" href="#">{{ headerLink }}</a>
</div>
```
I would like to expand the page-header-component in my next files and only in this next file. something like this:
```
<div class="page-header-links">
<a *ngFor="let headerLink of headerLinks" href="#">{{ headerLink }}</a>
</div>
add more content ---
<span class="rectangle-shape"></span>
<h3> title </h3>
<span class="rectangle-shape"></span>
and more
```
any idea how can i do this?
i tried this but maybe i miss doing something in ts file ?!
```
<page-header [headerLinks]="['link1', 'link2', 'link3']">
<span class="rectangle-shape"></span>
<h3> title </h3>
<span class="rectangle-shape"></span>
</page-header>
``` | 2016/07/18 | [
"https://Stackoverflow.com/questions/38432993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6479112/"
] | You are trying to do right:
```
<page-header [headerLinks]="['link1', 'link2', 'link3']">
<span class="rectangle-shape"></span>
<h3> title </h3>
<span class="rectangle-shape"></span>
</page-header>
```
You just need to add `<ng-content></ng-content>` inside page-header.component.html, like this:
```
<div class="page-header-links">
<a *ngFor="let headerLink of headerLinks" href="#">{{ headerLink }}</a>
</div>
<ng-content></ng-content>
``` | You can use
```
<div [innerHTML]="somePropertyWithHTML">
```
but that only adds plain HTML and doesn't resolve any bindings or instantiate Angular2 components or directives for the added HTML.
If you need this see Maybe [How to realize website with hundreds of pages in Angular2](https://stackoverflow.com/questions/36008476/how-to-realize-website-with-hundreds-of-pages-in-angular2) |
34,894,330 | I have a table in SQL Server with data that has an auto-increment column. The data in the auto increment column is not sequential. It is like `1, 2, 3, 5, 6, 7, 9` (missing 4 and 8).
I want to copy the exact data in this table to another fresh and empty identical table. The destination table also has an auto increment column.
Problem: when I copy the data using the query below, the `AttachmentID` has new and different values
```
INSERT INTO FPSDB_new.dbo.Form_Attachment
SELECT
CategoryID
FROM
FPSDB.dbo.Form_Attachment
```
the `Form_Attachment` table in destination and source is same as below
```
CREATE TABLE [dbo].[Form_Attachment]
(
[AttachmentID] [int] IDENTITY(1,1) NOT NULL,
[CategoryID] [int] NULL
)
```
Is there a SQL query solution to make the two tables with identical data? | 2016/01/20 | [
"https://Stackoverflow.com/questions/34894330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404715/"
] | You can insert into an `IDENTITY` column by using `SET IDENTITY_INSERT ON` in your transaction (don't forget to turn it off afterwards):
[How to turn IDENTITY\_INSERT on and off using SQL Server 2008?](https://stackoverflow.com/questions/7063501/how-to-turn-identity-insert-on-and-off-using-sql-server-2008)
```
SET IDENTITY_INSERT FPSDB_new.dbo.Form_Attachment ON
INSERT INTO FPSDB_new.dbo.Form_Attachment ( AttachmentID, CategoryID )
SELECT
AttachmentID,
CategoryID
FROM
FPSDB.dbo.Form_Attachment
SET IDENTITY_INSERT FPSDB_new.dbo.Form_Attachment OFF
``` | You can also do this:
1. Drop the copy table
2. Create as select, which will copy the exact structure and data to the new table.
```
Select *
into new_table
from old_table
``` |
24,362,582 | I am having a table which will store current year dates , I am having a start date in that table also. Is there any possibility to get all the dates between current and start date using CROSS APPLY.
```
Ex:
Current_Year Start_Date
2014-06-12 2011-01-01
2014-04-12 2011-01-01
2014-02-12 2011-01-01
2014-01-12 2011-01-01
I want result set like
Year
2014-06-12 2011-01-01
2014-04-12 2011-01-01
2014-02-12 2011-01-01
2014-01-12 2011-01-01
2013-06-12 2011-01-01
2013-04-12 2011-01-01
2013-02-12 2011-01-01
2013-01-12 2011-01-01
2012-06-12 2011-01-01
2012-04-12 2011-01-01
2012-02-12 2011-01-01
2012-01-12 2011-01-01
2011-06-12 2011-01-01
2011-04-12 2011-01-01
2011-02-12 2011-01-01
2011-01-12 2011-01-01
``` | 2014/06/23 | [
"https://Stackoverflow.com/questions/24362582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751754/"
] | The following will give the desired results using CROSS APPLY:
```
WITH T AS
( SELECT Current_Year = CAST(cy AS DATE), Start_Date = CAST(sd AS DATE)
FROM (VALUES
('2014-06-12', '2011-01-01'),
('2014-04-12', '2011-01-01'),
('2014-02-12', '2011-01-01'),
('2014-01-12', '2011-01-01')
) t (cy, sd)
)
SELECT Current_Year = DATEADD(YEAR, - n.Number, t.Current_Year),
t.Start_Date
FROM T
CROSS APPLY
( SELECT TOP 1000 ROW_NUMBER() OVER (ORDER BY a.object_id) - 1
FROM sys.all_objects AS a
) AS n (Number)
WHERE DATEADD(YEAR, - n.Number, t.Current_Year) > t.Start_Date;
```
But a CROSS JOIN would work equally well, and perhaps make more sense semantically, although the execution plan would end up being the same. | ```
DECLARE @TAB1 TABLE (CURRENT_YEAR DATE)
INSERT INTO @TAB1 VALUES('2014-06-12'),('2014-04-12'),('2014-02-12'),('2014-01-12')
DECLARE @TAB2 TABLE (CURRENT_YEAR DATE)
INSERT INTO @TAB2 VALUES('2011-01-01'),('2011-01-01'),('2011-01-01'),('2011-01-01')
```
SQL:
```
SELECT DATEADD(YY,
LU.[ROW] * (-1),A.CURRENT_YEAR) [YEAR],LU.CURRENT_YEAR [Static_YEAR]
FROM @TAB1 A,
(SELECT *,(ROW_NUMBER() OVER (ORDER BY CURRENT_YEAR)) - 1 [ROW] FROM @TAB2) LU
```
**Result**
 |
7,404,709 | I need to backup database (using SQL Server 2008 R2). Size of db is about 100 GB so I want backup content only of important tables (containing settings) and of course object of all tables, views, triggers etc.
For example:
* db: `Products`
* tables: `Food, Clothes, Cars`
There is too much cars in `Cars`, so I will only backup table definition (`CREATE TABLE ...`) and complete `Food` and `Clothes` (including its content).
Advise me the best solution, please. I will probably use SMO (if no better solution). Should I use `Backup` class? Or `Scripter` class? Or another (if there is any)? Which class can handle my requirements?
I want backup these files to `*.sql` files, one per table if possible.
I would appreciate code sample. Written in answer or somewhere (post url), but be sure that external article has solution exactly for this kind of problem.
You can use this part of code
```
ServerConnection connection = new ServerConnection("SERVER,1234", "User", "User1234");
Server server = new Server(connection);
Database database = server.Databases["DbToBackup"];
``` | 2011/09/13 | [
"https://Stackoverflow.com/questions/7404709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/809009/"
] | [This](http://weblogs.asp.net/shahar/archive/2010/03/03/generating-sql-backup-script-for-tables-amp-data-from-any-net-application-using-smo.aspx) arcitle was enough informative to solve my problem. Here is my working solution.
I decided script all objects to one file, it's better solution because of dependencies, I think. If there is one table per on file and there is also some dependencies (foreign keys for example) it would script more code than if everything is in one file.
I omitted some parts of code in this sample, like backuping backup files in case wrong database backup. If there is no such a system, all backups will script to one file and it will go messy
```
public class DatabaseBackup
{
private ServerConnection Connection;
private Server Server;
private Database Database;
private ScriptingOptions Options;
private string FileName;
private const string NoDataScript = "Cars";
public DatabaseBackup(string server, string login, string password, string database)
{
Connection = new ServerConnection(server, login, password);
Server = new Server(Connection);
Database = Server.Databases[database];
}
public void Backup(string fileName)
{
FileName = fileName;
SetupOptions();
foreach (Table table in Database.Tables)
{
if (!table.IsSystemObject)
{
if (NoDataScript.Contains(table.Name))
{
Options.ScriptData = false;
table.EnumScript(Options);
Options.ScriptData = true;
}
else
table.EnumScript(Options);
}
}
}
private void SetupOptions()
{
Options = new ScriptingOptions();
Options.ScriptSchema = true;
Options.ScriptData = true;
Options.ScriptDrops = false;
Options.WithDependencies = true;
Options.Indexes = true;
Options.FileName = FileName;
Options.EnforceScriptingOptions = true;
Options.IncludeHeaders = true;
Options.AppendToFile = true;
}
}
``` | What you describe is not really a Backup but I understand what your goal is:
* [Scripter sample code](http://www.sqlteam.com/article/scripting-database-objects-using-smo-updated)
* [Using SMO to get create script for table defaults](https://stackoverflow.com/questions/274408/using-smo-to-get-create-script-for-table-defaults/274578#274578)
* <http://blogs.msdn.com/b/mwories/archive/2005/05/07/basic-scripting.aspx>
* <http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scripter.aspx>
* <http://weblogs.asp.net/shahar/archive/2010/03/03/generating-sql-backup-script-for-tables-amp-data-from-any-net-application-using-smo.aspx>
* <http://en.csharp-online.net/SQL_Server_Management_Objects>
* <http://www.mssqltips.com/sqlservertip/1833/generate-scripts-for-database-objects-with-smo-for-sql-server/>
For "Backup" of Data you could load the table content via a `Reader` into a `DataTable` and store the result as XML... |
61,161,205 | Not able to click button
```
<p>
<img class="getdata-button" style="float:right;" src="/common/images/btn-get-data.gif" id="get" onclick="document.getElementById('submitMe').click()">
<input type="button" value="Get Results" tabindex="9" id="submitMe" onclick="submitData();" style="display:none" ;="">
</p>
```
Case-1.
```
sub_driver.find_element_by_xpath("//img[@class='getdata-button']").click()
```
session goes into like hung state (not actually), but nothing happened.
Case-2
```
sub_driver.find_element_by_xpath("//img[@class='getdata-button']").click()
```
throws error like : `Element not interactable` | 2020/04/11 | [
"https://Stackoverflow.com/questions/61161205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13288689/"
] | Use the builtin `numpy.savez_compressed`?
From the [numpy docs](https://docs.scipy.org/doc/numpy/reference/generated/numpy.savez_compressed.html):
```
>>> test_vector = np.random.rand(4)
>>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector)
>>> loaded = np.load('/tmp/123.npz')
>>> print(np.array_equal(test_array, loaded['a']))
True
>>> print(np.array_equal(test_vector, loaded['b']))
True
``` | so, to sum-up, i cannot use something else than zlib for now but :
* I can totaly compress/decompress a (unique) numpy array and write/read it to/from a file doing as follow :
```
row = array[0,:]
with open(outputFile, 'wb') as zFile:
print(row)
compressed = zlib.compress(row, compressionLevel)
zFile.write(compressed)
```
```
with open(os.path.join(path, fileName), 'rb') as zFile:
decompressed = zlib.decompress(zFile.read())
data = np.frombuffer(decompressed, dtype=np.float))
print(data)
```
* I added `np.frombuffer` as pointed out by sagarwal (actually `np.frombuffer` is better than `np.fromstring`) and `print(row)` and `print(data)` gives the same thing. The probleme comes when i add a for loop in the writing process to add several compressed row in the file. thus i have trouble to retrieve each full size compressed row (with a `for line in zFile: ...`) to decompress them one at a time. Indeed, some element in each compressed row are seen as `\n` and thus is does not retrieve the real lines (wich gives `zlib.error: Error -5 while decompressing data: incomplete or truncated stream`) |
1,766,342 | What is the fastest method to fill a database table with 10 Million rows? I'm asking about the technique but also about any specific database engine that would allow for a way to do this as fast as possible. I"m not requiring this data to be indexed during this initial data-table population. | 2009/11/19 | [
"https://Stackoverflow.com/questions/1766342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147141/"
] | Using SQL to load a lot of data into a database will usually result in poor performance. In order to do things quickly, you need to go around the SQL engine. Most databases (including Firebird I think) have the ability to backup all the data into a text (or maybe XML) file and to restore the entire database from such a dump file. Since the restoration process doesn't need to be transaction aware and the data isn't represented as SQL, it is usually very quick.
I would write a script that generates a dump file by hand, and then use the database's restore utility to load the data.
After a bit of searching I found [FBExport](http://fbexport.sourceforge.net/), that seems to be able to do exactly that - you'll just need to generate a CSV file and then use the FBExport tool to import that data into your database. | Use MySQL or MS SQL and embedded functions to generate records inside the database engine. Or generate a text file (in cvs like format) and then use Bulk copy functionality. |
1,338,045 | I can only assume this is a bug. The first assert passes while the second fails:
```
double sum_1 = 4.0 + 6.3;
assert(sum_1 == 4.0 + 6.3);
double t1 = 4.0, t2 = 6.3;
double sum_2 = t1 + t2;
assert(sum_2 == t1 + t2);
```
If not a bug, why? | 2009/08/26 | [
"https://Stackoverflow.com/questions/1338045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163867/"
] | This is something that has bitten me, too.
Yes, floating point numbers should never be compared for equality because of rounding error, and you probably knew that.
But in this case, you're computing `t1+t2`, then computing it again. *Surely* that has to produce an identical result?
Here's what's probably going on. I'll bet you're running this on an x86 CPU, correct? The x86 FPU uses 80 bits for its internal registers, but values in memory are stored as 64-bit doubles.
So `t1+t2` is first computed with 80 bits of precision, then -- I presume -- stored out to memory in `sum_2` with 64 bits of precision -- and some rounding occurs. For the assert, it's loaded back into a floating point register, and `t1+t2` is computed again, again with 80 bits of precision. So now you're comparing `sum_2`, which was previously rounded to a 64-bit floating point value, with `t1+t2`, which was computed with higher precision (80 bits) -- and that's why the values aren't exactly identical.
*Edit* So why does the first test pass? In this case, the compiler probably evaluates `4.0+6.3` at compile time and stores it as a 64-bit quantity -- both for the assignment and for the assert. So identical values are being compared, and the assert passes.
*Second Edit* Here's the assembly code generated for the second part of the code (gcc, x86), with comments -- pretty much follows the scenario outlined above:
```
// t1 = 4.0
fldl LC3
fstpl -16(%ebp)
// t2 = 6.3
fldl LC4
fstpl -24(%ebp)
// sum_2 = t1+t2
fldl -16(%ebp)
faddl -24(%ebp)
fstpl -32(%ebp)
// Compute t1+t2 again
fldl -16(%ebp)
faddl -24(%ebp)
// Load sum_2 from memory and compare
fldl -32(%ebp)
fxch %st(1)
fucompp
```
Interesting side note: This was compiled without optimization. When it's compiled with `-O3`, the compiler optimizes *all* of the code away. | When comparing floating point numbers for closeness you usually want to measure their relative difference, which is defined as
```
if (abs(x) != 0 || abs(y) != 0)
rel_diff (x, y) = abs((x - y) / max(abs(x),abs(y))
else
rel_diff(x,y) = max(abs(x),abs(y))
```
For example,
```
rel_diff(1.12345, 1.12367) = 0.000195787019
rel_diff(112345.0, 112367.0) = 0.000195787019
rel_diff(112345E100, 112367E100) = 0.000195787019
```
The idea is to measure the number of leading significant digits the numbers have in common; if you take the -log10 of 0.000195787019 you get 3.70821611, which is about the number of leading base 10 digits all the examples have in common.
If you need to determine if two floating point numbers are equal you should do something like
```
if (rel_diff(x,y) < error_factor * machine_epsilon()) then
print "equal\n";
```
where machine epsilon is the smallest number that can be held in the mantissa of the floating point hardware being used. Most computer languages have a function call to get this value. error\_factor should be based on the number of significant digits you think will be consumed by rounding errors (and others) in the calculations of the numbers x and y. For example, if I knew that x and y were the result of about 1000 summations and did not know any bounds on the numbers being summed, I would set error\_factor to about 100.
Tried to add these as links but couldn't since this is my first post:
* en.wikipedia.org/wiki/Relative\_difference
* en.wikipedia.org/wiki/Machine\_epsilon
* en.wikipedia.org/wiki/Significand (mantissa)
* en.wikipedia.org/wiki/Rounding\_error |
3,498,005 | Are there any existing user authentication libraries for node.js? In particular I'm looking for something that can do password authentication for a user (using a custom backend auth DB), and associate that user with a session.
Before I wrote an auth library, I figured I would see if folks knew of existing libraries. Couldn't find anything obvious via a google search.
-Shreyas | 2010/08/16 | [
"https://Stackoverflow.com/questions/3498005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170589/"
] | I was basically looking for the same thing. Specifically, I wanted the following:
1. To use express.js, which wraps Connect's middleware capability
2. "Form based" authentication
3. Granular control over which routes are authenticated
4. A database back-end for users/passwords
5. Use sessions
What I ended up doing was creating my own middleware function `check_auth` that I pass as an argument to each route I want authenticated. `check_auth` merely checks the session and if the user is not logged in, then redirects them to the login page, like so:
```js
function check_auth(req, res, next) {
// if the user isn't logged in, redirect them to a login page
if(!req.session.login) {
res.redirect("/login");
return; // the buck stops here... we do not call next(), because
// we don't want to proceed; instead we want to show a login page
}
// the user is logged in, so call next()
next();
}
```
Then for each route, I ensure this function is passed as middleware. For example:
```js
app.get('/tasks', check_auth, function(req, res) {
// snip
});
```
Finally, we need to actually handle the login process. This is straightforward:
```js
app.get('/login', function(req, res) {
res.render("login", {layout:false});
});
app.post('/login', function(req, res) {
// here, I'm using mongoose.js to search for the user in mongodb
var user_query = UserModel.findOne({email:req.body.email}, function(err, user){
if(err) {
res.render("login", {layout:false, locals:{ error:err } });
return;
}
if(!user || user.password != req.body.password) {
res.render("login",
{layout:false,
locals:{ error:"Invalid login!", email:req.body.email }
}
);
} else {
// successful login; store the session info
req.session.login = req.body.email;
res.redirect("/");
}
});
});
```
At any rate, this approach was mostly designed to be flexible and simple. I'm sure there are numerous ways to improve it. If you have any, I'd very much like your feedback.
EDIT: This is a simplified example. In a production system, you'd never want to store & compare passwords in plain text. As a commenter points out, there are libs that can help manage password security. | A different take on authentication is Passwordless, a [token-based authentication](https://passwordless.net) module for express that circumvents the inherent problem of passwords [1]. It's fast to implement, doesn't require too many forms, and offers better security for the average user (full disclosure: I'm the author).
[1]: [Passwords are Obsolete](https://medium.com/@ninjudd/passwords-are-obsolete-9ed56d483eb) |
35,699,502 | I've finally got two pickers into one viewcontroller and i've realised they're a little tricky to see because the background is dark. How do I go about changing the colour of the pickers text?
Here's my whole view controller M
```
//
// ViewController.m
// Repayment Calculator
//
// Created by Stewart Piper-Smith on 04/11/2015.
// Copyright (c) 2015 Stewart Piper-Smith. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
NSArray *_pickerViewArray;
NSArray *CareerViewArray;
@implementation ViewController
@synthesize button1, textbox1, textbox2, textbox3, startingsalary, repaymentlabel, debtlabel, startingrepayments, timetakentopayoffloan, realtimetakentopayoffloan, debtamounttextfield, annualrepaymentstextfield, monthlyrepaymentstextfield,weeklyrepaymentstextfield, payoffloantextfield, testlabel, annualrepaymentstest, totaldebtamounttest, writtenofflabel,payoffloanlabel,newlabel;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// - (IBAction)button1Press:(id)sender {
// [button1 setTitle:textbox1.text forState:UIControlStateNormal];
// }
//The start of the calculate button that starts the calculations.
-(IBAction)menucontactbuttonPress:(id)sender {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Error"
message:@"Contact Form Coming Soon"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
-(IBAction)button1Press:(id)sender
{
[self.view endEditing:YES];
int x = ([textbox1.text intValue]);
int y = ([textbox2.text intValue]);
int q = ([textbox3.text intValue]);
float startingsal = ([startingsalary.text intValue]);
int debtamounttfield = ([debtamounttextfield.text intValue]);
float annualrepayments = ([annualrepaymentstextfield.text floatValue]);
//PROBLEM STARTS
float p1 = debtamounttfield /annualrepayments;//([debtamounttextfield.text intValue]);
if(isnan(p1) || isinf(p1)){
p1 = 0.00;
}
//int a = ([annualrepaymentstextfield.text intValue]);
//int b = ([debtamounttextfield.text intValue]);
//[newlabel setText:[NSString stringWithFormat:@"%@", a/b]];
[testlabel setText:[NSString stringWithFormat:@"%.01f",p1]];
[totaldebtamounttest setText:[NSString stringWithFormat:@"%d", debtamounttfield]];
[annualrepaymentstest setText:[NSString stringWithFormat:@"%@", annualrepaymentstextfield]];
[payoffloantextfield setText:[NSString stringWithFormat:@"%.01f", p1]];
//PROBLEM ENDS
[debtamounttextfield setText:[NSString stringWithFormat:@"£" "%i" , (x + y) * q]];
int arp = (startingsal - 17335)*0.09;
[annualrepaymentstextfield setText:[NSString stringWithFormat:@"£" "%i", arp ]];
if (arp < 0) {
annualrepaymentstextfield.text = @"Written Off";
}
int monthlyrepayments = (startingsal - 17335)*0.09/12;
[monthlyrepaymentstextfield setText:[NSString stringWithFormat:@"£" "%i", monthlyrepayments]];
if (monthlyrepayments < 0){
monthlyrepaymentstextfield.text = @"Written Off";
}
int weeklyrepayments = (startingsal - 17335)*0.09/12/4;
[weeklyrepaymentstextfield setText:[NSString stringWithFormat:@"£" "%i", weeklyrepayments]];
if (weeklyrepayments < 0){
weeklyrepaymentstextfield.text = @"Written Off";
}
//Error Handling
//Enter starting salary
if ([annualrepaymentstextfield.text isEqualToString: @"Written Off"]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Debt Written Off"
message:@"As it will take you longer than 30 years to pay off the loan, the debt would be written off."
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
if ([startingsalary.text isEqualToString: @""]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Error"
message:@"Please enter your expected starting salary"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
//If course length is equal to 0
if ([textbox3.text isEqualToString: @"0"]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Error"
message:@"Your course lenth cannot be 0 Years. Please enter a different value"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
//If course length text field is empty
if ([textbox3.text isEqualToString: @""]){
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Error"
message:@"Please enter your current course length"
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
//time taken to pay off loan > 20 years
int newtimetaken = [timetakentopayoffloan.text intValue];
if (newtimetaken <= 20) {
writtenofflabel.text = @"WO";
}
}
-(IBAction)clearbutton:(id)sender {
[textbox1 setText:[NSString stringWithFormat:@""]];
[textbox2 setText:[NSString stringWithFormat:@""]];
[textbox3 setText:[NSString stringWithFormat:@""]];
[startingrepayments setText:[NSString stringWithFormat:@"Loan at start of repayments: "]];
[startingsalary setText:[NSString stringWithFormat:@""]];
[realtimetakentopayoffloan setText:[NSString stringWithFormat:@""]];
[debtamounttextfield setText:[NSString stringWithFormat:@""]];
[annualrepaymentstextfield setText:[NSString stringWithFormat:@""]];
[monthlyrepaymentstextfield setText:[NSString stringWithFormat:@""]];
[weeklyrepaymentstextfield setText:[NSString stringWithFormat:@""]];
[payoffloantextfield setText:[NSString stringWithFormat:@""]];
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Cleared"
message:@"All fields have now been cleared."
preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
myLabel.text = @"Use the scroller above...";
datePickerView.delegate = self;
//CareerPickerView.dataSource = self;
_pickerViewArray = @[@"Before September 2012",@"After September 2012"];
CareerViewArray = @[@"1000",@"2000"];
CareerPickerView.delegate = self;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if(pickerView == datePickerView)
{
NSString *dateSelected = [_pickerViewArray objectAtIndex:row];
myLabel.text = dateSelected;
}
else if(pickerView == CareerPickerView)
{
NSString *careerSelected = [CareerViewArray objectAtIndex:row];
startingsalary.text = careerSelected;
}
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if(pickerView == datePickerView)
{
return _pickerViewArray.count;
}
else if(pickerView == CareerPickerView)
{
return CareerViewArray.count;
}
return 1;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if(pickerView == datePickerView)
{
return _pickerViewArray[row];
}
else if(pickerView == CareerPickerView)
{
return CareerViewArray[row];
}
return nil;
}
@end
``` | 2016/02/29 | [
"https://Stackoverflow.com/questions/35699502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4320517/"
] | `<-` is to `>>=` (`bind`) where `let` is to `fmap` in a `do` block.
Stealing an example from [here](https://en.wikibooks.org/wiki/Haskell/do_notation):
```
do x1 <- action1 x0
x2 <- action2 x1
action3 x1 x2
-- is equivalent to:
action1 x0 >>= \ x1 -> action2 x1 >>= \ x2 -> action3 x1 x2
```
`action1`, `action2` & `action3` all return some sort of monad, say:
```
action1 :: (Monad m) => a -> m b
action2 :: (Monad m) => b -> m c
action3 :: (Monad m) => b -> c -> m d
```
You can rewrite let bindings as such:
```
-- assume action1 & action3 are the same
-- but action2 is thus:
action2 :: b -> c
do
x1 <- action1 x0
let x2 = action2 x1
action3 x1 x2
do
x1 <- action1 x0
x2 <- return & action2 x1
action3 x1 x2
-- of course it doesn't make sense to call action2
-- an action anymore, it's just a pure function.
``` | A good example to visualize what `<-` does:
```
do
a <- ['a'..'z']
b <- [1..3]
pure (a,b)
```
You can try this in the online REPL at [try.frege-lang.org](http://try.frege-lang.org/)
(You can enter this as a single line:
```
do { a <- ['a'..'z']; b <- [1..3]; pure (a,b) }
``` |
396,588 | For e.g
"All Muslims are terrorists, that muslim guy knifed that girl in London last month"
"All white men have privilege, just look at any senior level boardroom"
(not the same as the fallacy for associating a group with the actions of a few) | 2017/06/30 | [
"https://english.stackexchange.com/questions/396588",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/237939/"
] | It can be a ***faulty generalization***
Described by [Wikipedia](https://en.m.wikipedia.org/wiki/Faulty_generalization) as:
>
> A faulty generalization is a conclusion about all or many instances of a phenomenon that has been reached on the basis of just one or just a few instances of that phenomenon. It is an example of jumping to conclusions. For example, we may generalize about all people, or all members of a group, based on what we know about just one or just a few people. If we meet an angry person from a given country X, we may suspect that most people in country X are often angry. If we meet a lazy recipient of social welfare benefits, we may suspect that all welfare recipients are lazy.
>
>
> | This is an example of **selected instances**.
The difference between this and hasty/faulty generalization is as follows: a user of selected instances deliberately tries to deceive his audience by using selected examples of his point, while one who generalizes hastily has no opinion beforehand.
From the AGLOA Propaganda Technique Explanations (<http://agloa.org/prop-definitions>):
>
> Selected Instances: A person believes in a certain proposition. He then looks for examples that will support his belief. He selects only those examples or instances that back up his belief while ignoring examples that contradict his belief. He tries to persuade you by giving you only his selected examples.
>
>
> Hasty Generalization: A person jumps to a conclusion based on only a few examples. Unlike Selected Instances, the person has no preconceived belief. Instead, after seeing only a few examples, he draws a conclusion.
>
>
> |
27,972,715 | I have the most basic net/http program that I'm using to learn the namespace in Go:
```
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL)
go HandleIndex(w, r)
})
fmt.Println("Starting Server...")
log.Fatal(http.ListenAndServe(":5678", nil))
}
func HandleIndex(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("Hello, World!"))
}
```
When I run the program and connect to `localhost:5678` in Chrome, I get this in the console:
```
Starting Server...
/
2015/01/15 13:41:29 http: multiple response.WriteHeader calls
/favicon.ico
2015/01/15 13:41:29 http: multiple response.WriteHeader calls
```
But I don't see how that's possible. I print the URL, start up a new goroutine, write the header once, and give it a static body of `Hello, World!` It seems like one of two things is happening. Either something behind the scenes is writing another header or somehow `HandleIndex` is called twice for the same request. What can I do to stop writing multiple headers?
EDIT: It seems to have something to do with the `go HandleIndex(w, r)` line because if I remove `go` and just make it a function call instead of a goroutine, I don't get any issues and the browser gets it's data. With it being a goroutine, I get the multiple WriteHeader error and the browser doesn't show "Hello World." Why is making this a goroutine breaking it? | 2015/01/15 | [
"https://Stackoverflow.com/questions/27972715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160527/"
] | From the documentation:
```
// WriteHeader sends an HTTP response header with status code.
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).
```
What is happening in your case is that you are launching `go HandleIndex` from the handler.
The first handler finishes. The standard WriteHeader writes to the ResponseWriter. Then the go routine HandleIndex is launched and it also tries to write a header and write.
Just remove the `go` from HandleIndex and it will work. | Because modern browsers send an extra request for **/favicon.ico** which is also handled in your / request handler.
If you ping your server with curl for example, you'll see only one request being sent:
```
curl localhost:5678
```
To be sure you can add an EndPoint in your http.HandleFunc
```
http.HandleFunc("/Home", func(w http.ResponseWriter, r *http.Request)
``` |
2,740,630 | I find myself doing this a lot:
```
script/generate migration my_new_migration
```
.. then select & copy the generated filename, then paste it into vi to actually write the migration.
Is there any way to do this in one step? i.e. when the script/generate migration runs, it creates the file the automatically opens that file in an editor?
(I'm working in an SSH terminal window on linux..) | 2010/04/29 | [
"https://Stackoverflow.com/questions/2740630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292008/"
] | Well to start with, I'd find out what query is being generated (in LINQ to SQL you'd set the Log on the data context) and then profile it in SQL Server Management Studio. Play with it there until you've found something that is fast enough (either by changing the query or adding indexes) and if you've had to change the query, work out how to represent that in LINQ.
I suspect the problem is that you're combining `OrderBy` and `Take` - which means it potentially needs to find out *all* the results in order to work out which the top 100 would look like. Is `Code` indexed? If not, try indexing that - it *may* help by allowing the server to consider records in the order in which they'd be returned, so it can stop after it's found 100 records. You should look at indexes for the other columns too. | The `Take(100)` translates to "Select Top 100" etc. This would help if your problem was an otherwise huge result set, where there are a lot of columns returned. I bet though that your problem is a table scan resulting from the query. In this case, `.Take(100)` might not help much at all.
So, the likely culprit is the same as if you were doing SQL using ADO.NET: **How are your Indxes**? Are the fields being searched fields for which you don't have good indexes? This would cause a drastic decrease in performance compared to queries that *do* utilize good indexes. Add an index that includes `Code` and `Name` and see what happens. Not using an index for `Code` is guaranteed to hose you, because of the `Order By`. Also, what field links *Genealogy\_Accounts* and *Genealogy\_AccountClass*? A lack of index on either table could hose things. (I would guess an index including *Searchable* is unlikely to help.)
Use [SQL Profiler](http://msdn.microsoft.com/en-us/library/aa173918%28SQL.80%29.aspx) to see the actual query being run (though you can do this in VS too), and to see how bad it really is on the server.
The problem *might* be LINQ doing something stupid generating the query, but this is probably not the case. We're finding LINQ-to-SQL often makes better queries than we do. [Even if it looks goofy, it's usually very efficient](http://blog.stevensanderson.com/2007/12/13/outsmarted-by-linq-to-sql/). You can put the SQL in Query Analyzer, and check out the query plan. Then rewrite the SQL to be more human-simple and see if it improve things -- I bet it won't. I think you'll still see a **table scan**, indicating something is wrong with your index. |
58,205,999 | First stack overflow question here. Hope I do this correctly:
I need to use an external python library in AWS glue. "Openpyxl" is the name of the library.
I follow these directions: <https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-libraries.html>
However, after I have my zip file saved in the correct s3 location and point my glue job to that location, I'm not sure what to actually write in the script.
I tried your typical `Import openpyxl` , but that just returns the following error:
```
ImportError: No module named openpyxl
```
Obviously I don't know what to do here - also relatively new to programming so I'm not sure if this is a noob question or what. Thanks in advance! | 2019/10/02 | [
"https://Stackoverflow.com/questions/58205999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12155080/"
] | It depends if the job is Spark or Python Shell.
For Spark you just need to zip the library and then when you point the job to the library S3 path, the job will import it. You just need to make sure that the zip contains this file: `__init__.py`
For example, for the library you are trying to import, if you download it from <https://pypi.org/project/openpyxl/#files>, you can zip the folder **openpyxl** inside the **openpyxl-3.0.0.tar.gz**, and store it in S3.
---
On the other hand, if it is a Python Shell job, a zip file will not work. You will need to create an **egg** file from the library.
If you are using this version openpyxl-3.0.0, then you can download it from that same website, extract everything, and run the command `python setup.py bdist_egg` or **python3** instead of **python** if you use python3 instead.
This will generate an **egg** file inside `dist` folder which is also generated. You just need to put that egg file in S3 and point the Glue Job Python Libraries to that path.
If you already have the library and for some reason you don't have the `setup.py`, then you must create it in order to run the command to generate the egg file. Please refer to <http://www.blog.pythonlibrary.org/2012/07/12/python-101-easy_install-or-how-to-create-eggs/>. There you can find an example. | You may use following boilerplate code to use extra files as well as external libraries - <https://github.com/fatangare/aws-python-shell-deploy> |
10,092,468 | I'd like to generate a random date between two dates -- for example a random date between today and 60 days from now. How do I do that?
**UPDATE**
Using information from the answers, I came up with this method, which I use quite often:
```
// Generate a random date sometime between now and n days before day.
// Also, generate a random time to go with the day while we are at it.
- (NSDate *) generateRandomDateWithinDaysBeforeToday:(NSInteger)days
{
int r1 = arc4random_uniform(days);
int r2 = arc4random_uniform(23);
int r3 = arc4random_uniform(59);
NSDate *today = [NSDate new];
NSCalendar *gregorian =
[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [NSDateComponents new];
[offsetComponents setDay:(r1*-1)];
[offsetComponents setHour:r2];
[offsetComponents setMinute:r3];
NSDate *rndDate1 = [gregorian dateByAddingComponents:offsetComponents
toDate:today options:0];
return rndDate1;
}
``` | 2012/04/10 | [
"https://Stackoverflow.com/questions/10092468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257550/"
] | Use seconds. Pseudocode:
```
1 Generate a random integer between 0 and (60 * 60 * 24 * 60)
2 Get the unixtime in seconds for the current time
3 Add your random integer
4 Convert this integer back to a date
``` | **Swift 3.x +**
```
public extension Date {
/// SwiftRandom extension
public static func randomWithinDaysBeforeToday(days: Int) -> Date {
let today = Date()
let gregorian = Calendar(identifier: .gregorian)
let r1 = arc4random_uniform(UInt32(days))
let r2 = arc4random_uniform(UInt32(23))
let r3 = arc4random_uniform(UInt32(23))
let r4 = arc4random_uniform(UInt32(23))
let offsetComponents = NSDateComponents()
offsetComponents.day = Int(r1) * -1
offsetComponents.hour = Int(r2)
offsetComponents.minute = Int(r3)
offsetComponents.second = Int(r4)
let rndDate1 = gregorian.date(byAdding: offsetComponents as DateComponents, to: today)
return rndDate1!
}
/// SwiftRandom extension
public static func random() -> Date {
let randomTime = TimeInterval(arc4random_uniform(UInt32.max))
return Date(timeIntervalSince1970: randomTime)
}
}
```
P.S. [Esqarrouth](https://stackoverflow.com/users/2589276/esqarrouth)'s [answer](https://stackoverflow.com/a/33077138/1603234) corrected for latest Swift. |
80,642 | [](https://i.stack.imgur.com/KBdJz.jpg)
* Shutter speed - 32 sec.
* Aperture - f/9
* ISO - 100
* Lens - EF-S18-55mm f/3.5-5.6 IS II
* Focal Length - 39 mm
I have took the photo through the window, with the lights off | 2016/08/03 | [
"https://photo.stackexchange.com/questions/80642",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/54416/"
] | Although the poster hasn't specified it, this answer assumes this picture was shot on a tripod (it looks too sharp to be hand-held, even holding the camera steady against the window).
Many claimed that this is caused by a movement of the camera. However, I believe that it is actually due to the optical stabilization (IS in Canon parlance) trying to compensate for a movement that isn't there on a tripod. The fact that the movement is very irregular, slow, then turn, then fast (the fluorescent/led light showing irregular blinking patterns) indicates that something active is going on - the simple shake after pressing the shutter button cannot explain this.
I have seen very similar artifacts (although not as massive) once when I forgot to turn it off on my Tamron 70-200 f/2.8 (mounted on a Nikon D750).
[](https://i.stack.imgur.com/czTqo.jpg)
When shooting on a tripod, remember to turn off the optical stabilization (IS/VR/VC/OS or whatever it is called on your lens). | Those street light lines are due to the camera motion mostly at the time of shutter release (or shutter closing )
you may avoid them to some extent by having Camera Timer of say 3s or so |
4,801,189 | This is probably the weirdest problem I have run into. I have a piece of code to submit POST to a url. The code doesn't work neither throws any exceptions when fiddler isn't running, However, when fiddler is running, the code posts the data successfuly. I have access to the post page so I know if the data has been POSTED or not. This is probably very non-sense, But it's a situation I am running into and I am very confused.
```
byte[] postBytes = new ASCIIEncoding().GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://myURL);
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10";
req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
req.Headers.Add("Accept-Language", "en-US,en;q=0.8");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
req.CookieContainer = cc;
Stream s = req.GetRequestStream();
s.Write(postBytes, 0, postBytes.Length);
s.Close();
``` | 2011/01/26 | [
"https://Stackoverflow.com/questions/4801189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/552301/"
] | Always use using construct. it make sure all resource release after call
```
using (HttpWebResponse responseClaimLines = (HttpWebResponse)requestClaimLines.GetResponse())
{
using (StreamReader reader = new StreamReader(responseClaimLines.GetResponseStream()))
{
responseEnvelop = reader.ReadToEnd();
}
}
```
add following entries to webconfig file
```
<system.net>
<connectionManagement>
<add address="*" maxconnection="30"/>
``` | I found the solution in increasing the default number of connections
```
ServicePointManager.DefaultConnectionLimit = 10000;
``` |
19,760,590 | I have two java class with same properties names.How Can I copy all the properties to another bean filled with data.I don't want to use the traditional form to copy properties because I have a lot of properties.
Thanks in advance.
**1 class**
```
@ManagedBean
@SessionScoped
public class UserManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
private String userSessionId;
private String userId;
private String name;
private String adress;
......................
```
**2 class**
```
public class UserBean {
private String userSessionId;
private String userId;
private String name;
....................
``` | 2013/11/04 | [
"https://Stackoverflow.com/questions/19760590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2683519/"
] | Use [`BeanUtils`](http://commons.apache.org/proper/commons-beanutils):
```
import org.apache.commons.beanutils.BeanUtils;
UserBean newObject = new UserBean();
BeanUtils.copyProperties(newObject, oldObject);
``` | Check out the [Dozer Framework](http://dozer.sourceforge.net/) - its an object to object mapping framework. The idea is that:
* Usually it will map by convention.
* You can override this convention with a mapping file.
. . therefore mapping files are as compact as possible. Its useful for many cases, such as mapping a use-case specify service payload on to the reusable core model objects.
When delivering the SpringSource training courses we used to point out this framework very often.
*Edit:*
These days try [MapStruct](http://mapstruct.org/). |
36,038,616 | In WebStorm to get `karma.conf` running I need to configure it in a pop up window and enter the "path to the node.js interpreter".
*(for some reason this information vanished after a restart)*
**Questions:**
1. What is the path to the needed file?
2. Where is the node interpreter on Mac/Linux/Windows by default?
(I am on OS X) | 2016/03/16 | [
"https://Stackoverflow.com/questions/36038616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3313410/"
] | On OSX if you've installed Node.js with brew:
`/usr/local/bin/node`
You can check the exact folder on your machine with the command `which node`
**Important**
When the finder opens on OSX, you won't be able to navigate to this path initially. You'll first need to navigate to the root folder e.g. `Macintosh HD` and then perform the keyboard shortcut `Command + Shift + .` (. = dot = period) to be able to select hidden files and folders.
[](https://i.stack.imgur.com/xuAnO.png) | This can be useful for someone. I tried all the previous methods on Linux Ubuntu 19.10, none worked, neither reinstalling nodejs. So I installed Webstorm via snap, with:
```
sudo snap install webstorm
sudo snap install webstorm --classic
```
And surprise, Nodejs was already configured in this version. Then I erased the webstorm version that I installed from Ubuntu Softwared.
That worked for me and was easy. Hope that can give you a clue. |
8,854,200 | I have some CSV data like this:
```
1325318514,197.1,184.9,172.4,146.0,147.3,131.1,280.9,182.7,12.6,5.0,0.0,73001,65848,0
1325318536,196.2,184.2,172.1,146.3,147.1,131.1,264.9,175.6,12.6,5.0,0.0,71590,64616,0
1325318557,196.6,184.9,172.1,147.6,146.8,130.9,264.9,178.4,12.6,5.0,0.0,69607,61274,0
1325318578,196.7,184.2,172.1,148.4,146.8,130.6,255.9,174.0,12.5,5.0,0.0,74127,59221,0
....
```
i want to replace the first , with a space on each string but not the rest of the ,s
Any ideas on the regexp for that? Tried a few different things and just cant seem to get it to work... | 2012/01/13 | [
"https://Stackoverflow.com/questions/8854200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You don't have an element with the id *hidden* so `document.getElementById("hidden").value="hidden";` will throw an error as you can't set properties on `undefined`. The script will stop running and never reach `return false` so the form will submit as normal. | You can use
```
onclick="return test()"
```
and just return false at the end of the function. |
86,102 | Is there a way to programmatically (that is write a small c app or better yet a ruby or perl script) to obtain a list of all of the guests (and also details about the guests) from a VMWare Infrastructure?
Thanks,
Matt Delves | 2009/11/18 | [
"https://serverfault.com/questions/86102",
"https://serverfault.com",
"https://serverfault.com/users/24923/"
] | **How to reset your log files**
Sooner or later, you'll want to reset your log files (`access_log` and `error_log`) because they are too big, or full of old information you don't need.
`access_log` typically grows by 1Mb for each 10,000 requests.
Most people's first attempt at replacing the logfile is to just move the logfile or remove the logfile. This doesn't work.
Apache will continue writing to the logfile at the same offset as before the logfile moved. This results in a new logfile being created which is just as big as the old one, but it now contains thousands (or millions) of null characters.
The correct procedure is to move the logfile, then signal Apache to tell it to reopen the logfiles.
Apache is signaled using the **SIGHUP** (-1) signal. e.g.
```
mv access_log access_log.old
kill -1 `cat httpd.pid`
```
Note: `httpd.pid` is a file containing the process id of the Apache httpd daemon, Apache saves this in the same directory as the log files.
Many people use this method to replace (and backup) their logfiles on a nightly or weekly basis.
<http://httpd.apache.org/docs/1.3/misc/howto.html#logreset> | Try using `logrotate`
* it is a powerful tool which gives configurable options for rotating logs.
* it also has facility to run command during `prerotate` and `postrotate`
* `copytruncate` enables you to copy existing files and then truncate it. The copy can be moved to another storage such as hadoop, s3 for backup if desired
* Moreover a cron can be set such as `/usr/sbin/logrotate --force /etc/logrotate.hourly.conf 2>&1 >> /tmp/logger` by using `/etc/cron.hourly/logrotate`
For more info `man logrotate` |
58,143,434 | Given an HTML string:
```
myhtml = "<title> my title </title>"
```
How can I write a function that returns `true` if there is a floating/unescaped `<` or `>`, along with the offending character itself? Examples:
```
myhtml = "<title> my title </title>"
hasFloating(myhtml) => false
myhtml = "<title> < </title>"
hasFloating(myhtml) => true, <
myhtml = "<title> > </title>"
hasFloating(myhtml) => true, >
```
Keep in mind this string could be one huge piece of HTML code with multiple elements in it. I'm also okay with one function checking whether an unescaped char exists and a second returning the offender character itself
Edit: For the record, I am also using the `mechanize` gem in this project | 2019/09/28 | [
"https://Stackoverflow.com/questions/58143434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11552811/"
] | You need to keep track of the previously selected value and remove it when the option is changed.
```
var val = "";
var theval = $("#1471599855");
$("#todoslosmodelos select").change(function(){
val = $.each($(this).children("option:selected"), ()=> {
var before_change = $(this).data('pre');
let value = $(this).val()
if(value.length>0) {
if(before_change && before_change.length>0) {
theval.val(theval.val().replace(before_change + ", ", "") + value + ", ");
} else {
theval.val(theval.val() + value + ", ");
}
}
if(value.length==0){
theval.val(theval.val().replace(before_change + ", ", ""));
}
$(this).data('pre', $(this).val());
});
console.log(theval.val())
});
```
fiddle: <http://jsfiddle.net/0ybfsLoj/> | I believe, this markup and the values of the select will remain like as you have shown in your code snippet. Your existing script fetch all the existing data from $("#1471599855") and append newly selected fields without checking if the values from that dropdown is already taken or not.
If I were you what I will do is on every change of select I would picked selected value and put it in "fieldsetstalles" with extra attribute and then loop through on it get selected data from there and put it into the input field or simply, every change of select I will pick latest selected values and put into input field.
EDIT: Here I've saved fiddle anonymously, I'm not sure it show you updated code for you or not. <http://jsfiddle.net/3La6d4mj/>
I'm trying here with later solution that I've mentioned.
```
var val = "";
var theval = $("#1471599855");
$("#todoslosmodelos select").change(function(){
var data = '';
$(".fieldsetstalles select").each(function(){
if( '' != $(this).children("option:selected").val() ) {
data += $(this).children("option:selected").val() + ", ";
}
});
theval.val(data);
});
```
This should be what you need I guess. |
37,729,878 | I am using WooCommerce for a nonprofit website and want to change the "Place Order" button text to say "Place Donation". The button is defined in WooCommerce's payment.php file:
```
<?php echo apply_filters( 'woocommerce_order_button_html',
'<input type="submit" class="button alt" name="woocommerce_checkout_place_order"
id="place_order" value="' . esc_attr( $order_button_text ) .
'" data-value="' . esc_attr( $order_button_text ) . '" />' ); ?>
```
I added the following to my functions.php file in the child theme:
```
function custom_order_button_text($order_button_text){
$order_button_text = 'Place Donation';
return $order_button_text;
}
add_filter('woocommerce_order_button_text', 'custom_order_button_text');
```
It momentarily seems to work, but changes back to 'Place Order' before the page finishes loading. The output HTML ends up as:
```
<input type="submit" class="button alt" name="woocommerce_checkout_place_order"
id="place_order" value="Place order" data-value="Place Donation">
```
**\*Update:** I turned off javascript and found that the button then said "Place Donation." I then found a script in woocommerce/assets/js/frontend/checkout.js as part of payment\_method\_selected
```
if ( $( this ).data( 'order_button_text' ) ) {
$( '#place_order' ).val( $( this ).data( 'order_button_text' ) );
} else {
$( '#place_order' ).val( $( '#place_order' ).data( 'value' ) );
}
```
Not sure the best way to override this. Any ideas? | 2016/06/09 | [
"https://Stackoverflow.com/questions/37729878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5775880/"
] | Just came across the same issue myself. What I did to solve it is close to your solution.
Instead of dequeueing it completely I dequeued it and uploaded the excact same script to my child theme + commented out
```
`/* if ( $( this ).data( 'order_button_text' ) ) {
$( '#place_order' ).val( $( this ).data( 'order_button_text' ) );
} else {
$( '#place_order' ).val( $( '#place_order' ).data( 'value' ) );
}*/ `
```
The PHP:
```
`add_action('wp_enqueue_scripts', 'override_woo_frontend_scripts');
function override_woo_frontend_scripts() {
wp_deregister_script('wc-checkout');
wp_enqueue_script('wc-checkout', get_template_directory_uri() . '/../storefront-child-theme-master/woocommerce/checkout.js', array('jquery', 'woocommerce', 'wc-country-select', 'wc-address-i18n'), null, true);
} `
``` | I solved this by using CSS:
```
#place_order {
font-size: 0px !important;
}
#place_order::after {
content: 'Place Donation';
font-size: 15px;
}
``` |
31,444,652 | I am trying to load a solution in Visual Studio 2013 but I am receiving this message:

When I click OK it shows another error message:
>
> Attempted re-targeting of the project has been canceled. Required
> assemblies 'WindowsBase', 'PresentationCore', 'PresentationFramework'
> are missing from the target framework.
>
>
>
I have all .NET Framework installed (I am running Windows 10) and I already tried the .NET Framework Repair Tool (<https://support.microsoft.com/en-us/kb/2698555>). | 2015/07/16 | [
"https://Stackoverflow.com/questions/31444652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5121581/"
] | Open that project file in notepad and change .net version to < your project .net version > and try loading it in VS 2013 | When you get these message, you can do the following step by step:
1. open another project by +click on a yourprojectname.sln, so
you have two visual studios open. (One with a working project).
2. RightClick on your projectname in the solution explore and
choose "Unload project".
3. RightClick again on you project and choose then "Edit
yourprojectname.csproj". Do this also with the project where you get
the message in.
4. Compare these two files and change the items.
and all under the
- Save the file and close it.
- RightClick again on you project and choose "Reload project" |
5,631,730 | Can any one suggest how I could remove the cancel button next to login button in the Facebook graph API for iPhone. Where does the code lie? | 2011/04/12 | [
"https://Stackoverflow.com/questions/5631730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/688663/"
] | Use a [DispatcherTimer](http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer.aspx), there are also examples how to use it on the given link | Use a dispatch timer like this
>
> Delcare it
>
>
>
```
public System.Windows.Threading.DispatcherTimer timer1;
```
>
> In the constructor
>
>
>
```
timer1 = new System.Windows.Threading.DispatcherTimer();
timer1.Interval = TimeSpan.FromSeconds(180); // 3 mintues interval
timer1.Tick += TimerTicked; // Event for handling the fetching data
```
>
> Do your job
>
>
>
```
private void TimerTicked(object sender, EventArgs args)
{
//Fetch the data
}
```
timer1.start(); // Whereever you want to start the timer |
68,703,212 | I started tinkering with JavaScript (Node) recently, and I'm having a problem with a function that performs file writing. This function is always executed last, regardless of the calling order, and I can't fix it, could someone help me? (For example, in the code below, the categorySumPrice() function should run after the createAndWriteFixedJsonFile() function, but it runs before)
This is the program:
```
// ********************* CLASSES ****************
class Produto {
constructor(id, name, quantity, price, category) {
this.id = id
this.name = name
this.quantity = quantity
this.price = price
this.category = category
}
}
// ********************* Procedural *************
// ------ Global variables
// vector of objects produto
var produtos = []
// file name
const fileName = "broken-database.json"
//fixed file name
const fixedFileName = "./arquivo.json"
// file open require
const fs = require("fs")
//Read and Writing modes, like C
/*
r - Open file for reading
r+ - Open file for reading and writing
rs - Open file for reading synchronous mode
rs+ - Open file for reading and writing, synchronous mode
w - Open file for writing synchronous mode (if not exists file, created that)
wx - Open file for writing (if not exists file, dont created that)
w+ - Open file for writing and reading (if not exists file, created that)
wx+ - Open file for writing and reading (if not exists file, dont created that)
*/
// Fix JSON Part
// open broken database
var jsonFileName = openFile(fileName)
//read json file, fix, if necessary, and create objects produto
readFile(jsonFileName)
//save new JSON file fixed
createAndWriteFixedJsonFile(fixedFileName)
//sum price functions
categorySumPrice()
// ********************* FUNÇÕES *************
// Open File
function openFile(_file_name) {
try {
console.log('********************************')
console.log('* Arquivo aberto com sucesso *')
console.log('********************************')
return fs.readFileSync(_file_name, 'utf-8')
} catch (err) {
console.error(err)
}
}
// Fix JSON File and create objects produto
function readFile(_json_File) {
// Create produtos objects
try {
console.log('********************************')
console.log('* Os dados serão corrigidos, *')
console.log('* se necessário. *')
console.log('********************************')
const data = JSON.parse(_json_File)
for (var i in data) {
produtos[i] = new Produto(parseInt(data[i].id), fixString(data[i].name),
fixQuantity(data[i].quantity), fixPrice(data[i].price), data[i].category)
}
console.log('********************************')
console.log('* Dados obtidos com sucesso *')
console.log('********************************')
}
catch (err) {
console.log(`Erro: ${err}`)
}
}
// create and write fixed Json file
function createAndWriteFixedJsonFile(_fixedFileName) {
try {
fs.writeFile(_fixedFileName, JSON.stringify(produtos, null, 2), err => {
if (err) {
console.log(err)
}
else {
console.log('********************************')
console.log('* Arquivo criado com sucesso *')
console.log('********************************')
}
})
} catch (err) {
console.error(err)
}
}
function fixQuantity(quantityToFix) {
let quantity
if (isNaN(quantityToFix)) {
quantity = 0
}
else {
quantity = parseFloat(quantityToFix)
}
return quantity
}
function fixPrice(priceToFix) {
return parseFloat(priceToFix)
}
// Fix string function
function fixString(stringToFix) {
// Quatro tipos de erros conhecidos:
/*
"a" por "æ",
"c" por "¢",
"o" por "ø",
"b" por "ß".
*/
// o /g significará que todos os valores correspondentes serão substituídos.
// por padrão, replace substitui somente a primeira ocorrência
stringToFix = stringToFix.replace(new RegExp(/æ/g), "a");
stringToFix = stringToFix.replace(new RegExp(/¢/g), "c");
stringToFix = stringToFix.replace(new RegExp(/ø/g), "o");
stringToFix = stringToFix.replace(new RegExp(/ß/g), "b");
return stringToFix
}
function categorySumPrice() {
let estoquePorCategoria = []
let indice
let countCategories = 0
for (var i in produtos) {
if (i === 0) {
estoquePorCategoria[countCategories] = { categoria: produtos[i].category, valor: (produtos[i].quantity * produtos[i].price) }
countCategories++
}
else {
indice = estoquePorCategoria.indexOf(estoquePorCategoria.filter(function (obj) {
return obj.categoria == produtos[i].category;
})[0]);
if (indice != -1) {
estoquePorCategoria[indice].valor += (produtos[i].quantity * produtos[i].price)
}
else {
estoquePorCategoria[countCategories] = { categoria: produtos[i].category, valor: (produtos[i].quantity * produtos[i].price) }
countCategories++
}
}
}
console.log(estoquePorCategoria)
}
``` | 2021/08/08 | [
"https://Stackoverflow.com/questions/68703212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16619374/"
] | `writeFile` is an asynchronous function, which means that it will execute in parallel to other things. So:
1. You call `writeFile` then it starts writing.
2. The rest of your code continues executing while it's writing.
3. The `writeFile` finishes writing.
In order to have it execute synchronously with your other code you need to use `writeFileSync`.
You should use `writeFile` when the rest of your code isn't dependent on that file and `writeFileSync` if it is. | `fs.writeFile()` is executed asynchronously meaning that `categorySumPrice()` comes ahead of `createAndWriteFixedJsonFile()` because it takes time to save the file.
To avoid this you need to call `categorySumPrice()` from the callback function in `fs.writeFile()`:
```
// create and write fixed Json file
function createAndWriteFixedJsonFile(_fixedFileName) {
try {
fs.writeFile(_fixedFileName, JSON.stringify(produtos, null, 2), err => {
if (err) {
console.log(err)
}
else {
console.log('********************************')
console.log('* Arquivo criado com sucesso *')
console.log('********************************')
//And now is the time for executing the following:
categorySumPrice();
}
})
} catch (err) {
console.error(err)
}
}
``` |
92,619 | I have a potential customer who has an idea for an ipad application but is unable to find sufficient fundings for this.
One idea that came up is that I do the work either for free or for a minor fee and then receive a percentage of the income from appstore.
How do I decide what percentage is realistic?
How is this affected by the price in appstore and how do I protect myself from the scenario where the customer suddenly decides to offer the app for free? | 2011/07/13 | [
"https://softwareengineering.stackexchange.com/questions/92619",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/11921/"
] | Do it like a record contract. He gets 90% of the profit, but first you get to recoup the development costs. Simple. | How much is your time worth? If you are into charity and want to spend the time to learn and help out a friend, then go ahead and do it for a percentage. However, if you expect to get any return for your time ($$), then either get paid for your time via a real contract or implement it yourself and get the rewards.
Your time is not cheap or free my friend - only YOU can decide how to spend it. |
9,292,465 | I'm trying to make a game for kids. I've a movieClip called "picChange" and inside that movieClip, there is another movieClip called "picFrame" and inside that movieClip there are three movieClips called "HolderL1", "HolderL2", "HolderL3". I use these 3 movieClips to attach movieClips(questions for game) from library. I put movieClip inside movieClip to add some animation while it loads. I used following code:
```
for(var i:int = 0; i<3; i++) {
var pic_mc:String = "picLeft" + ranque[i];
var que_mc_class:Class = getDefinitionByName(pic_mc) as Class;
q = new que_mc_class();
picChange.picFrame.this["HolderL"+(i+1)].addChild(q);
}
```
In above code ranque is randomly generated numbers and q is a sprite. It's not working in the final code. But it works if I write it separately like `picChange.picFrame.HolderL1.addChild(q);` I'm not sure if this is the write way to do it. So if there's any easier way to do it please help me out and if anyone know how to use this["HolderL"+i] from mainTimeLine to attach a movieClip inside a movieClip. | 2012/02/15 | [
"https://Stackoverflow.com/questions/9292465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1170685/"
] | Well, to start with I'd suggest using `List<T>` instead of `ArrayList`. Then LINQ to Objects makes it really easy:
```
if (list.Any(x => x.HasFoo))
{
}
```
Or without LINQ (but still `List<T>`)
```
if (list.FindIndex(x => x.HasFoo) != -1)
{
}
```
If you *really* need to stick with a non-generic collection but have LINQ to Objects available too, you can use:
```
if (arrayList.Cast<YourType>().Any(x => x.HasFoo))
{
}
``` | use Linq:
```
var query = from o in yourarray select o where o.atribute==ValueIWant;
`query.Count()` will return the number of objects that fit the condition.
```
check that msdn example: [Linq example](http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b) |
60,328,437 | I am trying to plot a median time denoted `ee$rfs` per `ee$Ki67`, which is marker of many cells that proliferates in a tumor sample, ie. a continuous covariate too.
I have attached my data `ee` below. I am searching for a solution in either `dplyr` or `ggplot`. Obviously, I have sought for help, such as [here](https://stackoverflow.com/questions/60030885/how-to-apply-mutate-based-on-ntile-groups-in-dplyr), but without luck.
My current plot:
[](https://i.stack.imgur.com/aTIdr.png)
With the following
```
ggplot(ee, (aes(x=Ki67,y=rfs))) +
geom_point(aes(color=as.factor(WHO)),size=6,shape=20,alpha=0.5) +
facet_wrap(.~EOR)
```
I have tried variations of `mutate`, `group_by`, `filter` and `geom_line`. I tried `geom_smooth` but I am concerned that this draws the best fit (?) and not the median.
```
ee <- structure(list(rfs = c(26.4, 84, 42, 13.2, 18, 33.6, 39.6, 9.6,
16.8, 19.2, 10.8, 7.2, 10.8, 76.8, 58.8, 31.2, 18, 182.4, 20.4,
13.2, 8.4, 2.4, 123.6, 60, 100.8, 82.8, 12, 60, 18, 29.8, 68.3,
27.2, 18.7, 64.9, 6.5, 50.3, 46.4, 29.9, 31.4, 42.7, 31.1, 98.1,
80.9, 24.1, 49.2, 12.2, 20.5, 62.8, 9, 69, 30, 91.79, 8.57, 60.88,
11.5, 56.87, 49.05, 16.95, 4.5, 8.74, 60.06, 37.85, 90.12, 123.76,
47.41, 55.92, 3.09, 27.34, 4.99, 28.06, 26.71, 23.03, 6.34, 79.34,
2.5, 19.32, 9.23, 2.6, 4.34, 45.9, 29.34, 8.58, 29.41, 30.72,
15.97, 37.06, 17.05, 14.29, 5.95, 3.42, 60.58, 19.81, 72.91,
16.99, 7.29, 74.32, 3.35, 39.95, 4.4, 15.44, 2.5, 28.32, 40.15,
57.69, 27.86, 21.59, 10.09, 8.18, 21.59, 3.19, 3.12, 8.25, 14,
14, 2, 23, 15, 9, 9, 28, 14, 23, 21, 26, 24, 63, 25, 34, 26.83333333,
32.4, 28.76666667, 32.93333333, 32.16666667, 10.06666667, 46.66666667,
58.06666667, 29.06666667, 30.33333333, 26.56666667, 24.23333333,
36.5, 31.73333333, 5.733333333, 44.16666667, 46.93333333, 48.5,
64.7, 37.16666667, 21.56666667, 14.8, 53.83333333, 59.06666667,
8.7, 13.43333333, 12.56666667, 65.73333333, 54.83333333, 30.63333333,
5, 65, 7, 12, 14, 6, 15, 36, 99, 16, 87, 6, 33, 3, 3, 11, 24,
24, 15, 10, 28, 18, 14, 29, 20, 12, 42, 31, 14, 18, 29, 39, 62,
62, 46), Ki67 = c(25, 15, 8, 15, 18, 5, 2, 18, 6, 12, 12, 13,
13, 15, 20, 3, 30, 10, 18, 20, 7, 17, 5, 3, 20, 5, 20, 10, 2,
5, 4, 7, 8, 12, 40, 17, 3, 5, 20, 5, 22, 6, 6, 18, 15, 12, 15,
5, 15, 15, 3, 4, 10, 5, 2, 4, 3, 5, 7, 7, 4, 2, 4, 3, 20, 15,
25, 20, 10, 15, 15, 8, 15, 8, 8, 10, 22, 18, 50, 30, 30, 45,
50, 30, 8, 25, 25, 10, 25, 20, 15, 10, 8, 55, 10, 10, 10, 20,
30, 5, 20, 8, 30, 10, 15, 25, 30, 38, 15, 30, 25, 15, 5, 8, 35,
9, 14, 2, 1, 1, 20, 30, 2, 8, 2, 16, 20, 23, 4.5, 2.2, 9.43,
8.95, 6.47, 1.81, 7.27, 12.4, 7.97, 21.99, 8.98, 17.3, 8, 15,
15, 20, 6, 5, 12.5, 3, 20, 20, 11.5, 2.66, 14.7, 9.13, 5, 5,
12, 11, 2, 8, 20, 50, 10, 15, 30, 8, 10, 20, 10, 10, 30, 10,
10, 13, 10, 15, 10, 10, 40, 10, 5, 15, 15, 15, 25, 15, 30, 30,
8, 30, 15, 20, 13), EOR = c(1L, 0L, 0L, 1L, 0L, 1L, 0L, 1L, 1L,
1L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 0L,
0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L,
0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L,
0L, 0L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L,
0L, 1L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L,
0L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 0L, 0L,
0L, 0L, 1L, 0L, 1L, 1L, 0L, 0L, 0L, 1L, 0L, 1L, 1L, 1L, 0L, 0L,
0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L), WHO = c(2L, 2L, 2L, 3L, 3L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 2L, 2L, 3L, 2L, 3L, 3L, 3L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 3L, 1L, 2L,
1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L,
2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-193L))
``` | 2020/02/20 | [
"https://Stackoverflow.com/questions/60328437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8811399/"
] | Hadoop doesnt have an SCP upload feature.
If you want to get files in without an edge node or SSH, then that's what WebHDFS or the NFSGateway offer | Transfer using pipe
mkfifo - this creates pipe on local server (this doesn't store any data)
try
mkfifo <pipename - some path on your server where ssh keys are present> | scp : | hdfs dfs -put | rm |
72,992,593 | How can I format date-time in Angular with `DatePipe.format()` & skip all timezone conversion regardless where I am.
For example for such examples all over the world (regardless time) I want to get `07/06/2022`:
```
console.log('2022-07-06T00:00:00.000Z :', this.datePipe.transform('2022-07-06T00:00:00.000Z', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T06:00:00.000Z :', this.datePipe.transform('2022-07-06T06:00:00.000Z', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T13:00:00.000Z : ', this.datePipe.transform('2022-07-06T13:00:00.000Z', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T23:59:59.000Z :', this.datePipe.transform('2022-07-06T23:59:59.000Z', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T00:00:00-07:00 :', this.datePipe.transform('2022-07-06T00:00:00-07:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T06:00:00-07:00 :', this.datePipe.transform('2022-07-06T06:00:00-07:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T13:00:00-07:00 :', this.datePipe.transform('2022-07-06T13:00:00-07:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T23:59:59-07:00 :', this.datePipe.transform('2022-07-06T23:59:59-07:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T00:00:00-12:00 :', this.datePipe.transform('2022-07-06T00:00:00-12:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T06:00:00-12:00 :', this.datePipe.transform('2022-07-06T06:00:00-12:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T13:00:00-12:00 :', this.datePipe.transform('2022-07-06T13:00:00-12:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T23:59:59-12:00 :', this.datePipe.transform('2022-07-06T23:59:59-12:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T00:00:00+12:00 :', this.datePipe.transform('2022-07-06T00:00:00+12:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T06:00:00+12:00 :', this.datePipe.transform('2022-07-06T06:00:00+12:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T13:00:00+12:00 :', this.datePipe.transform('2022-07-06T13:00:00+12:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T23:59:59+12:00 :', this.datePipe.transform('2022-07-06T23:59:59+12:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T00:00:00+07:00 :', this.datePipe.transform('2022-07-06T00:00:00+07:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T06:00:00+07:00 :', this.datePipe.transform('2022-07-06T06:00:00+07:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T13:00:00+07:00 :', this.datePipe.transform('2022-07-06T13:00:00+07:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T23:59:59+07:00 :', this.datePipe.transform('2022-07-06T23:59:59+07:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T00:00:00+00:00 :', this.datePipe.transform('2022-07-06T00:00:00+00:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T06:00:00+00:00 :', this.datePipe.transform('2022-07-06T06:00:00+00:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T13:00:00+00:00 :', this.datePipe.transform('2022-07-06T13:00:00+00:00', 'MM/dd/yyyy', '+0000'), '\n\n');
console.log('2022-07-06T23:59:59+00:00 :', this.datePipe.transform('2022-07-06T23:59:59+00:00', 'MM/dd/yyyy', '+0000'), '\n\n');
```
all this examples should return `07/06/2022`.
I tried different approaches - but still can see issues.
The only way I found is a very dirty solution:
```
if (date?.match(/^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$/)) {
return date.substring(5, 7) + '/' + value.substring(8, 10) + '/' + value.substring(0, 4);
}
```
Basically take string and parse values from it. I don't think it's a pretty way.
Also I'm using `dayjs` and tried: `dayjs(date).tz('Greenwich').format('MM/DD/YYYY');`
How can I get the same date everywhere? | 2022/07/15 | [
"https://Stackoverflow.com/questions/72992593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1645431/"
] | Haha, I tried many ways but it doesn't work, maybe just cut the string to cheat
```
const dateArr = [
'2022-07-06T00:00:00+00:00',
'2022-07-06T00:00:00.000Z',
'2022-07-06T06:00:00.000Z',
'2022-07-06T13:00:00.000Z',
'2022-07-06T23:59:59.000Z',
'2022-07-06T00:00:00-07:00',
'2022-07-06T06:00:00-07:00',
'2022-07-06T13:00:00-07:00',
'2022-07-06T23:59:59-07:00',
'2022-07-06T00:00:00-12:00',
'2022-07-06T06:00:00-12:00',
'2022-07-06T13:00:00-12:00',
'2022-07-06T23:59:59-12:00',
'2022-07-06T00:00:00+12:00',
'2022-07-06T06:00:00+12:00',
'2022-07-06T13:00:00+12:00',
'2022-07-06T23:59:59+12:00',
'2022-07-06T00:00:00+07:00',
'2022-07-06T06:00:00+07:00',
'2022-07-06T13:00:00+07:00',
'2022-07-06T23:59:59+07:00',
'2022-07-06T00:00:00+00:00',
'2022-07-06T06:00:00+00:00',
'2022-07-06T13:00:00+00:00',
'2022-07-06T23:59:59+00:00'
];
dateArr.forEach(date => {
const result = this.datePipe.transform(new Date(date.slice(0,10)),'MM/dd/yyyy');
console.log(result);
})
```
[](https://i.stack.imgur.com/kUUDD.png) | Here is what i think:
In the component ts :
declare a variable call d='2022-07-06T00:00:00+00:00'(for example)
And in the HTML of the component :
```
<div>{{d| date:'dd/MM/YYYY'}}</div>
```
Now you should get 07/06/2022 no matter what timezone is. |
1,370,277 | I am a student of Pure Mathematics and also interested in programming .I have learnt C++,SAGE .
Recently I have started learning "Cryptography" .But there are many definitions involved here like polynomial time algorithm,time complexity etc.
My question is it all right for a student in Pure Mathematics to study Cryptography or as time progresses I will eventually fall out of place and lose interest in this subject.
Is Cryptography more suitable for computer science graduates or it does not matter which background a student is from to study this?
Please share your thoughts here as i am still in my early days and may help to change the subject if necessary before it is too late | 2015/07/22 | [
"https://math.stackexchange.com/questions/1370277",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/294365/"
] | As a computer science student who took a graduate course (albeit an introductory one) in cryptography last semester, I found myself pulling from my knowledge of number theory *immensely* more than I did from my knowledge of computer science. The field today is a highly mathematical one, with current state-of-the-art systems reliant on number theoretical subjects like discrete logarithms, prime factorization, and elliptic curves. Emerging techniques center around even more mathematical subjects, such as the hardness of lattice basis reduction. In fact, I think that pure math students will on average have an *easier* time learning cryptography than computer science students.
Even though you are not currently familiar with the meaning of terms like "polynomial time algorithm," you should be able to grasp time complexity very quickly as a student of pure mathematics. You will need to become familiar with algorithm design, but that will come naturally as you study.
In short, go for it! Almost everyone will come in lacking some sort of background knowledge *regardless* of what they studied, but if you are motivated then you should be able to pick up the slack without much trouble. | Much of cryptography today works on grounds of abstract algebra (and number theory). Clearly to show that some encryption technique has a corresponding decryption one requires proof, that is math. But that is just a small part of cryptography. The recent most talked about problems with cryptographic systems have been programming errors, disregard of the theory and existing practical experiences, blatant misuse of the theory or of the programs, and other "human", not "technical" or "theoretical" problems.
I'd suggest you take a peek at the classic ["Security Engineering"](http://www.cl.cam.ac.uk/~rja14/book.html) by Anderson (the link is to the free full set of PDFs for the chapters, I liked it so much I bought it on paper...), it shows a much wider scenery (one I find much more relevant in actual practice). |
54,019,699 | I need to show alert if my parent div has a child div using JavaScript only No jQuery.
I have tried using the `contains()` function to check my div and send alert but it's not working.
```html
<script type="text/javascript">
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
} else
{
alert("no");
}
</script>
<div class="row leftpad collapse" id="commentBox">
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
```
There should be an alert box with message `yes` in it but it's not visible. I have also tried checking JavaScript using the `alert()` method only without any code. | 2019/01/03 | [
"https://Stackoverflow.com/questions/54019699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1933996/"
] | Make sure that the whole DOM is loaded before you execute javascript code.
You can do this by adding the event listener `DOMContentLoaded` to your code or placing your scripts at the end of the file
```html
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(){
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv && parentDiv.contains(childDiv)) {
alert("yes");
}
else {
alert("no");
}
}, false);
</script>
<div class="row leftpad collapse" id="commentBox" >
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
```
You won't get an alert because `parentDiv` will not exist yet and the value will be `null`. This results that it does not contain the `contains()` function and it will throw an error. To be safe you can add a null check inside the if statement. | How about using `window.onload` function?
```
<script>
window.onload = function() {
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
} else {
alert("no");
}
}
</script>
```
**[This will execute the function until dom loads completely](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload)**
```
<script>
window.onload = function() {
var parentDiv = document.getElementById("commentBox");
var childDiv = document.getElementById("comment1");
if (parentDiv.contains(childDiv)) {
alert("yes");
} else {
alert("no");
}
}
</script>
<div class="row leftpad collapse" id="commentBox">
<div id="comment1">
<div class="col-md-3 dir-rat-left"> <i class="fa fa-user-circle" aria-hidden="true"></i>
<h6>James </h6>
</div>
<div class="col-md-9 dir-rat-right">
<p class="removemarg">always available, always helpfull that goes the same for his team that work with him - definatley our first phone call.</p>
</div>
</div>
</div>
``` |
1,073,423 | When writing a new jQuery plugin is there a straightforward way of checking that the current version of jQuery is above a certain number? Displaying a warning or logging an error otherwise.
It would be nice to do something like:
```
jQuery.version >= 1.2.6
```
in some form or another. | 2009/07/02 | [
"https://Stackoverflow.com/questions/1073423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132177/"
] | ```
$().jquery;
```
or
```
jQuery.fn.jquery;
``` | Instead of using `parseInt` as i saw in one of the answers above i would suggest to use `parseFloat` as mentioned below
```
var _jQueryVer = parseFloat('.'+$().jquery.replace(/\./g, ''));
/* Here the value of _jQueryVer would be 0.1012 if the jQuery version is 1.0.12
which in case of parseInt would be 1012 which is higher than
140 (if jQuery version is 1.4.0)
*/
if(_jQueryVer < 0.130) {
alert('Please upgrade jQuery to version 1.3.0 or higher');
}
``` |
48,513,607 | I've seen examples of DynamoDB as the data source for AWS AppSync but I'm wondering if Aurora (specifically PostgreSQL) can be used? If yes, what would the resolvers look like for a basic example? Are there any resources that demonstrate doing this for Aurora PostgreSQL or even MySQL? | 2018/01/30 | [
"https://Stackoverflow.com/questions/48513607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1843640/"
] | You can use the AWS Lambda resolver available in AWS AppSync to access Aurora Postgres. The code is similar to how you would access a relational database using any language. For example, you could use [node-postgres](https://node-postgres.com/) with NodeJS to implement the Lambda function. | As of time of writing, yes but only if it is a **Serverless** Aurora RDS cluster set to Postgres compatibility. The reason for this is it's the only RDS instance type that supports the [Data API](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html). Other RDS instances would have to be configured as a different data source type, most commonly Lambda. |
25,338 | I read on Wikipedia that zero-knowledge proofs are not used for authentication in practice. Instead (I think) the server is entrusted with seeing a password in plaintext form, which it should then add a salt to and hash. But for a split moment, the server knows the secret. Why should I implicitly trust the server like this? It could go rogue and record my password in plaintext form. I could use that same password for other sensitive things. Aren't zero-knowledge proofs a necessity? Why aren't they used? Or are they used?
Update, an alternative: What about never reusing your password and instead generating different passwords from a master password and website name using only a program that runs on the client? It seems much simpler, because you never reveal the master password. That way, you don't need to trust the website nearly as much.
This clarifies my previous question. | 2015/04/30 | [
"https://crypto.stackexchange.com/questions/25338",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/23901/"
] | Having a client (ex. your web browser) use zero-knowledge proofs to authenticate itself to a server only makes sense if the server knows about the client's public key in advance, and if the client keeps the same private key forever. So you could have the client-side generate a keypair when you register your account, and the server records your public key along with your login info. Then you could use a zero-knowledge proof to log in. Great. I think SSH supports this kind of authentication. There are some second-factor authentication methods that work this way too, but in practice it's more trouble than it's worth; what if:
1. The user clears their browser cache?
2. The user tries to log in from a different computer?
3. Some other bad thing happens to their private key.
In all these cases the user will be unable to log in, and will have to recover their account. It'll be super annoying.
You could, I suppose, have the user type their password, and on client-side use that password to re-generate the private key. That way it's still password-based, you can't lose the private key, and you get to use zero-knowledge proofs for the actual data exchange. The counter-argument that comes to mind is that using the password as a seed does not add any strength to the password, since an attacker still only has to guess the password, but you have to perform a full RSA key gen each time you want to log into something, which can take minutes on a mobile device. Most people would find that infuriating.
In relation to your point about letting the server see your password in plaintext: Yes. This is true. I don't know what to tell you. This is why hard-core security experts will tell you to use a different password for every website, and use a password manager to keep track of them all. | >
> But for a split moment, the server knows the secret
>
>
>
... and so is the wireless bug in the cable of the keyboard, the web-cam of your laptop and iPhone, the microwave microphone of the satellite eavesdropping the sound of your keystrokes, etc. If you are afraid of the server don't go in Internet (it is not the server, BTW -it is the screen memory capturing your passwords that is not getting out of the memory ... but remains traces that can be traced and captured) you may use a smart-card for hashing and salting your password before supplying it to the server.
>
> I could use that same password for other sensitive things. Aren't zero-knowledge proofs a necessity?
>
>
>
When you start using a one-time pad as multi-time breakout in the cryptography the zero-knowledge proof is your least problem. Any start up hacker on the communication line can break your *'same password'* just for breakfast. |
129,713 | Recently, I heard one of my colleague said "the 16-bits ADC is enough for us, we can use 'oversampling' tech...". Finally I figured out his "oversampling tech" means to sample many many cycles (AC sampling). But I wonder if we don't improve the sample rate, what is the benefit from sampling many cycles? Can it increase the resolution of the ADC? So my question is:
1. I think "oversampling" means to improve the sample rate. Right?
2. What is the benefit from multiple cycle sampling?
---
My colleague's "oversampling" is as below:
If we want to measure 50 Hz AC signal, we set ADC's sample rate to 1000 Hz, and sample 10 cycles, that is (1000 Hz / 50 Hz) x 10 = 200 samples. If the result is not good, increase the cycles to 100, etc. Yes, he only increases the samples, but not the sample rate! | 2014/09/18 | [
"https://electronics.stackexchange.com/questions/129713",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/25264/"
] | Oversampling means to sample at significantly more than the Nyquist Rate.
When using an ADC, the ADC generates quantisation noise because the continuous valued signal has to be translated to discrete output values. If you oversample then this noise power is "spread out" over a larger frequency range, i.e. it has a lower spectral density. So if you apply a digital low-pass filter after the ADC you can reduce the total noise. The reduction would be -3dB if you halved the bandwidth of the signal, which is equivalent to 1/2 bit improvement in your ADC. So oversampling by 16x and filtering with a perfect brick wall LPF would give you an improvement of 4\*1/2 bit = 2bits.
Intuitively so you can see this works: say the ADC output is oversampled by 4 so for a specific sample you get 3,4,3,3 ; the average of this is 3.25 so you have improved the effective number of bits (ENoB) of your ADC reading.
Delta-Sigma ADCs shape the quantisation noise, pushing more of it out to higher frequencies so they can get 2 or even 3 bits per octave of oversampling. This diagram (from EETimes) illustrates the point:

On your point (2) you refer to "multiple cycle sampling" as "means to sample many many cycles (AC sampling)".
Your description is a little confusing, but you can use techniques that rely on sampling a repetitive signal over multiple cycles to "fill in" samples that fall in between the sample rate. Digital Sampling Oscilloscopes use this technique. Basically you sample your signal starting from time 0 and then sample again from time T/N (either on stored data or the next input signal cycle), where T is the sample period and N is the oversample rate. You then "fill in" the new data.
EDIT: Based on OP clarification:
"If we want to measure 50 Hz AC signal, we set ADC's sample rate to 1000 Hz, and sample 10 cycles, that is (1000 Hz / 50 Hz) x 10 = 200 samples. "
By sampling the same points from a periodic perspective you will get some noise reduction once you average the values as described in my answer, but the noise reduction will not match the theoretical reduction because the quantisation noise will be correlated to the sampling. Also, you're missing a trick if you do not recognise the point I made in (2). By choosing the sample frequency to be relatively prime with respect to the signal frequency you would not be sampling the "same points" each period. This gives you more data. If you then choose to average this you get less noise because the quantisation noise will be de-correlated. | The minimum sampling rate needed is twice the highest frequency of the spectrum of the signal you wish to measure. If the highest frequency in the spectrum of the signal is 10kHz then you need to sample at least twice as high (20,000 times per second) in order to avoid aliasing.
Most folk go a bit better than this and, for instance, CD's sample audio at 44.1k samples per second and expect to be able to reproduce an audio spectrum that goes from DC to 20kHz. that's 2.205 times higher than 20kHz. Here's an example picture: -

It shows a benefit for oversampling in that the filtering used to recover an audio signal after a DAC is more easily designed and uses fewer components (take my word for it). I'm involved a lot with sampling analogue signals and we place a minimum sampling rate at 2.5 times to make reconstruction of the signal after leaving the DAC a relatively easy process.
Under-sampling is to be avoided unless you are designing (eg) software radios which rely on under-sampling as a means for demodulation. This is what happens: -

The red signal is the original and it is under-sampled at the blue-dot points - when this is reconstructed by a low pass filter the blue signal is generated and clearly this does not look like the original signal! If you sampled a sine wave exactly at twice its frequency then you'll get a dc level somewhere between -pk and +pk.
Strictly speaking, both CDs and the systems I work on "over-sample" and of course everyone else does to a lesser or greater extent.
So, the benefit of over-sampling is: -
* improved signal-to-noise ratio,
* ability to recover signals that are less than one quantization step in amplitude (called dithering and also used in digital audio on CDs),
* simpler reconstruction filters (analogue and digital domain),
* DAC [sinc-compensation filter](http://www.maximintegrated.com/en/app-notes/index.mvp/id/3853) less likely to be needed.
I'm not going to go too deep into this as you are probably a beginner in this subject but please ask if you need more info.
EDIT - following the amendment by the OP: -
>
> If we want to measure 50 Hz AC signal, we set ADC's sample rate to
> 1000 Hz, and sample 10 cycles, that is (1000 Hz / 50 Hz) x 10 = 200
> samples. If the result is not good, increase the cycles to 100, etc.
> Yes, he only increases the samples, but not the sample rate!
>
>
>
Sampling more cycles of a 50Hz waveform may or may not give you what you want. For instance, the RMS value from one cycle can be calculated as X but the next cycle it could be fractions higher or lower. Another problem is that sampling several cycles (or even 1 cycle) may result in only a partial coverage of exact cycles and this will give another error. How you would know that the result is not good is another thing and this I rely on the OP in explaining.
One thing can be said though, if the signal is stable (frequency and voltage and shape) over several cycles, then sampling more cycles improves accuracy. |
67,736,409 | I am trying to remove the brackets from the list I have created but I am not sure how to go about doing this. I thought of doing replace() but this is a list object and so this would not work. How can I remove these tuple brackets and also the numbers? I have tried using isDigit() for number removal from the list but this does not seem to work. I get an error saying "tuple' object has no attribute 'isdigit"
```
movies = {'Spider-Man': 98, 'King Kong': 100}
displayMoviesForSort = list(movies.items())
displayMovies = sorted(displayMoviesForSort, key=lambda tup: (-tup[1],tup[0]))
print(displayMovies)
```
Output:
```
[('King Kong', 100), ('Spider-Man', 98)]
```
Desired output:
```
['King Kong', 100, 'Spider-Man', 98] #Removed brackets
['King Kong', 'Spider-Man'] #Removed numbers
``` | 2021/05/28 | [
"https://Stackoverflow.com/questions/67736409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14723580/"
] | You can use `extend` to add all items from a `tuple` to a list:
```
displayMovies = [('King Kong', 100), ('Spider-Man', 98)]
noTuples = []
for item in displayMovies:
noTuples.extend(item)
```
Output:
```
>>>noTuples
>>>['King Kong', 100, 'Spider-Man', 98]
```
Then you can use list comprehensions to remove numbers:
```
noNumbers = [item for item in noTuples if not isinstance(item, int)]
```
Output:
```
>>>noNumbers
>>>['King Kong', 'Spider-Man']
``` | You can try `dict.keys`:
```
displayMoviesForSort = list(movies.keys())
>>>
['Spider-Man', 'King Kong']
```
Or:
```
#Removed brackets
flatList = [item for sublist in displayMoviesForSort for item in sublist]
flatList
>>>
['Spider-Man', 98, 'King Kong', 100]
#Removed numbers
flatList = flatList[::2]
flatList
>>>
['Spider-Man', 'King Kong']
``` |
54,019,850 | I have 2 php variables in PHP (mainly $usm and $ag) and am passing them to the frontend. In Javascript am using isset to check if they have a value before executing some code but seems not to work
```
<script>
if( <?php isset($usm , $ag) ?> ){
$( document ).ready(function() {
var usmData = {!! json_encode($usm) !!};
var agData = {!! json_encode($ag) !!};
});
}
</script
``` | 2019/01/03 | [
"https://Stackoverflow.com/questions/54019850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6013697/"
] | You need to check the isset part with PHP only.
```
<?php if(isset($usm) and isset($ag)){ ?>
<script>
$( document ).ready(function() {
var usmData = '<?php echo json_encode($usm); ?>';
var agData = '<?php echo json_encode($ag); ?>';
});
</script>
<?php } ?>
``` | ```
<script>
<?php if(isset($usm , $ag)) { ?>
$( document ).ready(function() {
var usmData = {!! json_encode($usm) !!};
var agData = {!! json_encode($ag) !!};
});
<?php } ?>
</script>
``` |
62,561,010 | I am trying to append a new child when user clicks on a button. The new child is already defined with few CSS properties. Is it possible to do so ? I have tried a few codes, the best i could do is -
```js
var body = document.querySelector('body');
var bubbles = document.createElement("span")
function a1click(){
var size = Math.random() * 100;
bubbles.style.width = 100 + size+'px';
bubbles.style.height = 100 + size+'px';
body.appendChild(bubbles);
}
```
```css
*{
margin: 0;
padding: 0;
}
#a1{
position: relative;
top: 250px;
left: 100px;
width: 30px;
height: 150px;
border: 2px solid #fff;
background: rgb(0, 0, 0);
float: left;
cursor: pointer;
perspective: 600;
}
span{
position: absolute;
top: 120px;
left: 60%;
width: 50px;
height: 50px;
background: black;
animation: tweek 1s linear;
transform-origin: top;
pointer-events: none;
}
@keyframes tweek {
0% {
transform: rotate(90deg) translate(300px);
}
100% {
transform: rotate(0deg) translate(250px);
opacity: 0;
}
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body onkeydown="keypress(event)">
<div id="a1" onclick="a1click()"></div>
<script src="script.js"></script>
</body>
</html>
```
This was good uptil here but the problem is that when we click button the box is getting appended continously, i want it to append only once if the button is clicked once if twice then again and so on.. Please help me..Any help will be appreciated. | 2020/06/24 | [
"https://Stackoverflow.com/questions/62561010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13779469/"
] | Use the `...` syntax with `.push()`
```
growthArr.push(...parentArr)
```
---
This works because `.push()` takes any number of arguments, and pushes them all into the targeted array.
***Note:*** This mutates the original array without creating a new one and overwriting it. This can be important if there are other references to the array that need to observe the mutation.
---
FYI, your attempt would have worked:
```
growthArr.push.apply(parentArr)
```
Except that `.apply` expects the first argument to be the `this` value (the targeted array). So you'd need this:
```
growthArr.push.apply(growthArr, parentArr)
``` | Use array concat() method. So the syntax would be
```
parentArr.concat(growthArr);
``` |
27,953,969 | I'm a beginner in Python and I can't find an answer to my problem. I have a file with some data and I want to get numbers from this file. My program looks like this:
```
class Mojaklasa:
def przenumeruj_pdb(self):
nazwa=raw_input('Podaj nazwe pliku: ')
plik=open(nazwa).readlines()
write=open('out.txt','w')
for i in plik:
j=i.split()
if len(j)>5:
if j[0] == "ATOM":
write.write(j[5])
write.write("\n")
zapis.close()
```
The 5th field in file has some numbers from -19 to 100, and it's working perfectly. But sometimes the 5th field has numbers with a letter, f.e. 28A and only want 28. Converting to int doesn't work. How can I do this? | 2015/01/14 | [
"https://Stackoverflow.com/questions/27953969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3541098/"
] | You can replace a lot of logic with a properly formatted regular expression.
```
for i in plik:
m = re.match(r'ATOM\s+.*?\s+.*?\s+.*?\s+.*?\s+(-?\d+)', i)
if m:
write.write(m.group(1) + '\n')
``` | Here's an overall-improved approach:
```
import re
class Mojaklasa:
def przenumeruj_pdb(self):
nazwa=raw_input('Podaj nazwe pliku: ')
with open(nazwa) as plik, open('out.txt','w') as zapis:
for i in plik:
j = i.split()
if len(j) <= 5: continue
if j[0] == "ATOM":
mo = re.match(r'\d+', j[5])
if mo is None: continue
zapis.write(mo.group() + '\n')
```
I have not improved your choice of identifiers (except for some confusion between `write` and `zapis`), but improvements include (a) useful indenting, (b) use of `with` to open files (so they're automatically closed), (c) extraction of leading digits only via `re` (the one most germane to your Q), (d) use of `if/continue` lines rather than indenting (as "flat is better than nested"). Plus perhaps some I may be forgetting:-)
I **would** also recommend renaming `j` to `line` and `i` to `fields` (or whatever the equivalents in your chosen language) as `i` and `j` "sound" a lot like integer loop counters or the like, which is very confusing:-). |
71,595,911 | Not sure what the right terms were to start this question but basically I have a downloaded UI tool that runs on 0.0.0.0:5000 on my AWS EC2 instance and my ec2 instance has a public ip address associated with it. So right now everyone in the world can access this tool by going to {ec2\_public\_ip}:5000.
I want to run some kinda script or add security group inbound rules that will require authorization prior to letting someone view the page. The application running on port 5000 is a downloaded tool not my own code so it wouldnt be possible to add authentication to the tool itself (Its KafkaMagic FYI).
The one security measure I was able to do so far was only allow specific IPs TCP connection to port 5000, which is a good start but not enough as there is no guarantee someone on that IP is authorized to view the tool. Is it possible to require an IAM role to access the IP? I do have a separate api with a login endpoint that could be useful if it was possible to run a script before forwarding the request, is that a possible/viable solution? Not sure what best practice is in this case, there might be a third option I have not considered.
**ADD-ON EDIT**
Additionally, I am using EC2 Instance Connect and if it is possible to require an active ssh connection before accessing the ec2 instances ip that would be a good solution as well.
**EDIT FOLLOWING INITIAL DISCUSSION**
Another approach that would work for me is if I had a small app running on a different port that could leverage our existing UI to log a user in. If a user authenticated through this app, would it be possible to display the ui from port 5000 to them then? In this case KafkaMagic would be on a private ip and there would be a different IP that the user would go through before seeing the tool | 2022/03/24 | [
"https://Stackoverflow.com/questions/71595911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9676301/"
] | In short, the answer is *no*. If you want authorization (I think, you mean, authentication) to access an application running on the server - you need tools that run *on the server*. If your tool offers such capability - use it. It looks like Kafka Magic *has* such capability: <https://www.kafkamagic.com/faq/#how-to-authenticate-kafka-client-by-consumer-group-id>
But you can't use external tools, like AWS, that perform such authentication. Security group is like a firewall - it either allows or blocks access to the port. | You can easily create a script that uses the aws sdk or even just executes the aws CLI to view/add/remove an ip address of a security group. How you execute that script depends on your audience and what language you use.
For a small number of trusted users you could issue them an IAM user and API key with a policy that allows them to manage a single dynamic security group. Then provide a script they can run/shortcut to click that gets the current gateway ip and adds/removes it from the security group.
If you want to allow users via website a simple script behind some existing authentication is also possible with sdk/cli approach(depending on available server side scripting).
If users have SSH access - you could authorise the ip by calling the script/cli from bashrc or some other startup script.
In any case the IAM policy that grants permissions to modify the SG should be as restrictive as possible (basically dont use any `*`'s in the policy). You can add additional conditions like the source IP/range (ie in your VPC) or that MFA must be active for user etc to make this more secure (can be handled in either case via script). If your running on ec2 id suggest looking at IAM Instance Roles as an easy way to give your server access to credentials for your script (but you can create a user and deploy the key/secret to the server and manage it manually if you wanted).
I would also suggest creating a dedicated security group for dynamically managed access alongside existing SGs required for internal operation for safety. It would be a good idea to implement a lambda function on a schedule to flush the dynamic SG (even if you script de-authorising an IP it might not happen so its good to clean up safely/automatically). |
8,181,894 | I have some doubts in JAVA.
I have a task executor which will create a new Thread for each task and each thread will execute a task from jar by
```
Runtime.getRuntime().exec(" java -jar myjar");
```
I read in some posts that by executing like this each thread will create its own JVM. Then if I want to execute the same class or a different class from the same jar using two threads it will create a copy of same jar in two JVMs. Actually I want to avoid copying same jar in two JVMs. Instead of that I want to share same jar between multiple JVMs.
Please give some hints about this situation. | 2011/11/18 | [
"https://Stackoverflow.com/questions/8181894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053496/"
] | It looks like the array that comes with gcc 4.6 doesn't have a debug mode yet. Understandable since C++11 support is still experimental.
There is a flag `_GLIBCXX_DEBUG` which is usually used to turn on debug mode. If you look at /usr/include/c++/4.6/debug/vector:313 you'll see `operator[]` has:
```
__glibcxx_check_subscript(__n);
```
Now, this may be uber-evil (and I mean *really* evil) but it looks like we can conditionally add this to array. Change lines 148-154 of /usr/include/c++/4.6/array from:
```
reference
operator[](size_type __n)
{ return _M_instance[__n]; }
const_reference
operator[](size_type __n) const
{ return _M_instance[__n]; }
```
to:
```
reference
operator[](size_type __n)
{
#ifdef _GLIBCXX_DEBUG
__glibcxx_check_subscript(__n);
#endif
return _M_instance[__n];
}
const_reference
operator[](size_type __n) const
{
#ifdef _GLIBCXX_DEBUG
__glibcxx_check_subscript(__n);
#endif
return _M_instance[__n];
}
```
This means you can enable bounds checking for array the same way you do for vector and other stl debugging - by adding `-D_GLIBCXX_DEBUG` to your compile line. E.g.:
```
g++ someAwesomeProgram.cpp -D_GLIBCXX_DEBUG
```
I just had a look at gcc trunk and apparently there is no reference to \_GLIBCXX\_DEBUG for array yet :(. <http://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/include/std/array>
Hopefully it's not too far away. I imagine we will have safe iterators and all that for array in debug mode soon enough. In the meantime, this can be our little secret :-). | ```
template<class T, std::size_t N>
T const& at(std::array<T,N> const& arr, std::size_t pos){
#ifndef NDEBUG
// debug versions, automatically range checked
return arr.at(pos);
#else
// release version, unchecked
return arr[pos];
#endif
}
template<class T, std::size_t N>
T& at(std::array<T,N>& arr, std::size_t pos){
typedef std::array<T,N> const& const_array;
// const_cast of the return is safe here because be pass a non-const array
// const_cast for the argument is needed to avoid infinite recursion
return const_cast<T&>(at(const_cast<const_array>(arr), pos));
}
```
Should do the job. Just use `at(arr, pos)` consistently throughout the codebase. |
9,483,348 | I use [google-gson](http://code.google.com/p/google-gson/) to serialize a Java map into a JSON string. It provides [a builder handles null values](https://sites.google.com/site/gson/gson-user-guide#TOC-Null-Object-Support):
```
Gson gson = new GsonBuilder().serializeNulls().create();
```
The problem is that the result is the string `null`, as in:
```
gson.toJson(categoriesMap));
{"111111111":null}
```
And the required result is:
```
{"111111111":""}
```
I can do a String-replace for `null` and `""`, but this is ugly and prone to errors. Is there a native gson support for adding a custom String instead of `null`? | 2012/02/28 | [
"https://Stackoverflow.com/questions/9483348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51197/"
] | In the actual version of gson you can do that:
```
Object instance = c.getConstructor().newInstance();
GsonBuilder gb = new GsonBuilder();
gb.serializeNulls();
Gson gson = gb.create();
String stringJson = gson.toJson(instance);
``` | There's no solution. I've [opened an issue at Gson's page](http://code.google.com/p/google-gson/issues/detail?id=416); Hope it will get fixed on the next version. |
95,337 | The official help does not mention such modification, but people mention this solution at various places on the net, saying they do this for quicker page load.
How can one be sure that it's an allowed modification of the default ad code (which otherwise loads during page load, before the window.load event), so one's account won't get suspended or banned for it? | 2016/06/16 | [
"https://webmasters.stackexchange.com/questions/95337",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/11093/"
] | According to this [Google Policy](https://support.google.com/adsense/answer/48182#beh):
>
> **Publishers are permitted to make modifications to the AdSense ad code** so long as those modifications do not artificially inflate ad performance or harm advertisers.
>
>
>
Loading Ad. script on Window load event in no way breaches this agreement. So by this one sentence alone, you can be sure that it is allowed.
Also, according to this [Modification of the AdSense ad code document](https://support.google.com/adsense/answer/1354736):
>
> In general, we recommend copying and pasting the ad code. In some situations though, **we understand that modifications are crucial to a clean user experience**.
>
>
>
So here as well you can see the same confirmation. Basically as long as you don't fundamentally change how the ads are being displayed, you are fine.
Furthermore, in the **Techniques to avoid** section, you'll see none of the points conflicts with window load event. On the other hand, the **Acceptable modifications** section clearly states:
>
> Here are **some** acceptable modifications ...
>
>
>
That means, not all the acceptable modifications are listed there. So, as long as you simply load the CODE in window load event & **do no further artificial delay**, Google have no reason to penalize you, since window load event is one of the most common **Browser Default** method people use to load additional scripts and contents. At best they may say that it's not necessary anymore & their [asynchronous CODE](https://support.google.com/adsense/answer/3221666?hl=en) is optimized enough.
Finally: I've done this myself on my own site and other client sites & never faced any problem whatsoever. Also didn't ever heard or seen anyone having any issue for this. Even a quick search on Google didn't reveal anything like that. So you should be fine. | This is not necessary. The latest ad code uses the "async" attribute on the script tag, which means it does not block rendering or delay loading of your site.
The tag that loads the script looks like this:
```
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
```
If you are loading multiple ads per page you should include that line once only (not once per ad). |
19,265,917 | I have a google+ share link that someone can click to share (on their own stream) a url specified by the rails app (not the current page).
I want to be able to record if the link was clicked and successfully shared. Here is the google+ share link code I'm using
```
<a href="https://plus.google.com/share?url=#{@user.website}" onclick="javascript:window.open(this.href,
'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;"><img
src="https://www.gstatic.com/images/icons/gplus-64.png" alt="Share on Google+"/></a>
```
I know it can be done with the Twitter api:
```
<script type="text/javascript">
twttr.ready(function (twttr) {
twttr.events.bind('tweet', function(event) {
$.post('<%="#{record_twitter_share_path}"%>');
});
});
</script>
```
But is there a way to do it with Google+ | 2013/10/09 | [
"https://Stackoverflow.com/questions/19265917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2135210/"
] | You cannot confirm if someone shared a post to their stream using the Share widget parameters or the JavaScript API. Niraj's answer is flawed and does not work, see [this JSBin to try it](http://jsbin.com/EhOpOba/1/edit?html,console,output).
In some situations, you can surround the widget with a div that you track the clicks on that div, but [that too doesn't work](http://jsbin.com/aVAZuHI/1/edit?html,console,output).
The one option that might work though it definitely won't work all the time given that the majority of user's on Google+ don't share most of their posts publicly is that you could use the [REST API's activities.search method](http://developers.google.com/+/api/latest/activities/search) and pass the URL that you're interested in as the search parameter, but you're not going to necessarily know that this particular user shared it, or it might be private, and depending on how popular your site is you might have to page through many pages of results possibly without luck. | It's possible to track a click on the button, but not the share itself. If you use the Google+ Web Share button, you can do something like the following:
```
<div class="g-plus" data-action="share" data-href="https://www.webniraj.com/2013/10/02/google-api-sharing-an-interactive-post/" data-onendinteraction="trackShare" data-onclick="trackShare"></div>
<!-- Place this asynchronous JavaScript just before your </body> tag -->
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function trackShare( jsonParam ) {
console.log( jsonParam );
}
</script>
```
The button has the `data-onclick="trackShare"` attribute set, which calls a JavaScript function to trigger logging.
The `console.log( jsonParam )` in the `trackShare` function will return something like:
```
{
"id": target URL,
"type": hover|confirm
}
```
However, in my testing, it only ever returns `type: hover`, even if it was shared successfully. |
3,007,419 | I have a function called init on my website in an external file called functions.php. Index.php loads that page and calls function init:
```
function init(){
error_reporting(0);
$time_start = microtime(true);
$con = mysql_connect("localhost","user123","password123");
mysql_select_db("db123");
}
```
How can I get all of these variables global(if possible) without having to use
```
global $time_start;
global $con;
``` | 2010/06/09 | [
"https://Stackoverflow.com/questions/3007419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/336983/"
] | If you want to specifically use globals, take a look at [$GLOBALS](http://www.php.net/manual/en/reserved.variables.globals.php) array. Even though there are couple of other ways, *[Pass by reference](http://php.net/manual/en/language.references.pass.php)*, *[Data Registry Object](http://zendframework.com/manual/en/zend.registry.using.html)* recommended, etc.
*[More on variable scopes](http://php.net/manual/en/language.variables.scope.php)*. | You can declare them in the global scope, then pass them to the function by reference. *After modifying the function to do so.* |
934 | I am at the end stages of choosing parts for my PC but am finding it quite difficult to choose a CPU cooler since there is so much to take in. Should I go for a standard CPU cooler (with fans), a fanless one or water cooling?
I am considering either water cooling / fanless because they are both quieter than normal coolers. Would you recommend going for a water cooling system or a fanless cooler? My only concern with the water cooling is that if in some way it malfunctions, it might damage my other parts. Out of the three options I know they
all have their positive and negatives but which one would you say is best?
* ***CPU*** - Intel Core i5-6600K 3.5GHz Quad-Core Processor
* ***Motherboard*** - Asus Z170-A ATX LGA1151 Motherboard
* ***Memory*** - Corsair Vengeance LPX 16GB (2 x 8GB) DDR4-2666 Memory
* ***Storage*** - Samsung 850 EVO-Series 250GB 2.5" Solid State Drive
* ***Case*** - NZXT H440 (Blue/Black) ATX Mid Tower Case
* ***Power Supply*** - SeaSonic X Series 400W 80+ Platinum Certified Fully-Modular Fanless ATX Power Supply
***Budget:*** Around £720 pounds (the parts listed above total £670 so the cooler is in budget as long as it is under £60 or there about).
### Edit: listening to all of the feedback, I have decided to go with the Cooler Master Hyper 212 EVO as it seems to be the best option for me. | 2015/10/29 | [
"https://hardwarerecs.stackexchange.com/questions/934",
"https://hardwarerecs.stackexchange.com",
"https://hardwarerecs.stackexchange.com/users/543/"
] | I don't recommend fanless or water cooling. Instead, I recommend [Cooler Master Hyper 212 EVO](http://www.newegg.com/Product/Product.aspx?Item=N82E16835103099) (which is a newer version of the [212 Plus](http://www.newegg.com/Product/Product.aspx?Item=N82E16835103065) I have).
[](https://i.stack.imgur.com/MVHnx.jpg)
This is a very quiet fan. The specs say it's between 9-36 dBA. For me, it's quieter than the noise my video card generates. It keeps the CPU cool too. I don't have a "before" comparison, as it was installed when I built the machine, but I have had no issues with the temperature of the CPU. This is despite very processor intensive tests and real world work.
Newegg is selling this for $30, which Google is telling me is about £20. | This is a slightly more budget friendly option, which is according to the budget which was just edited in, the Noctua NH-D14.
This CPU cooler keeps temps pretty low, about 5\*C higher on an i7-4770k than the NZXT Kraken x61 I mentioned above.
The NH-D14 is an air cooler available [here](http://www.amazon.co.uk/dp/B002VKVZ1A/?tag=pcp0f-21http://www.amazon.co.uk/dp/B002VKVZ1A/?tag=pcp0f-21), for 56 pounds.
Pros
----
* Is an air cooler, and therefore does not have the probability to leak
* Is within the budget
* Is colder than the 212 evo
Cons
----
* Not as cold as the Kraken x61
* Looks ugly as heck
* Is only 4 pounds lower than the budget.
 |
10,378,926 | I m using jsf2.0. And i m making one email application, I m calling web service to read the content of the file, and i m using SAX parser to extract the content from the to read the file. And i m storing that content in string variable and set it in setter method. And displaying it in outputLabel. Now, problem is when the content is displayed in jsf page at that time it is not displaying in proper format. it's displayed in one line. But when i see the view source of page at that time in view source it's displayed in proper format. So,what should be the solution. Please reply me.
Thanks in advance. | 2012/04/30 | [
"https://Stackoverflow.com/questions/10378926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1260898/"
] | Check out if `h:outputText`'s `escape` flag set to `false` can help you.
>
> escape: This attribute sets a boolean flag value that determines if
> sensitive HTML and XML characters should be escaped in the output
> generated by the component. It's default value is "true".
>
>
>
(Description from [here](http://www.roseindia.net/jsf/outputText.shtml)) | Set the CSS `white-space` property of the parent element to `pre`.
E.g.
```
<h:outputText value="#{bean.xml}" styleClass="preformatted" />
```
with
```css
.preformatted {
white-space: pre;
}
``` |
8,985,569 | I have 5 views(.ui.xml). On every view i paste soemthing like that:
```
<ui:style src="../MyStyle.css" />
```
and on every button on every page I put styleName attribute:
```
<g:Button ui:field="buttonName" styleName="{style.myButtonStyle}" />
```
My Question is: Do I have to put styleName for all my buttons ? I would like to do something general style for this kind of widget .
What is good practice for this case? | 2012/01/24 | [
"https://Stackoverflow.com/questions/8985569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/458197/"
] | Have you tried to customize [GWT themes](http://code.google.com/intl/ru/webtoolkit/doc/latest/DevGuideUiCss.html#themes) or create your own ? I think this is what you need to do. | Create your own button MyButton by extending Composite and define the UIBinder for this Button with style once.
Next you can re-use this button by adding your own namespace in the views.
Here's your widget :
```
package com.example.widgets;
...
public class MyButton extends Composite {
interface MyButtonUiBinder extends UiBinder<Widget, MyButton> {
}
private static MyButtonUiBinder uiBinder = GWT.create(MyButtonUiBinder.class);
@UiField
Button wrapped;
public MyButton() {
initWidget(uiBinder.createAndBindUi(this));
}
}
```
and the UIBinder file :
```
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
xmlns:g='urn:import:com.google.gwt.user.client.ui'>
<ui:style>
.myStyle {
text-shadow: gray;
color: gray;
font-size: 12px;
text-decoration: italic;
}
</ui:style>
<g:HTMLPanel>
<g:Button ui:field="wrapped" styleName="{style.myStyle}" />
</g:HTMLPanel>
</ui:UiBinder>
```
In your views, you can now include this button in the UIBinder files :
```
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g='urn:import:com.google.gwt.user.client.ui' xmlns:k='urn:import:com.example.widgets'>
<g:AbsolutePanel width="350px" height="225px">
<g:at left='10' top='0'>
<k:MyButton></k:MyButton>
</g:at>
</g:AbsolutePanel>
</ui:UiBinder>
```
If you need to set the text or other properties on your personal widget, simply delegate the methods from the wrapped button to expose them. |
4,637,036 | I have the following directory layout:
```
runner.py
lib/
tests/
testsuite1/
testsuite1.py
testsuite2/
testsuite2.py
testsuite3/
testsuite3.py
testsuite4/
testsuite4.py
```
The format of testsuite\*.py modules is as follows:
```
import pytest
class testsomething:
def setup_class(self):
''' do some setup '''
# Do some setup stuff here
def teardown_class(self):
'''' do some teardown'''
# Do some teardown stuff here
def test1(self):
# Do some test1 related stuff
def test2(self):
# Do some test2 related stuff
....
....
....
def test40(self):
# Do some test40 related stuff
if __name__=='__main()__'
pytest.main(args=[os.path.abspath(__file__)])
```
The problem I have is that I would like to execute the 'testsuites' in parallel i.e. I want testsuite1, testsuite2, testsuite3 and testsuite4 to start execution in parallel but individual tests within the testsuites need to be executed serially.
When I use the 'xdist' plugin from py.test and kick off the tests using 'py.test -n 4', py.test is gathering all the tests and randomly load balancing the tests among 4 workers. This leads to the 'setup\_class' method to be executed every time of each test within a 'testsuitex.py' module (which defeats my purpose. I want setup\_class to be executed only once per class and tests executed serially there after).
Essentially what I want the execution to look like is:
```
worker1: executes all tests in testsuite1.py serially
worker2: executes all tests in testsuite2.py serially
worker3: executes all tests in testsuite3.py serially
worker4: executes all tests in testsuite4.py serially
```
while `worker1, worker2, worker3 and worker4` are all executed in parallel.
Is there a way to achieve this in 'pytest-xidst' framework?
The only option that I can think of is to kick off different processes to execute each test suite individually within runner.py:
```
def test_execute_func(testsuite_path):
subprocess.process('py.test %s' % testsuite_path)
if __name__=='__main__':
#Gather all the testsuite names
for each testsuite:
multiprocessing.Process(test_execute_func,(testsuite_path,))
``` | 2011/01/09 | [
"https://Stackoverflow.com/questions/4637036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | With pytest-xdist there currently no kind of "per-file" or "per-test-suite" distribution. Actually, if a per-file distribution (e.g. tests in a file will be only executed by at most one worker at a time) would already help your use case i encourage you to file a feature issue with the pytest issue tracker at <https://bitbucket.org/hpk42/pytest/issues?status=new&status=open> and link back to your good explanation here.
cheers,holger | Having test suites in directory like in the question, you can run them in parallel it via:
```
pytest -n=$(ls **/test*py | wc -l) --dist=loadfile
```
If you have your tests suite files in single directory then just
```
pytest -n=$(ls test*py | wc -l) --dist=loadfile
```
In case new suite file occurs, this will include new test file automatically and will add additional worker for it |
33,240,871 | Android studio has updated and before everything was going ok but now with this update I cant seem to get my next activity after successful login to start, here:
```
public void doLogIn(View v) {
EditText username = (EditText) findViewById(R.id.userEditText);
EditText password = (EditText) findViewById(R.id.passwordditText);
final Intent intent = new Intent(this, Menu.class);
if (username.getText().toString().isEmpty() || password.getText().toString().isEmpty()) {
//Intent intent = new Intent(this, Registro_activity.class);
//intent.putExtra(EXTRA_MESSAGE, change);
Toast.makeText(this, "Necesitas poner tu usuario y la contraseña para acceder.", Toast.LENGTH_LONG).show();
} else {
Log.d("We", "are almost");
ParseUser.logInInBackground(username.getText().toString(), password.getText().toString(), new LogInCallback() {
@Override
public void done(ParseUser user, com.parse.ParseException e) {
if (user != null) {
// Hooray! The user is logged in.
Log.d("IN", "APP");
validLogin(e);
startActivityNew(intent);
} else {
// Signup failed. Look at the ParseException to see what happened.
Log.d("error", e.toString());
invalidLogin(e);
}
}
});
}
}
public void startActivityNew(Intent intent) {
startActivity(intent);
}
```
And it is declared in AndroidManifest.xml as:
```
<application
android:name=".StarterApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.parse.APPLICATION_ID"
android:value="@string/parse_app_id" />
<meta-data
android:name="com.parse.CLIENT_KEY"
android:value="@string/parse_client_key" />
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ChangePass"
android:label="@string/title_activity_change_pass" >
</activity>
<activity
android:name=".Menu"
android:label="@string/title_activity_menu"
android:parentActivityName=".MainActivity"
android:theme="@style/AppTheme" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.parse.starter.MainActivity" />
</activity>
</application>
```
The error:
```
10-19 23:44:58.922 21649-21649/com.parse.starter E/AndroidRuntime: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.parse.starter/android.view.Menu}; have you declared this activity in your AndroidManifest.xml?
```
What has happened?? Any help?? | 2015/10/20 | [
"https://Stackoverflow.com/questions/33240871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1423656/"
] | Solved it. The problem was that the user that handles Rails on the virtual server didn't have all the access needed to generate files on behalf of paperclip in the app's folder. So I gave larger access to the folder using this terminal command:
```
$ sudo chmod -R 775 /RailsAppFolder
``` | Try to replace
```
path: "~rails/umbertoputzu/public/system/:attachment/:id/:style/:filename",
```
with
```
path: "~/rails/umbertoputzu/public/system/:attachment/:id/:style/:filename",
``` |
18,240 | I worked for a company that named the pc's after roman gods (zeus, mars...). That was quiet funny while there where only 5 pc's on the network, but after changing the pc's several times I didn't remember my pc name. What naming convention do you use or what was the most useless naming convention you ever used? | 2009/06/02 | [
"https://serverfault.com/questions/18240",
"https://serverfault.com",
"https://serverfault.com/users/13733/"
] | There is actually an [RFC (1178)](http://www.faqs.org/rfcs/rfc1178.html) regarding best practice in naming computers.
The following is discouraged by this RFC:
* Don't overload other terms already in common use.
* Don't choose a name after a project unique to that machine.
* Don't use your own name.
* Don't use long names.
* Avoid alternate spellings.
* Avoid domain names
* Don't use antagonistic or otherwise embarrassing names
* Don't use digits at the beginning of the name.
* Don't use non-alphanumeric characters in a name
* Don't expect case to be preserved
Guidence for naming given by this RFC is:
* Use words/names that are rarely used
* Use theme names
* Use real words
And as always *"There is always room for an exception"* | I mostly use names from a **set of names**.
Examples:
* Characters from animated series (Simpsons, American Dad, Family Guy)
* Names of [real stars](http://en.wikipedia.org/wiki/List_of_traditional_star_names) (Sol, Arktur, Maia, Bellatrix, Deneb, ...)
* Names of (semi-)fictious Star Trek planets (Chronos, Vulcan, Risa, Bajor, ...)
Sometimes when I can't think of a good set I use **[Google Sets](http://labs.google.com/sets)**. |
5,601,222 | I would like to know the difference between two conventions:
1. Creating an abstract base class with an abstract method
which will be implemented later on the derived classes.
2. Creating an abstract base class without abstract methods
but adding the relevant method later on the level of the derived classes.
What is the difference? | 2011/04/08 | [
"https://Stackoverflow.com/questions/5601222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/698895/"
] | Much like interfaces, abstract classes are designed to express a set of known operations for your types. Unlike interfaces however, abstract classes allow you to implement common/shared functionality that may be used by any derived type. E.g.:
```
public abstract class LoggerBase
{
public abstract void Write(object item);
protected virtual object FormatObject(object item)
{
return item;
}
}
```
In this really basic example above, I've essentially done two things:
1. Defined a contract that my derived types will conform to.
2. Provides some default functionality that could be overriden if required.
Given that I know that any derived type of `LoggerBase` will have a `Write` method, I can call that. The equivalent of the above as an interface could be:
```
public interface ILogger
{
void Write(object item);
}
```
As an abstract class, I can provide an additional service `FormatObject` which can optionally be overriden, say if I was writing a `ConsoleLogger`, e.g.:
```
public class ConsoleLogger : LoggerBase
{
public override void Write(object item)
{
Console.WriteLine(FormatObject(item));
}
}
```
By marking the `FormatObject` method as virtual, it means I can provide a shared implementation. I can also override it:
```
public class ConsoleLogger : LoggerBase
{
public override void Write(object item)
{
Console.WriteLine(FormatObject(item));
}
protected override object FormatObject(object item)
{
return item.ToString().ToUpper();
}
}
```
So, the key parts are:
1. `abstract` classes must be inherited.
2. `abstract` methods must be implemented in derived types.
3. `virtual` methods can be overriden in derived types.
In the second scenario, because you wouldn't be adding the functionality to the abstract base class, you couldn't call that method when dealing with an instance of the base class directly. E.g., if I implemented `ConsoleLogger.WriteSomethingElse`, I couldn't call it from `LoggerBase.WriteSomethingElse`. | In the case 1) you can access those methods from the abstract base type without knowing the exact type (abstract methods are virtual methods).
The point of the abstract classes is usually to define some contract on the base class which is then implemented by the dervied classes (and in this context it is important to recognize that interfaces are sort of "pure abstract classes"). |
121,222 | I found a very old pot in my very old house. I suspect it to be carbon steel, for the following reasons:
1. It's rusty
2. It's magnetic
3. It looks a lot like the carbon steel pans that were stored with it, except it's the shape of a pot
I would like to use it for the same purposes one usually uses a pot: cooking rice, boiling water etc.
I am wondering how that works though:
* If I follow the same processes as with a carbon steel pan, I would always have a thin layer of oil on the walls and bottom. Can one cook rice or pasta in such a pot, with boiling water?
* If I season but I don't add a thin layer of oil everytime, I am afraid the pot will rust very quickly
Does anybody know how to use such a pot?
---
Side note on why:
I am well aware that using another pot would be simpler. The reasons why I am asking this question are the following:
* The goal is to use the pot over a wood fire. The aforementioned pot used to be used in such a setting, thus wouldn't be dirtied by doing so. Conversely I don't have other pots whose cleanliness I would be willing to sacrifice
* The goal is also to give a new life to this pot, which is probably a century old, and use it the same way the previous inhabitants of this house did
* More generally, I am interested to know how cumbersome it would be to use it
Thanks in advance for the help | 2022/08/02 | [
"https://cooking.stackexchange.com/questions/121222",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/100262/"
] | I am with Bon Appetit on this one, or even more extreme - I always pan-fry mushrooms on the highest heat setting.
For me, the keys for nice, browned mushrooms on a domestic stove are:
* Use very *high heat*, and preheat the pan before the first batch.
* *Don't crowd* the pan, make a single layer of mushrooms.
* Use a proper *turning*/stirring regime. That mostly includes to have the patience to wait for the mushrooms to brown well on one side before flipping them to another.
McGee's advice sounds intriguing, but note that he specifies
>
> with dry heat
>
>
>
At least for me, that is incompatible with the "cooked slowly" suggestion. Whenever I try to pan fry mushrooms on medium or low heat, the water they exude stays around, instead of instantly evaporating the way it does on a hot pan. They just stew around in their own sauce, which makes them soggy, bland, rubbery, and prevents caramelization.
I don't know why it works for McGee; it might be that he has some technique trick I don't know, or maybe he simply leaves mushrooms in a low oven overnight with the intention to produce a kind of undiluted stew, or even to process them further to something marmitey. But for pan-frying, I have never had success with medium or low temperatures. | While I often cook mushrooms the way @rumtscho does, I wouldn't discount the advice of Harold McGee ([refer to top right, p. 346](http://wtf.tw/ref/mcgee.pdf)). If you are looking to maximize flavor, it might be worth experimenting with a combination of both techniques. The important point McGee makes is that when heated, the enzymatic action enhances the flavor. Too hot, too soon, and those enzymes don't get a chance to do their flavor thing before the heat inactivates them (same is true in something like a sweet potato, btw). So, to more precisely address your desire to achieve the MOST flavor. It appears you need to maximize enzymatic activity. In this case, I would follow McGee's advice for as long (in terms of cooking time) as possible...depending on your final product. Loss of water, remember, is also concentrating flavor. If you find there is too much, you can always continue to cook, and allow that water to evaporate...or ultimately turn up the heat. Also consider, that different mushrooms (foraged, for example) require different cooking techniques. So you may have to take that into account as well. |
19,331,941 | Why don't the numeric arrays end with a null character?
For example,
```
char name[] = {'V', 'I', 'J', 'A', 'Y', '\0'};
```
But in case of numeric arrays there is no sign of null character at the end...
For example,
```
int marks[] = {20, 22, 23};
```
What is the reason behind that? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19331941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2873504/"
] | An array of char not necessarilly ends with \0.
It is a C convention that strings are ended with \0.
This is useful to find the end of the string.
But if you are only interested in holding data that is of type char, you can have a \0 at end or not.
If your array of char is intended to be used as a string, you should add \0 at the end of it.
**EDIT**: What is ended by \0 are the string literals, not the array of char.
The question is ill formulated. | **We have a convention:** special character `'0'` with numeric code `0`, marks end of the string.
But if you want to mark end of `int` array, how will you know is that `0` is a valid array member or end-of-array mark? So, in general, it is not possible to have such a mark.
**In other words:**
The character `'\0'` (but not character `'0'`, code `48`) **have no any sense** in context of text string (by convention, it is a special character, that marks end), so it **can** be used as end-of-array mark:
Integer `0` or `\0` (which is the same), are valid integer. It **can have sense**, and that is why it **cannot** be used as end-of-array mark:
`int votesInThisThread[] = { 0, -1, 5, 0, 2, 0 }; // Zeroes here is a valid numbers of upvotes`
If you'l try to detect end of this example array by searching `0`, you'll get size of 0.
That is what question about? |
41,423,373 | Below is what I am trying to achieve. I have a procedure which receives employeeIds as optional arguments and stores them into a temp table (temp\_table) like this
```
empId
-------
3432
3255
5235
2434
```
Now I need to run below query in 2 conditions:
**1st condition**: if argument is non blank then my query should be-
```
SELECT *
FROM DEPARTMENTS
INNER JOIN temp_table ON emp_no = empId
```
**2nd condition**: if argument is blank it will take all the rows from department table
```
SELECT *
FROM DEPARTMENTS
```
One option I can use is:
```
IF (@args <> '')
BEGIN
SELECT *
FROM DEPARTMENTS
INNER JOIN temp_table ON emp_no = empId
END
ELSE
BEGIN
SELECT *
FROM DEPARTMENTS
END
```
But I am looking for a better option where I don't need to write almost same query twice. Please help. | 2017/01/02 | [
"https://Stackoverflow.com/questions/41423373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7364392/"
] | I recommend to stick to what you are already doing.
It is the cleanest and safest way performance wise. | Try this one
```
SELECT *
FROM DEPARTMENTS
WHERE (
@args <> ''
OR EXISTS (SELECT 1 FROM temp_table WHERE emp_no = empId)
)
``` |
73,760,710 | So I'm trying to study in advance about css/html. I wanted to get rid of the extra space after the navigation pane and i can't remove it. can someone help me? thanks. also I'm having a hard time putting some elements on every section and putting some animation in it(any recommendations?)
```css
**/* what line should i edit*/**
body {
font-family: 'Roboto', sans-serif;
padding: 0;
margin: 0;
box-shadow: 0px 0px 0px #dedede;
}
h1 {
text-align: center;
padding: 50px 0;
font-weight: 800;
margin: 0;
letter-spacing: -1px;
color: inherit;
font-size: 40px;
}
section {
height: 100vh;}
nav {
width: 100%;
margin: 0 ;
background: #fff;
padding: 0px 0;
box-shadow: 0px 5px 0px #dedede;
}
nav ul {
list-style: none;
text-align: center;}
nav ul li {
display: inline-block;}
nav ul li a {
display: block;
padding: 15px;
text-decoration: none;
color: #aaa;
font-weight: 800;
text-transform: uppercase;
margin: 0 ;
}
{
nav ul li a,
nav ul li a:after,
nav ul li a:before
transition: all .5s;
}
nav ul li a:hover {
color: #555;}
```
```html
<html>
<head>
<title> Main Page </title>
<link rel="stylesheet" href="navpanecss.css">
</head>
<h1> MY WEBSITE </h1>
<nav class="stroke">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Downloads</a></li>
<li><a href="#">More</a></li>
<li><a href="#">Nice staff</a></li>
</ul>
</nav>
<section style="background: #D7FFF1">
<article>
</article>
</section>
<section style="background: #aafcb8">
<nav class="fill">
</nav>
</section>
</section>
<section style="background: #FFA69E">
<nav class="fill">
</nav>
</section>
</html>
``` | 2022/09/18 | [
"https://Stackoverflow.com/questions/73760710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20024260/"
] | This is because of scoped recomposition. Any Composable that is not inline and returns Unit is a scope. Compose only triggers recomposition in nearest scope. In your example it's Button's scope. You can check out this question which is very similar
[Why does mutableStateOf without remember work sometimes?](https://stackoverflow.com/questions/71045838/why-does-mutablestateof-without-remember-work-sometimes?noredirect=1&lq=1) | In this particular example when you click the button, only lines 42-47 will be recomposed. You can verify this by adding a log statement in line 41.
When the whole `MyChildUI` composable recomposes, the value of the `count` will be reset to 1.
So, you should use `remember` to avoid issues. |
9,998,243 | I'm trying to do some analysis for an upcoming project.
It has something to do with trending, charting and analysis; so think MAX, MIN, AVG, SUM etc over a period of time.
Say we have an OLAP cube that's setup to figure out these calculations against a time dimension.
In theory the backend is there to query the cube and get the results for some object A for some property B for a bunch of days in a month or a year or whatever the case may be (i.e over the last 5 years and you can manipulate the rendered date range by using a slider window similar to those used on finance stock charts to expand or narrow your field of view).
Some of us are thinking we can query the cube using MDX to drive a UI that uses some HTML 5 charting tools.
I'm new to OLAP, MDX, Cubes etc
but it seems that there isn't a clean way of retrieving the results of an MDX query in .NET code (we'll be using C# in an MVC web site).
So far what we've found will probably work best is ADOMD.
I'm wondering if there are any alternatives folks can suggest.
Is anyone using an OLAP cube and MDX queries to drive their web site?
It seems to me that if the cube is already setup properly to answer questions like object A for property B for the last 2 months, then we should be able to query the cube for exactly that data and display it how we see fit on some UI. I'm not sure there's a clean way of doing so though.
Any suggestions, insight, ideas would be appreciated. | 2012/04/03 | [
"https://Stackoverflow.com/questions/9998243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62068/"
] | 5 years ago...
I worked on a project which had a drag-and-drop interface (HTML and an awful lot of JS) to allow users to construct custom cube queries exactly as they wanted. We called an ASP with ajax to go get the cube data with ADOMD and return it as an HTML table. Charting was via custom JS which created SVG. (It would be easier these days with .NET and JQuery, but still a lot of work.)
It sounds ropey, but worked well and was reliable enough to sell to the UK's largest hospitality firms to analyse their sales data.
Whenever I had a problem, and Googled for help, it seemed like I was the only one who was presenting OLAP data over the Internet (most people were within an intranet situation, and wewre not using web-browsers to deliver either). I don't know if the situation has changed now, but I do believe OLAP is seen as a way to look at your own data, not manage a customer's data and enable them to see it.
My advice:
1. If you hear the words 'pivot tables' then run away
2. If customers want user-level or location-level security (roles), run away
3. Make sure you are very good at writing MDX, since people will ask you to construct complex reports for them (they won't always want to use a UI to configure a report)
4. Cubes take time to build, but sometimes people expect to see real-time changes when they hit refresh (SQL does this, but OLAP needs reprocessing time)
5. Drillable charts are cool, and great for finding anomolies | One thing we've done in the past that works fairly well, though some might see it as a cop-out - we've used SSIS packages with embedded MDX queries that flatten data out and stores it in two dimensional SQL tables.
For example - we took an OLAP cube and flattened data out by day, week, etc. along with the calculations as additional columns. This allowed us to do super-fast queries against the data using AJAX. This solution works particularly well for MDX calculations that take a while to process for data sets that update once a day or once a week. We'd just trigger the SSIS-to-SQL sync package to run at night after the normal ETL processes had run.
MDX calcs that might have taken 20 seconds to refresh could be flattened into SQL and retrieved in milliseconds, giving the users essentially the same data as their full OLAP reports and instant response times. We then paired this method up with charting libraries to display summary data.
Just food for thought. |
12,756,324 | Is there a control to show an animated gif in a Windows Store (Metro) app in Windows 8? I am using C# and XAML with databinding. | 2012/10/06 | [
"https://Stackoverflow.com/questions/12756324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573218/"
] | The Image control doesn't support animated GIFs. You will need to extract the frames and animate them on your own timer.
You should take a look at this link which might help you regarding your question:
<http://advertboy.wordpress.com/2012/05/08/animated-gifs-in-xamlc/> | Just for a note: you can use the BitmapDecoder class to read the GIF frames, create a storyboard an animated them.
I've got an example of an Windows 8 user control on my blog: <http://www.henrikbrinch.dk/Blog/2013/02/21/Windows-8---GIF-animations--the-RIGHT-way> |
25,986,114 | I've just read and watched about 20 videos, StackOverFlow questions and articles but they're all outdated.
[This tutorial](http://www.appcoda.com/use-storyboards-to-build-navigation-controller-and-table-view/) and [video](http://vimeo.com/53563148) were the most helpful. You can see I followed the steps, but nothing happens when I click a cell.
I also overwrite didSelectRowAtIndexPath with some actions, and that executes properly when I click a cell, but the segue doesn't do anything.
I'm trying to setup my app so users look at the 2 tabs (each containing TableView) and can click on a cell to be sent to another screen. Similar to the interface of Twitter... tabs, and click on a TableView cell to view individual information.
When I used the Editor > Embed In feature of Xcode, it placed the Navigation Controller before the Table View. However, previously, I've been trying to: `TabView -> UINavigationController -> UIViewController`. I'm not sure who is right here. I tried both, and both didn't cause the view to change when I clicked a cell.
This should be able to be done without code, right?
1st attempt: Below I've done the first tab using the Editor > Embed In feature.

Another different approach/attempt: Below I've dragged in a navigation controller (which brought 2 boxes, one being a TableView for some reason) and setup a segue from the original TableView to the navigation controller.
 | 2014/09/23 | [
"https://Stackoverflow.com/questions/25986114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2199852/"
] | There were two parts missing in your project:
1. The identifier for the segue on the Main.storyboard. I named it *details*.
2. `self.performSegueWithIdentifier("details", sender: self)` in the *tableView delegate* **didSelectRowAtIndexPath**.
Happy xCoding. | I was about to comment, but i do not have enough reputation.
in addition to what @minneostasteve said, your storyboard is actually correctly set up in the first pic but not in the second pic
ie. tab bar controller -> navi controller -> tableviewcontroller -> viewcontroller |
38,726,810 | When the user types in the textbox i want it to format itself with decimals.
For example, if the user types `10000` I want it to show up like `10,000` while he types it. | 2016/08/02 | [
"https://Stackoverflow.com/questions/38726810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5829467/"
] | That problem proved to be more challenging than I expected (I should have known better). Here is what I got, using vanilla Javascript.
You can set event handler for the `onkeyup` event of the TextBox:
```
<asp:TextBox ID="txtAutoFormat" runat="server" onkeyup="processKeyUp(this, event)" />
```
And here is the Javascript code:
```
<script type="text/javascript">
function extractDigits(str) {
return str.replace(/\D/g, '');
};
function findDigitPosition(str, index) {
var pos = 0;
for (var i = 0; i < str.length; i++) {
if (/\d/.test(str[i])) {
pos += 1;
if (pos == index) {
return i + 1;
}
}
}
};
function isCharacterKey(keyCode) {
// Exclude arrow keys that move the caret
return !(35 <= keyCode && keyCode <= 40);
};
function processKeyUp(txt, e) {
if (isCharacterKey(e.keyCode)) {
var value = txt.value;
// Save the selected text range
var start = txt.selectionStart;
var end = txt.selectionEnd;
var startDigit = extractDigits(value.substring(0, start)).length;
var endDigit = extractDigits(value.substring(0, end)).length;
// Insert the thousand separators
txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");
// Restore the adjusted selected text range
txt.setSelectionRange(findDigitPosition(txt.value, startDigit), findDigitPosition(txt.value, endDigit));
}
};
</script>
```
**Credits:**
CMS's solution to extract digits from string in [Regex using javascript to return just numbers](https://stackoverflow.com/questions/1183903/regex-using-javascript-to-return-just-numbers/1183922#1183922).
Alan Moore's regular expression to insert thousand separators in [How do I add thousand separators with reg ex?](https://stackoverflow.com/questions/1228129/how-do-i-add-thousand-separators-with-reg-ex/1229268#1229268).
**Note:** Ron Royston's idea of using `toLocaleString` is also very interesting. It could provide a more universal solution. You could replace this line of `processKeyUp`:
```
txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");
```
with the following:
```
txt.value = Number(extractNumber(value)).toLocaleString();
``` | Try an input mask, here is an example:
<http://digitalbush.com/projects/masked-input-plugin/> |
24,476,805 | I am new to node.js. I downloaded and install node.js installer from the [official site](http://nodejs.org/download/). I have added this installer folder in PATH environment variable and I am able to run programs. But when I try to install some package using npm in node console it shows the error `npm should be run outside of the node repl, in your normal shell`. I also tried it on a separate console. But it shows command not found though I have added node in the environment variable.

 | 2014/06/29 | [
"https://Stackoverflow.com/questions/24476805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2396539/"
] | For Windows users, run `npm` commands from the Command Prompt (cmd.exe), not *Node.Js* (node.exe). **So your *"normal shell"* is cmd.exe**. *(I agree this message can be confusing for a Windows, Node newbie.)*
By the way, the *Node.js Command Prompt* is actually just an easy shortcut to *cmd.exe*.
Below is an example screenshot for installing grunt from cmd.exe:
 | [](https://i.stack.imgur.com/recta.png)
**Just open Node.js commmand promt as run as administrator** |
7,943,171 | For example:
```
Pattern pattern = Pattern.compile("a(.*)b");
Matcher matcher = pattern.matcher("a19203b");
matcher.find();
System.out.println(matcher.group());
```
This prints out the entire string (`a19203b`). All I need is `19203`. How can I get this in Java?
(for example, in a mod\_rewrite rule, I would do something like `RewriteRule article/(.*) article.php?id=$1` where `$1` is the string I need) | 2011/10/30 | [
"https://Stackoverflow.com/questions/7943171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/450164/"
] | Found the solution. Instead of `matcher.group()`, use `matcher.group(1)`.
```
Pattern pattern = Pattern.compile("a(.*)b");
Matcher matcher = pattern.matcher("a19203b");
matcher.find();
System.out.println(matcher.group(1));
``` | Use lookbehinds/lookaheads :
```
Pattern regex = Pattern.compile("(?<=a).*(?=b)");
```
Don't capture what you don't want to capture. Here your entire match will be what you want. |
29,381,233 | I am using Python 2.7 and Selenium 2.44.
I want to *automate drag and drop* action in Selenium WD but according to other related posts **Actions in HTML5 are not supported by Selenium** yet. Is there any way to simulate drag and drop in Python?
Here is the code I tried:
```
driver = webdriver.Firefox()
driver.get("http://html5demos.com/drag")
target = driver.find_element_by_id("one")
source = driver.find_element_by_id("bin")
actionChains = ActionChains(driver)
actionChains.drag_and_drop(target, source).perform()
```
and it did not work. | 2015/04/01 | [
"https://Stackoverflow.com/questions/29381233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2100011/"
] | Yes, HTML5 "drag&drop" **is not currently supported** by Selenium:
* [Issue 3604: HTML5 Drag and Drop with Selenium Webdriver](https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/3604)
One of the [suggested workarounds](http://elementalselenium.com/tips/39-drag-and-drop) is to *simulate HTML5 drag and drop* via JavaScript:
* download [`drag_and_drop_helper.js`](https://gist.github.com/rcorreia/2362544)
* execute the script via `execute_script()` calling `simulateDragDrop()` function on a `source` element passing the `target` element as a `dropTarget`
Sample code:
```
with open("drag_and_drop_helper.js") as f:
js = f.read()
driver.execute_script(js + "$('#one').simulateDragDrop({ dropTarget: '#bin'});")
```
The problem is that it won't work in your case "as is" since it **requires `jQuery`**.
---
Now we need to figure out **how to dynamically load jQuery**. Thankfully, [there is a solution](https://sqa.stackexchange.com/a/3453/5574).
Complete working example in Python:
```
from selenium import webdriver
jquery_url = "http://code.jquery.com/jquery-1.11.2.min.js"
driver = webdriver.Firefox()
driver.get("http://html5demos.com/drag")
driver.set_script_timeout(30)
# load jQuery helper
with open("jquery_load_helper.js") as f:
load_jquery_js = f.read()
# load drag and drop helper
with open("drag_and_drop_helper.js") as f:
drag_and_drop_js = f.read()
# load jQuery
driver.execute_async_script(load_jquery_js, jquery_url)
# perform drag&drop
driver.execute_script(drag_and_drop_js + "$('#one').simulateDragDrop({ dropTarget: '#bin'});")
```
where `jquery_load_helper.js` contains:
```
/** dynamically load jQuery */
(function(jqueryUrl, callback) {
if (typeof jqueryUrl != 'string') {
jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
}
if (typeof jQuery == 'undefined') {
var script = document.createElement('script');
var head = document.getElementsByTagName('head')[0];
var done = false;
script.onload = script.onreadystatechange = (function() {
if (!done && (!this.readyState || this.readyState == 'loaded'
|| this.readyState == 'complete')) {
done = true;
script.onload = script.onreadystatechange = null;
head.removeChild(script);
callback();
}
});
script.src = jqueryUrl;
head.appendChild(script);
}
else {
callback();
}
})(arguments[0], arguments[arguments.length - 1]);
```
Before/after result:

 | Java version is in below commit
<https://github.com/vikramvi/Selenium-Java/commit/a1354ca5854315fded8fc80ba24a4717927d08c7> |
22,578,737 | I like to implement a function if I click on the button so in my tbody clear all tr tags after the first tr tag.
Here my HTML example:
```
<table id="event_table">
<thead>
<tr>
<th>date</th>
<th>time</th>
<th>action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
blabla
</td>
<td>
blabla
</td>
<td>
blabla
</td>
</tr>
<!-- from here clear all tr tag -->
<tr>
<td>
blubblub
</td>
<td>
blubblub
</td>
<td>
blubblub
</td>
</tr>
<tr>
<td>
blubblub
</td>
<td>
blubblub
</td>
<td>
blubblub
</td>
</tr>
</tbody>
</table>
<input type="submit" class="enter">
```
Here my jQuery Code:
```
jQuery(".enter").click(function() {
jQuery('#event_table > tbody > tr:first-child + tr').empty();
});
```
Here my jsFiddle Example: <http://jsfiddle.net/D4cx9/2/>
But my example don't works correctly.
What am I doing wrong?
Hope someone can help me. | 2014/03/22 | [
"https://Stackoverflow.com/questions/22578737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3319587/"
] | Your selector only select the next siblind tr after the first one. If you want to select all the `tr`s after the first child use the [`~` General sibling selectors](http://www.w3.org/TR/selectors/#general-sibling-combinators), also `empty` just empties the element, it does not remove it, use `remove` instead
```
jQuery('#event_table > tbody > tr:first-child ~ tr').empty();
```
<http://jsfiddle.net/D4cx9/4/> | And also:
```
$('#event_table > tbody > tr:gt(0)').remove();
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.