id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,640,742 | Convert double to float without Infinity | <p>I'm converting double to float using ye old <code>float myFloat = (float)myDouble</code>.</p>
<p>This does however sometimes result in "Infinity", which is not good for the further processing I'm doing. I'm okay with loss as long as it is pointing in the general direction as the original number (the relative number 'strength' on all numbers I'm converting must be maintained).</p>
<p>How can I convert float to double and avoid Infinity?</p>
<p>Background:<br />
I'm reading a bytestream from wav/mic, converting it to <code>float</code>, converting it to <code>double</code>, running it through FFT calculation (this is what requires <code>double</code>), and now I want it back to <code>float</code> (storing the data in 32-bit image container).</p> | 6,640,771 | 4 | 0 | null | 2011-07-10 11:18:25.37 UTC | null | 2017-03-13 08:22:33.79 UTC | 2012-09-24 11:58:44.933 UTC | null | 587,884 | null | 313,088 | null | 1 | 28 | c#|types|floating-point|double | 95,266 | <p>So if the value is greater than <code>float.MaxValue</code>, are you happy for it to just be <code>float.MaxValue</code>? That will effectively "clip" the values. If that's okay, it's reasonably easy:</p>
<pre><code>float result = (float) input;
if (float.IsPositiveInfinity(result))
{
result = float.MaxValue;
} else if (float.IsNegativeInfinity(result))
{
result = float.MinValue;
}
</code></pre> |
57,007,749 | date.getDate is not a function Typescript | <p>I have 3 input controls two date type and one is number, what i wanna to do is get the date from 1st control and no. of days from other controls add them both and assign it to third date control in typescript. but i gives me error here is my code: </p>
<pre><code>activeFrom: Date;
activeNoDays: number;
//UpdateExpiry Function is called by textbox event
updateExpiry=():void =>{
this.gDetailDS = this.gDetailForm.value;
console.log("Expiry days:"+this.gDetailDS.activeNoDays);
console.log (this.addDays(this.gDetailDS.activeFrom,this.gDetailDS.activeNoDays))
}
addDays(date: Date, days: number): Date {
console.log('adding ' + days + ' days');
console.log(date);
date.setDate(date.getDate() + days);
console.log(date);
return date;
}
</code></pre>
<p>Here is HTML Controls:</p>
<pre><code><input
id="txtActivateFrom"
type ="date"
min="rdMinDate"
formControlName="activeFrom"
class="form-control"
value="{{ this.gDetailDS.activeFrom | date:'yyyy-MM-dd' }}"
displayFormat="yyyy-MM-dd"
useValueAsDate />
<input type="number"
formControlName="activeNoDays" class="form-control"
(change)="updateExpiry()"/>
</code></pre>
<p>console Messages:</p>
<pre><code>Expiry days:25
adding 25 days
2019-07-12
</code></pre>
<p>I have tried everthing but still getting this issue : </p>
<blockquote>
<p>ERROR TypeError: date.getDate is not a function</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/p6AmD.png" rel="noreferrer">link: screenshot of error appear on browser console</a></p> | 57,007,983 | 2 | 4 | null | 2019-07-12 13:14:38.74 UTC | 2 | 2019-07-12 14:34:24.727 UTC | 2019-07-12 13:31:31.013 UTC | null | 10,064,963 | null | 10,064,963 | null | 1 | 11 | angular|typescript|date|datetime | 53,158 | <p>I once had a similar problem when getting dates from a web API. I solved it by creating a new Date object.</p>
<p>So your function call could look like this:</p>
<pre><code>this.addDays(new Date(this.gDetailDS.activeFrom),this.gDetailDS.activeNoDays)
</code></pre> |
18,777,433 | making simple Calculator using netbeans | <p>i am making a simple calculator using Net beans but there is a problem in between Button and text field .
i want that thing where i click button "1" after clicking one it supposed to show one but nothing showing and please help how to setup "+" button in between them help please.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/</p>
<pre><code>/**
*
* @author Administrator
*/
public class Calculator extends javax.swing.JFrame {
/**
* Creates new form Calculator
*/
public Calculator() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton12 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jButton11 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jButton8 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton13 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Rajendra Calculator", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.ABOVE_TOP));
jButton12.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton12.setText("=");
jButton10.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton10.setText("0");
jButton11.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton11.setText("+");
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
jButton9.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton9.setText("9");
jButton1.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton1.setText("1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextField1.setText("0");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jButton8.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton8.setText("8");
jButton5.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton5.setText("5");
jButton4.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton4.setText("4");
jButton4.setToolTipText("");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton2.setText("2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton7.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton7.setText("7");
jButton6.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton6.setText("6");
jButton13.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton13.setText("Clear");
jButton3.setFont(new java.awt.Font("Arial Black", 0, 11)); // NOI18N
jButton3.setText("3");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton6))
.addComponent(jTextField1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton9)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton11, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE)
.addComponent(jButton10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton13, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton4)
.addComponent(jButton5)
.addComponent(jButton6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton7)
.addComponent(jButton8)
.addComponent(jButton9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton10)
.addComponent(jButton13))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton11)
.addComponent(jButton12))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(18, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"1");
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"2"); // TODO add your handling code here:
}
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {
int valA = Integer.parseInt(jTextField1.getText());
int valB = Integer.parseInt(jTextField1.getText()); // TODO add your handling code here:
int valC = valA+valB;
jTextField1.append(Integer.toString(valC));
jTextField1.append("\n"); // TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Calculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Calculator().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
</code></pre> | 18,778,250 | 2 | 2 | null | 2013-09-13 02:41:44.72 UTC | null | 2013-09-13 04:19:19.573 UTC | 2013-09-13 02:47:11.013 UTC | user2674280 | null | user2674280 | null | null | 1 | 0 | java|swing|netbeans|jbutton | 41,616 | <blockquote>
<p>...How to set up JButton ..where i press it and it shows "1" on textField</p>
</blockquote>
<p>Typically, in cases like this the text field would be non-editable so you can effectively "append" text to the text field by using:</p>
<pre><code>textField.replaceSelection("1");
</code></pre>
<p>However, the better approach is to share an Action for all the buttons:</p>
<pre><code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ButtonCalculator extends JPanel
{
private JButton[] buttons;
private JTextField display;
public ButtonCalculator()
{
Action numberAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
display.replaceSelection(e.getActionCommand());
}
};
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
buttons = new JButton[10];
for (int i = 0; i < buttons.length; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( numberAction );
buttons[i] = button;
buttonPanel.add( button );
// Support Key Bindings
KeyStroke pressed = KeyStroke.getKeyStroke(text);
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(pressed, text);
button.getActionMap().put(text, numberAction);
}
setLayout( new BorderLayout() );
add(display, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.SOUTH);
}
private static void createAndShowUI()
{
UIManager.put("Button.margin", new Insets(5, 10, 5, 10) );
JFrame frame = new JFrame("Button Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new ButtonCalculator() );
frame.setResizable( false );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
</code></pre> |
5,017,454 | Make IE cache the resources but always revalidate | <p>The cache control header "no-cache, must-revalidate, private" allows browsers to cache the resource but forces a revalidate with conditional requests. This works as expected in FF, Safari, and Chrome.</p>
<p>However, IE7+8 does not send a conditional request, that is, "If-Modified-Since" is missing in the request header and hence the server responds with HTTP/200 instead of HTTP/304.</p>
<p>Here are the full server response headers:</p>
<pre><code>Last-Modified: Wed, 16 Feb 2011 13:52:26 GMT
Content-type: text/html;charset=utf-8
Content-Length: 10835
Date: Wed, 16 Feb 2011 13:52:26 GMT
Connection: keep-alive
Cache-Control: no-cache, must-revalidate, private
</code></pre>
<p>This seems like an IE bug, but I haven't found anything related on the web, so I wonder whether maybe the absence or existence of another header makes IE behave strangely?</p>
<p>A good discussion of the difference between no-cache and max-age: <a href="https://stackoverflow.com/questions/1046966/whats-the-difference-between-cache-control-max-age-0-and-no-cache">What's the difference between Cache-Control: max-age=0 and no-cache?</a></p> | 5,084,395 | 2 | 2 | null | 2011-02-16 14:11:40.05 UTC | 30 | 2019-08-28 16:15:46.293 UTC | 2019-08-28 16:15:46.293 UTC | null | 823,282 | null | 389,442 | null | 1 | 43 | internet-explorer|http-headers|browser-cache|cache-control | 50,563 | <p>I've eventually figured it out. Here is an explanation and a tested solution.</p>
<p>The following site confirms my observation: <a href="http://blog.httpwatch.com/2008/10/15/two-important-differences-between-firefox-and-ie-caching/" rel="noreferrer">http://blog.httpwatch.com/2008/10/15/two-important-differences-between-firefox-and-ie-caching/</a></p>
<p>It says that IE does not locally store pages with the 'no-cache' directive and hence always sends an unconditional request.</p>
<p>There's also a MS support article - <a href="https://support.microsoft.com/help/234067/" rel="noreferrer">https://support.microsoft.com/help/234067/</a> - which confirms this:</p>
<p>"Internet Explorer supports the HTTP 1.1 Cache-Control header, which prevents all caching of a particular Web resource when the no-cache value is specified..."</p>
<p>This behavior is not entirely wrong -- but it is not what RFC 2616 (sec. 14.9.1) intended. About 'no-cache' it says "... a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server." So the response CAN be cached but MUST revalidate it. The major browsers, except for IE, do cache the response and revalidate it. To prevent storing the request, there's the 'no-store' Cache-Control directive.</p>
<p><em>In summary, IE treats 'no-cache' as 'no-store'.</em></p>
<p>And here's the <strong>solution to enable conditional requests for IE and the other browsers</strong> in a consistent way: </p>
<p>Don't use no-cache, but instead set the Expires header to the past (or -1, which has the same effect). IE, as well as the other major browsers, will then send conditional requests. (Note, you should also be aware of the IE Vary header bug, which prevents caching.)</p>
<p>These are the critical header fields:</p>
<pre><code>Last-Modified: Wed, 16 Feb 2011 13:52:26 GMT
Expires: -1
Cache-Control: must-revalidate, private
</code></pre>
<ul>
<li>Last-Modified (or ETag) is needed as a validator</li>
<li>Expires -1 tells that the resource is stale and must be revalidated</li>
<li>Cache-Control must not include no-cache or no-store</li>
</ul> |
5,406,935 | Why does reading into a string buffer with scanf work both with and without the ampersand (&)? | <p>I'm a little bit confused about something. I was under the impression that the correct way of reading a C string with <code>scanf()</code> went along the lines of</p>
<p>(never mind the possible buffer overflow, it's just a simple example)</p>
<pre><code>char string[256];
scanf( "%s" , string );
</code></pre>
<p>However, the following seems to work too,</p>
<pre><code>scanf( "%s" , &string );
</code></pre>
<p>Is this just my compiler (gcc), pure luck, or something else?</p> | 5,407,121 | 2 | 4 | null | 2011-03-23 14:40:55.353 UTC | 67 | 2021-12-26 20:44:18.307 UTC | 2021-12-26 20:44:18.307 UTC | null | 3,840,170 | null | 376,597 | null | 1 | 166 | c|scanf | 637,382 | <p>An array "decays" into a pointer to its first element, so <code>scanf("%s", string)</code> is equivalent to <code>scanf("%s", &string[0])</code>. On the other hand, <code>scanf("%s", &string)</code> passes a pointer-to-<code>char[256]</code>, but it points to the same place.</p>
<p>Then <code>scanf</code>, when processing the tail of its argument list, will try to pull out a <code>char *</code>. That's the Right Thing when you've passed in <code>string</code> or <code>&string[0]</code>, but when you've passed in <code>&string</code> you're depending on something that the language standard doesn't guarantee, namely that the pointers <code>&string</code> and <code>&string[0]</code> -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.</p>
<p>I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I <em>think</em> the C implementation on the Symbolics "Lisp Machines" did something like this.)</p> |
545,730 | Tool (or combination of tools) for reproducible environments in Python | <p>I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. </p>
<p>I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.</p> | 545,912 | 7 | 0 | null | 2009-02-13 12:20:56.13 UTC | 17 | 2010-05-14 00:53:17.21 UTC | 2009-03-26 14:21:50.65 UTC | Sam | 48,721 | Sam | 48,721 | null | 1 | 9 | python|continuous-integration|installation|development-environment|automated-deploy | 1,539 | <ol>
<li><p><a href="http://pypi.python.org/pypi/virtualenv" rel="noreferrer">virtualenv</a> to create a contained virtual environment (prevent different versions of Python or Python packages from stomping on each other). There is increasing buzz from people moving to this tool. The author is the same as the older working-env.py mentioned by Aaron.</p></li>
<li><p><a href="http://pypi.python.org/pypi/pip" rel="noreferrer">pip</a> to install packages inside a virtualenv. The traditional is easy_install as answered by S. Lott, but pip works better with virtualenv. easy_install still has features not found in pip though.</p></li>
<li><p><a href="http://www.scons.org/" rel="noreferrer">scons</a> as a build tool, although you won't need this if you stay purely Python.</p></li>
<li><p><a href="http://pypi.python.org/pypi/Fabric/0.0.3" rel="noreferrer">Fabric</a> paste, or <a href="http://www.blueskyonmars.com/projects/paver/" rel="noreferrer">paver</a> for deployment.</p></li>
<li><p><a href="http://buildbot.net/trac" rel="noreferrer">buildbot</a> for continuous integration.</p></li>
<li><p>Bazaar, mercurial, or git for version control.</p></li>
<li><p><a href="http://somethingaboutorange.com/mrl/projects/nose/" rel="noreferrer">Nose</a> as an extension for unit testing.</p></li>
<li><p><a href="http://pypi.python.org/pypi/PyFIT/0.8a2" rel="noreferrer">PyFit</a> for <a href="http://fit.c2.com" rel="noreferrer">FIT</a> testing.</p></li>
</ol> |
820,795 | Visual Studio or Resharper functionality for placement of using directives | <p>I like to put my using directives inside the current namespace, and not outside as VS and Resharper per default puts them.</p>
<p>Does anyone know of a macro/standard functionality that sorts/removes unused using directives and puts them <em>inside</em> the current namespace?</p> | 825,256 | 7 | 0 | null | 2009-05-04 16:25:10.03 UTC | 13 | 2020-10-16 06:09:03.693 UTC | 2012-09-11 13:56:40.763 UTC | null | 39,709 | null | 2,732 | null | 1 | 123 | visual-studio|resharper|using-directives | 32,271 | <p><strong>UPDATE - ReSharper 2016.1</strong>: This option is now moved to <em>Code Editing → C# → Code Style → Add 'using' directive to the deepest scope</em></p>
<p>Have you tried the ReSharper option:</p>
<p><em>Languages → C# → Formatting Style → Namespace Imports → Add using directive to the deepest scope</em></p>
<p>I'm not sure whether R#'s code cleanup will reorder the existing ones for you though.</p> |
821,818 | Is there a way to hide the scroll indicators in a UIScrollView? | <p>I've got a use case where those indicators disturb the user interaction. Can I subclass and override a method or do something similar to remove the scroll indicators from the scroll view?</p> | 822,118 | 7 | 0 | null | 2009-05-04 20:14:24.8 UTC | 18 | 2020-06-25 13:26:44.91 UTC | 2018-02-15 06:59:18.583 UTC | null | 1,402,846 | null | 62,553 | null | 1 | 147 | ios|uiscrollview | 91,075 | <p>Set the <code>showsHorizontalScrollIndicator</code> and <code>showsVerticalScrollIndicator</code> properties of the <code>UIScrollView</code> to <code>NO</code>.</p>
<pre><code>[tableView setShowsHorizontalScrollIndicator:NO];
[tableView setShowsVerticalScrollIndicator:NO];
</code></pre>
<p><a href="https://developer.apple.com/documentation/uikit/uiscrollview?language=objc" rel="noreferrer">Documentation - UIScrollView</a></p> |
760,904 | How can I monitor a Windows directory for changes? | <p>When a change is made within a directory on a Windows system, I need a program to be notified immediately of the change.</p>
<p>Is there some way of executing a program when a change occurs?</p>
<p>I'm not a C/C++/.NET programmer, so if I could set up something so that the change could trigger a batch file then that would be ideal.</p> | 760,933 | 8 | 1 | null | 2009-04-17 15:32:11.093 UTC | 18 | 2021-04-26 17:28:50.067 UTC | null | null | null | null | 18,333 | null | 1 | 36 | windows|directory|monitoring | 62,736 | <p>Use a <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" rel="nofollow noreferrer">FileSystemWatcher</a> like below to create a WatcherCreated Event().</p>
<p>I used this to create a Windows Service that watches a Network folder and then emails a specified group on arrival of new files.</p>
<pre><code> // Declare a new FILESYSTEMWATCHER
protected FileSystemWatcher watcher;
string pathToFolder = @"YourDesired Path Here";
// Initialize the New FILESYSTEMWATCHER
watcher = new FileSystemWatcher {Path = pathToFolder, IncludeSubdirectories = true, Filter = "*.*"};
watcher.EnableRaisingEvents = true;
watcher.Created += new FileSystemEventHandler(WatcherCreated);
void WatcherCreated(object source , FileSystemEventArgs e)
{
//Code goes here for when a new file is detected
}
</code></pre> |
180 | Function for creating color wheels | <p>This is something I've pseudo-solved many times and have never quite found a solution for.</p>
<p>The problem is to come up with a way to generate <code>N</code> colors, that are as distinguishable as possible where <code>N</code> is a parameter.</p> | 539 | 8 | 1 | null | 2008-08-01 18:42:19.343 UTC | 24 | 2020-07-05 21:49:16.857 UTC | 2018-05-30 13:53:46.533 UTC | null | 5,321,363 | null | 2,089,740 | null | 1 | 72 | algorithm|language-agnostic|colors|color-space | 18,757 | <p>My first thought on this is "how to generate N vectors in a space that maximize distance from each other."</p>
<p>You can see that the RGB (or any other scale you use that forms a basis in color space) are just vectors. Take a look at <a href="http://mathworld.wolfram.com/topics/RandomPointPicking.html" rel="noreferrer">Random Point Picking</a>. Once you have a set of vectors that are maximized apart, you can save them in a hash table or something for later, and just perform random rotations on them to get all the colors you desire that are maximally apart from each other!</p>
<p>Thinking about this problem more, it would be better to map the colors in a linear manner, possibly (0,0,0) → (255,255,255) lexicographically, and then distribute them evenly.</p>
<p>I really don't know how well this will work, but it should since, let us say:</p>
<pre><code>n = 10
</code></pre>
<p>we know we have 16777216 colors (256^3).</p>
<p>We can use <a href="https://stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data#794">Buckles Algorithm 515</a> to find the lexicographically indexed color.<img src="https://i.stack.imgur.com/gEuCs.gif" alt="\frac {\binom {256^3} {3}} {n} * i">. You'll probably have to edit the algorithm to avoid overflow and probably add some minor speed improvements.</p> |
138,043 | Find the next TCP port in .NET | <p>I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port.</p>
<p>I know that TcpClient will assign a new client side port when I open a connection to a given server.</p>
<p>Is there a simple way to find the next open TCP port in .NET?</p>
<p>I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.</p> | 150,974 | 8 | 1 | null | 2008-09-26 06:33:50.9 UTC | 25 | 2019-11-18 23:37:54.797 UTC | 2019-04-09 19:25:44.737 UTC | TheSeeker | 63,550 | TheSeeker | 4,829 | null | 1 | 80 | c#|.net|wcf|networking|tcp | 47,224 | <p>Here is what I was looking for:</p>
<pre><code>static int FreeTcpPort()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
</code></pre> |
119,432 | Logging Clientside JavaScript Errors on Server | <p>Im running a ASP.NET Site where I have problems to find some JavaScript Errors just with manual testing.</p>
<p>Is there a possibility to catch all JavaScript Errors on the Clientside and log them on the Server i.e. in the EventLog (via Webservice or something like that)?</p> | 119,510 | 8 | 4 | null | 2008-09-23 06:43:11.747 UTC | 44 | 2019-05-16 07:47:18.657 UTC | 2012-09-27 17:54:18.73 UTC | Sergio Acosta | 20,774 | MADMap | 17,558 | null | 1 | 104 | javascript|logging|error-handling | 54,526 | <p>You could try setting up your own handler for the <a href="http://developer.mozilla.org/En/DOM:window.onerror" rel="noreferrer">onerror event</a> and use XMLHttpRequest to tell the server what went wrong, however since it's not part of any specification, <a href="http://www.quirksmode.org/dom/events/error.html" rel="noreferrer">support is somewhat flaky</a>.</p>
<p>Here's an example from <a href="http://www.the-art-of-web.com/javascript/ajax-onerror/" rel="noreferrer">Using XMLHttpRequest to log JavaScript errors</a>:</p>
<pre><code>window.onerror = function(msg, url, line)
{
var req = new XMLHttpRequest();
var params = "msg=" + encodeURIComponent(msg) + '&amp;url=' + encodeURIComponent(url) + "&amp;line=" + line;
req.open("POST", "/scripts/logerror.php");
req.send(params);
};
</code></pre> |
333,889 | Why have header files and .cpp files? | <p>Why does C++ have header files and .cpp files?</p> | 333,902 | 9 | 5 | 2008-12-02 13:18:06.26 UTC | 2008-12-02 13:17:55.403 UTC | 243 | 2020-12-23 05:58:08.863 UTC | 2017-05-28 16:58:49.1 UTC | unwind | 3,980,929 | Clueless | null | null | 1 | 539 | c++|header-files | 325,812 | <p>Well, the main reason would be for separating the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.</p>
<p>This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times and also the amount of recompilation needed when something in the implementation changes.</p>
<p>It's not perfect, and you would usually resort to techniques like the <a href="http://aszt.inf.elte.hu/~gsd/halado_cpp/ch09s03.html" rel="noreferrer">Pimpl Idiom</a> to properly separate interface and implementation, but it's a good start.</p> |
1,276,237 | How to prevent decompilation of any C# application | <p>We are planning to develop a client server application using C# and MySQL. We plan to sell the product on the shelf like any other software utility. We are worried about the decompilation of our product which does have some sort of edge over our competitors in terms of usability and bundled functionality.</p>
<p>How can we prevent our software from decompilation, so the business logic of the product remains intact?</p>
<p>We have heard about Reflector and other decompilers which makes our code very much vulnerable for copying.</p>
<p>Our customer base is not Corporates but medical practitioners who themselves may not do it but our competitors may want to copy/disable licensing or even replicate the code/functionality so the value of our product goes down in the market.</p>
<p>Any suggestion to prevent this is most welcome.</p> | 1,283,968 | 10 | 2 | null | 2009-08-14 05:44:54.553 UTC | 13 | 2018-07-14 02:40:18.177 UTC | 2018-07-14 02:40:18.177 UTC | null | 5,198,140 | null | 156,272 | null | 1 | 33 | c#|licensing|obfuscation|decompiling|piracy-prevention | 51,578 | <p>If you deploy .NET assemblies to your client machines, some kind of decompilation will always be possible using reflector and similar tools.</p>
<p>However, this situation isn't materially different to what you'd encounter if you wrote the application in native C++. It is always possible to decompile things - if it were impossible, the processor couldn't understand it either.</p>
<p>You're never going to defeat the expert cracker - they'll treat your security as an intellectual puzzle to be solved for the challenge alone.</p>
<p>The question revolves around how hard it is to defeat your licensing practices and the <em>return on investment</em>.</p>
<p>Sit down with a spreadsheet and look through the possible scenarios - the danger is probably less than you think. </p>
<p>Factors like "ease of use" are visible in your software for any user to observe - so you'd think it easy to copy. But, good User experience is rare (and seldom copied well), because most developers (myself included) are nothing like typical users.</p>
<p>I'd suggest you concentrate on making the job of a cracker harder, cause you can never make it impossible, just non-profitable. </p>
<p>One possibility to try: It's possible to pre-compile assemblies into native code as a part of the installation process. Paint.NET does this for performance reasons. I believe that once you've done this, you can discard the original assemblies and use the optimised, native code editions. </p> |
598,933 | How do I change the default "www.example.com" domain for testing in rails? | <p>I have a rails application which acts differently depending on what domain it's accessed at (for example www.myapp.com will invoke differently to user.myapp.com). In production use this all works fine but my test code always sees a hostname of "www.example.com".</p>
<p>Is there a clean way of having a test specify the hostname it's pretending to access?</p> | 599,123 | 10 | 0 | null | 2009-03-01 00:05:41.81 UTC | 9 | 2022-04-12 23:44:22.287 UTC | null | null | null | Denis Hennessy | 35,958 | null | 1 | 73 | ruby-on-rails|rspec | 41,226 | <pre><code>@request.host = 'user.myapp.com'
</code></pre> |
1,216,114 | How can I make a div stick to the top of the screen once it's been scrolled to? | <p>I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place and scrolls with the page.</p> | 1,216,130 | 22 | 6 | null | 2009-08-01 07:54:31.58 UTC | 192 | 2022-02-11 16:19:54.677 UTC | 2019-05-14 21:56:34.037 UTC | null | 1,582,182 | null | 148,883 | null | 1 | 389 | javascript|jquery|css|scroll|positioning | 634,911 | <p>You could use simply css, positioning your element as <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/position" rel="noreferrer">fixed</a>:</p>
<pre><code>.fixedElement {
background-color: #c0c0c0;
position:fixed;
top:0;
width:100%;
z-index:100;
}
</code></pre>
<p><strong>Edit:</strong> You should have the element with position absolute, once the scroll offset has reached the element, it should be changed to fixed, and the top position should be set to zero.</p>
<p>You can detect the top scroll offset of the document with the <a href="http://docs.jquery.com/CSS/scrollTop" rel="noreferrer">scrollTop</a> function:</p>
<pre><code>$(window).scroll(function(e){
var $el = $('.fixedElement');
var isPositionFixed = ($el.css('position') == 'fixed');
if ($(this).scrollTop() > 200 && !isPositionFixed){
$el.css({'position': 'fixed', 'top': '0px'});
}
if ($(this).scrollTop() < 200 && isPositionFixed){
$el.css({'position': 'static', 'top': '0px'});
}
});
</code></pre>
<p>When the scroll offset reached 200, the element will <em>stick</em> to the top of the browser window, because is placed as fixed.</p> |
295,135 | Turn a string into a valid filename? | <p>I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.</p>
<p>I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like <code>"_-.() "</code>. What's the most elegant solution?</p>
<p>The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.</p> | 295,466 | 26 | 4 | null | 2008-11-17 09:02:07.683 UTC | 94 | 2022-06-17 17:57:53.397 UTC | 2016-11-28 02:18:47.987 UTC | Imran | 355,230 | Sophie | 37,134 | null | 1 | 387 | python|filenames|slug|sanitize | 241,169 | <p>You can look at the <a href="http://www.djangoproject.com" rel="noreferrer">Django framework</a> for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly.</p>
<p>The Django text utils define a function, <a href="https://docs.djangoproject.com/en/4.0/ref/utils/#django.utils.text.slugify" rel="noreferrer"><code>slugify()</code></a>, that's probably the gold standard for this kind of thing. Essentially, their code is the following.</p>
<pre><code>import unicodedata
import re
def slugify(value, allow_unicode=False):
"""
Taken from https://github.com/django/django/blob/master/django/utils/text.py
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
underscores, or hyphens. Convert to lowercase. Also strip leading and
trailing whitespace, dashes, and underscores.
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize('NFKC', value)
else:
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value.lower())
return re.sub(r'[-\s]+', '-', value).strip('-_')
</code></pre>
<p>And the older version:</p>
<pre><code>def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
value = unicode(re.sub('[-\s]+', '-', value))
# ...
return value
</code></pre>
<p>There's more, but I left it out, since it doesn't address slugification, but escaping.</p> |
572,768 | Styling an input type="file" button | <p>How do you style an input <code>type="file"</code> button?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" /></code></pre>
</div>
</div>
</p> | 714,626 | 46 | 3 | null | 2009-02-21 10:36:49.02 UTC | 314 | 2022-09-01 06:14:53.41 UTC | 2021-09-09 02:02:30.033 UTC | null | 4,076,315 | Shivanand | 34,642 | null | 1 | 986 | html|css | 1,577,544 | <p>Styling file inputs are notoriously difficult, as most browsers will not change the appearance from either CSS or javascript.</p>
<p>Even the size of the input will not respond to the likes of:</p>
<pre><code><input type="file" style="width:200px">
</code></pre>
<p>Instead, you will need to use the size attribute:</p>
<pre><code><input type="file" size="60" />
</code></pre>
<p>For any styling more sophisticated than that (e.g. changing the look of the browse button) you will need to look at the tricksy approach of overlaying a styled button and input box on top of the native file input. The article already mentioned by rm at <a href="http://www.quirksmode.org/dom/inputfile.html" rel="noreferrer">www.quirksmode.org/dom/inputfile.html</a> is the best one I've seen.</p>
<p><strong>UPDATE</strong></p>
<p>Although it's difficult to style an <code><input></code> tag directly, this is easily possible with the help of a <code><label></code> tag. See answer below from @JoshCrozier: <a href="https://stackoverflow.com/a/25825731/10128619">https://stackoverflow.com/a/25825731/10128619</a></p> |
34,855,049 | Using HMAC SHA256 in Ruby | <p>I'm trying to apply HMAC-SHA256 for generate a key for an Rest API.</p>
<p>I'm doing something like this:</p>
<pre><code>def generateTransactionHash(stringToHash)
key = '123'
data = 'stringToHash'
digest = OpenSSL::Digest.new('sha256')
hmac = OpenSSL::HMAC.digest(digest, key, data)
puts hmac
end
</code></pre>
<p>The output of this is always this: (if I put '12345' as parameter or 'HUSYED815X', I do get the same)</p>
<pre><code>ۯw/{o���p�T����:��a�h��E|q
</code></pre>
<p>The API is not working because of this... Can some one help me with that?</p> | 34,877,237 | 3 | 5 | null | 2016-01-18 12:41:03.09 UTC | 6 | 2019-07-30 16:01:32.407 UTC | null | null | null | null | 4,897,880 | null | 1 | 28 | ruby-on-rails|ruby|sha256|hmac | 22,680 | <p>According to the documentation <a href="https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/HMAC.html#method-i-digest" rel="noreferrer"><code>OpenSSL::HMAC.digest</code></a></p>
<blockquote>
<p>Returns the authentication code an instance represents as a binary string.</p>
</blockquote>
<p>If you have a problem using that maybe you need a hex encoded form provided by <code>OpenSSL::HMAC.hexdigest</code></p>
<p>Example</p>
<pre><code>key = 'key'
data = 'The quick brown fox jumps over the lazy dog'
digest = OpenSSL::Digest.new('sha256')
OpenSSL::HMAC.digest(digest, key, data)
#=> "\xF7\xBC\x83\xF40S\x84$\xB12\x98\xE6\xAAo\xB1C\xEFMY\xA1IF\x17Y\x97G\x9D\xBC-\x1A<\xD8"
OpenSSL::HMAC.hexdigest(digest, key, data)
#=> "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
</code></pre> |
6,538,485 | Java using AES 256 and 128 Symmetric-key encryption | <p>I am new in cipher technology. I found this code to do Symmetric Encryption.</p>
<pre><code>byte[] key = //... secret sequence of bytes
byte[] dataToSend = ...
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedData = c.doFinal(dataToSend);
</code></pre>
<p>Its working. Here I can use my own password. And thats what exactly I needed. But I dont know how to do 128 or 256 Symmetric Enctryption.
How can I use 128 and 256 key into my code ?</p> | 6,538,834 | 5 | 4 | null | 2011-06-30 17:09:53.333 UTC | 16 | 2018-02-05 16:22:51.113 UTC | 2011-06-30 17:34:33.3 UTC | null | 823,496 | null | 823,496 | null | 1 | 15 | java|aes|encryption | 71,984 | <p>Whether AES uses 128 or 256 bit mode depends on size of your key, which must be 128 or 256 bits long. Typically you don't use your password as a key, because passwords rarely have exact length as you need. Instead, you derive encryption key from your password by using some key derivation function.</p>
<p><strike>Very simple example: take MD5 of your password to get 128-bit key.</strike> If you want 256-bit key, you can use SHA-256 to get 256-bit hash of your password. Key-derivation functions usually run this hashing several hundreds time and use extra salt as well. Check out <a href="http://en.wikipedia.org/wiki/Key_derivation_function" rel="noreferrer">http://en.wikipedia.org/wiki/Key_derivation_function</a> for details.</p>
<p>Also note: to run encryption stronger than 128-bit you will need to download and install 'Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6' from <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" rel="noreferrer">http://www.oracle.com/technetwork/java/javase/downloads/index.html</a>.</p> |
6,997,190 | What the difference between Eclipse 3.7, 3.8 and 4.2? | <p>Eclipse Indigo is 3.7, and Eclipse Juno is 4.2, but 3.8M1 has just been released. What's 3.8 and how is this different from 3.7? I'm eagerly awaiting Java 7 support and am confused whether I should use 3.8M1 or wait for 3.7.1</p> | 6,997,266 | 5 | 1 | null | 2011-08-09 13:48:34.163 UTC | 10 | 2012-09-24 17:46:12.747 UTC | 2012-09-12 05:01:10.047 UTC | null | 255,961 | null | 44,330 | null | 1 | 30 | java|eclipse|eclipse-indigo|eclipse-juno | 30,056 | <blockquote>
<p>...the feature and API set for the next feature release of the Eclipse
SDK after 3.7, designated release 4.2 and code-named Juno. This
release is occurring simultaneously with the 3.8 platform release. The
4.2 release is a mature platform release containing significant new
feature work, while the 3.8 release focuses on stability and bug
fixes.</p>
</blockquote>
<p>From: <a href="http://www.eclipse.org/projects/project-plan.php?projectid=eclipse" rel="noreferrer">http://www.eclipse.org/projects/project-plan.php?projectid=eclipse</a></p>
<p>Also, Java 7 support began with 3.7.1:</p>
<p><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=288548" rel="noreferrer">https://bugs.eclipse.org/bugs/show_bug.cgi?id=288548</a></p> |
6,621,785 | POSIX pthread programming | <p>I have to code a multithreaded(say 2 threads) program where each of these threads do a different task. Also, these threads must keep running infinitely in the background once started. Here is what I have done. Can somebody please give me some feedback if the method is good and if you see some problems. Also, I would like to know how to shut the threads in a systematic way once I terminate the execution say with Ctrl+C.</p>
<p>The main function creates two threads and let them run infinitely as below.</p>
<p>Here is the skeleton:</p>
<pre><code>void *func1();
void *func2();
int main(int argc, char *argv[])
{
pthread_t th1,th2;
pthread_create(&th1, NULL, func1, NULL);
pthread_create(&th2, NULL, func2, NULL);
fflush (stdout);
for(;;){
}
exit(0); //never reached
}
void *func1()
{
while(1){
//do something
}
}
void *func2()
{
while(1){
//do something
}
}
</code></pre>
<p>Thanks.</p>
<p><strong>Edited code using inputs from the answers:</strong>
Am I exiting the threads properly?</p>
<pre><code>#include <stdlib.h> /* exit() */
#include <stdio.h> /* standard in and output*/
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <signal.h>
#include <semaphore.h>
sem_t end;
void *func1();
void *func2();
void ThreadTermHandler(int signo){
if (signo == SIGINT) {
printf("Ctrl+C detected !!! \n");
sem_post(&end);
}
}
void *func1()
{
int value;
for(;;){
sem_getvalue(&end, &value);
while(!value){
printf("in thread 1 \n");
}
}
return 0;
}
void *func2()
{
int value;
for(;;){
sem_getvalue(&end, &value);
while(!value){
printf("value = %d\n", value);
}
}
return 0;
}
int main(int argc, char *argv[])
{
sem_init(&end, 0, 0);
pthread_t th1,th2;
int value = -2;
pthread_create(&th1, NULL, func1, NULL);
pthread_create(&th2, NULL, func2, NULL);
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = ThreadTermHandler;
// Establish a handler to catch CTRL+c and use it for exiting.
if (sigaction(SIGINT, &sa, NULL) == -1) {
perror("sigaction for Thread Termination failed");
exit( EXIT_FAILURE );
}
/* Wait for SIGINT. */
while (sem_wait(&end)!=0){}
//{
printf("Terminating Threads.. \n");
sem_post(&end);
sem_getvalue(&end, &value);
/* SIGINT received, cancel threads. */
pthread_cancel(th1);
pthread_cancel(th2);
/* Join threads. */
pthread_join(th1, NULL);
pthread_join(th2, NULL);
//}
exit(0);
}
</code></pre> | 6,959,876 | 7 | 3 | null | 2011-07-08 08:17:57.97 UTC | 11 | 2012-05-28 17:43:25.947 UTC | 2011-07-14 14:08:03.57 UTC | null | 489,152 | null | 489,152 | null | 1 | 11 | c|pthreads|posix | 17,191 | <p>There are mainly two approaches for thread termination.</p>
<ul>
<li><strong>Use a cancellation point.</strong> The thread will terminate when requested to cancel <em>and</em> it reaches a cancellation point, thus ending execution in a controlled fashion;</li>
<li><strong>Use a signal.</strong> Have the threads install a signal handler which provides a mechanism for termination (setting a flag and reacting to <code>EINTR</code>).</li>
</ul>
<p>Both approaches has caveats. Refer to <a href="https://stackoverflow.com/questions/2084830/kill-thread-in-pthread/6560246#6560246">Kill Thread in Pthread Library</a> for more details.</p>
<p>In your case, it seems a good opportunity to use cancellation points. I will work with a commented example. The error-checking has been omitted for clarity.</p>
<pre><code>#define _POSIX_C_SOURCE 200809L
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void sigint(int signo) {
(void)signo;
}
void *thread(void *argument) {
(void)argument;
for (;;) {
// Do something useful.
printf("Thread %u running.\n", *(unsigned int*)argument);
// sleep() is a cancellation point in this example.
sleep(1);
}
return NULL;
}
int main(void) {
// Block the SIGINT signal. The threads will inherit the signal mask.
// This will avoid them catching SIGINT instead of this thread.
sigset_t sigset, oldset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGINT);
pthread_sigmask(SIG_BLOCK, &sigset, &oldset);
// Spawn the two threads.
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread, &(unsigned int){1});
pthread_create(&thread2, NULL, thread, &(unsigned int){2});
// Install the signal handler for SIGINT.
struct sigaction s;
s.sa_handler = sigint;
sigemptyset(&s.sa_mask);
s.sa_flags = 0;
sigaction(SIGINT, &s, NULL);
// Restore the old signal mask only for this thread.
pthread_sigmask(SIG_SETMASK, &oldset, NULL);
// Wait for SIGINT to arrive.
pause();
// Cancel both threads.
pthread_cancel(thread1);
pthread_cancel(thread2);
// Join both threads.
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// Done.
puts("Terminated.");
return EXIT_SUCCESS;
}
</code></pre>
<p>The need for blocking/unblocking signals is that if you send SIGINT to the process, any thread may be able to catch it. You do so before spawning the threads to avoid having them doing it by themselves and needing to synchronize with the parent. After the threads are created, you restore the mask and install a handler.</p>
<p>Cancellation points can be tricky if the threads allocates a lot of resources; in that case, you will have to use <code>pthread_cleanup_push()</code> and <code>pthread_cleanup_pop()</code>, which are a mess. But the approach is feasible and rather elegant if used properly.</p> |
6,384,710 | Why is a Dictionary "not ordered"? | <p>I have read this in answer to many questions on here. But what exactly does it mean?</p>
<pre><code>var test = new Dictionary<int, string>();
test.Add(0, "zero");
test.Add(1, "one");
test.Add(2, "two");
test.Add(3, "three");
Assert(test.ElementAt(2).Value == "two");
</code></pre>
<p>The above code seems to work as expected. So in what manner is a dictionary considered unordered? Under what circumstances could the above code fail? </p> | 6,384,765 | 7 | 7 | null | 2011-06-17 10:54:33.08 UTC | 4 | 2019-01-25 09:45:36.347 UTC | 2019-01-25 09:45:36.347 UTC | null | 2,940,265 | null | 207,752 | null | 1 | 47 | c#|.net|dictionary|base-class-library|operator-precedence | 13,947 | <p>Well, for one thing it's not clear whether you expect this to be <em>insertion-order</em> or <em>key-order</em>. For example, what would you expect the result to be if you wrote:</p>
<pre><code>var test = new Dictionary<int, string>();
test.Add(3, "three");
test.Add(2, "two");
test.Add(1, "one");
test.Add(0, "zero");
Console.WriteLine(test.ElementAt(0).Value);
</code></pre>
<p>Would you expect "three" or "zero"?</p>
<p>As it happens, I <em>think</em> the current implementation preserves insertion ordering so long as you never delete anything - but you <em>must not rely on this</em>. It's an implementation detail, and that could change in the future.</p>
<p>Deletions also affect this. For example, what would you expect the result of this program to be?</p>
<pre><code>using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
var test = new Dictionary<int, string>();
test.Add(3, "three");
test.Add(2, "two");
test.Add(1, "one");
test.Add(0, "zero");
test.Remove(2);
test.Add(5, "five");
foreach (var pair in test)
{
Console.WriteLine(pair.Key);
}
}
}
</code></pre>
<p>It's actually (on my box) 3, 5, 1, 0. The new entry for 5 has used the vacated entry previously used by 2. That's not going to be guaranteed either though.</p>
<p>Rehashing (when the dictionary's underlying storage needs to be expanded) could affect things... all kinds of things do.</p>
<p><strong>Just don't treat it as an ordered collection. It's not designed for that. Even if it happens to work now, you're relying on undocumented behaviour which goes against the purpose of the class.</strong></p> |
6,921,588 | Is it possible to reflect the arguments of a Javascript function? | <p>Is it possible to get all of the arguments a Javascript function <strong>is written to</strong> accept? (I know that all Javascript function arguments are "optional")? If not, is it possible to get the number of arguments? For example, in PHP, one could use:</p>
<pre><code>$class = new ReflectionClass('classNameHere');
$methods = $class->getMethods();
foreach ($methods as $method) {
print_r($method->getParameters());
}
</code></pre>
<p>... or something like that, I haven't touched PHP in a while so the example above may not be correct.</p>
<p>Thanks in advance!</p>
<p>EDIT: Unfortunately, I have to be able to get the arguments <strong>outside</strong> of the body of the function... Sorry for the lack of clarification, but thanks for the current answers!</p> | 6,921,607 | 8 | 5 | null | 2011-08-03 04:21:28.063 UTC | 9 | 2019-02-27 05:09:06.077 UTC | 2011-08-03 04:41:15.86 UTC | null | 252,042 | null | 252,042 | null | 1 | 26 | javascript|reflection|methods | 15,227 | <p>Suppose your function name is <code>foo</code></p>
<blockquote>
<p>Is it possible to get all of the arguments a Javascript function is
written to accept? </p>
</blockquote>
<p><code>arguments[0]</code> to <code>arguments[foo.length-1]</code></p>
<blockquote>
<p>If not, is it possible to get the number of arguments? </p>
</blockquote>
<p><code>foo.length</code> would work</p> |
6,817,107 | Abstract UserControl inheritance in Visual Studio designer | <pre><code>abstract class CustomControl : UserControl
{
protected abstract int DoStuff();
}
class DetailControl : CustomControl
{
protected override int DoStuff()
{
// do stuff
return result;
}
}
</code></pre>
<p>I dropped a DetailControl in a form. It renders correctly at runtime, but the designer displays an error and won't open because the base user control is abstract.</p>
<p>For the moment, I'm contemplating the following patch, which seems pretty wrong to me, as I want the child classes to be forced to implement the method.</p>
<pre><code>class CustomControl : UserControl
{
protected virtual int DoStuff()
{
throw new InvalidOperationException("This method must be overriden.");
}
}
class DetailControl : CustomControl
{
protected override int DoStuff()
{
// do stuff
return result;
}
}
</code></pre>
<p>Anyone has a better idea on how to work my way around this problem?</p> | 6,817,281 | 9 | 2 | null | 2011-07-25 13:47:16.117 UTC | 7 | 2020-01-28 16:06:33.587 UTC | 2011-08-09 19:23:18.037 UTC | user356178 | null | user356178 | null | null | 1 | 42 | c#|winforms|abstract-class|user-controls | 26,709 | <p>You can use a TypeDescriptionProviderAttribute to provide a concrete design-time implementation for your abstract base class. See <a href="http://wonkitect.wordpress.com/2008/06/20/using-visual-studio-whidbey-to-design-abstract-forms/" rel="noreferrer">http://wonkitect.wordpress.com/2008/06/20/using-visual-studio-whidbey-to-design-abstract-forms/</a> for details.</p> |
6,713,365 | ItemContainerGenerator.ContainerFromItem() returns null? | <p>I'm having a bit of weird behavior that I can't seem to work out. When I iterate through the items in my ListBox.ItemsSource property, I can't seem to get the container? I'm expecting to see a ListBoxItem returned, but I only get null.</p>
<p>Any ideas?</p>
<p>Here's the bit of code I'm using:</p>
<pre><code>this.lstResults.ItemsSource.ForEach(t =>
{
ListBoxItem lbi = this.lstResults.ItemContainerGenerator.ContainerFromItem(t) as ListBoxItem;
if (lbi != null)
{
this.AddToolTip(lbi);
}
});
</code></pre>
<p>The ItemsSource is currently set to a Dictionary and does contain a number of KVPs.</p> | 6,736,301 | 10 | 4 | null | 2011-07-15 21:31:44.53 UTC | 6 | 2016-02-01 23:43:28.683 UTC | 2012-02-17 13:11:04.1 UTC | null | 546,730 | null | 88,069 | null | 1 | 46 | wpf|listbox|containers|itemssource | 46,626 | <p>Finally sorted out the problem... By adding <code>VirtualizingStackPanel.IsVirtualizing="False"</code> into my XAML, everything now works as expected.</p>
<p>On the downside, I miss out on all the performance benefitst of the virtualization, so I changed my load routing to async and added a "spinner" into my listbox while it loads...</p> |
6,376,452 | Hide the browse button on a input type=file | <p>Is there a way to hide the browse button and only leave the text box that works in all browsers? </p>
<p>I have tried setting the margins but they show up different in each browser</p> | 6,376,555 | 11 | 1 | null | 2011-06-16 18:01:57.447 UTC | 2 | 2021-01-04 02:28:15.06 UTC | null | null | null | null | 708,908 | null | 1 | 31 | html|css | 121,358 | <p>No, what you can do is a (ugly) workaround, but largely used</p>
<ol>
<li>Create a normal input and a image</li>
<li>Create file input with opacity 0</li>
<li>When the user click on the image, you simulate a click on the file input</li>
<li>When file input change, you pass it's value to the normal input (so user can see the path)</li>
</ol>
<p>Here you can see a full explanation, along with code:</p>
<p><a href="http://www.quirksmode.org/dom/inputfile.html" rel="noreferrer">http://www.quirksmode.org/dom/inputfile.html</a></p> |
42,395,034 | How to display binary data as image in React? | <p>I am receiving a bindata from the Nodejs server and now from that I need to display an image.</p>
<p>How can I achieve this? Is there any method to convert bindata to JPEG or any other format? Or is it possible to convert that in server and then send that image to react?</p>
<p>Here's how I'm trying to display the binary data (<code>item.Image.data.data</code>) with an image tag:</p>
<pre><code><img src={item.Image.data.data} />
</code></pre>
<hr>
<p>This is my detailed react code snippet:</p>
<pre><code>componentDidMount(){
let self = this;
axios.get('http://localhost:8080/list')
.then(function(data) {
console.log(data);
self.setState({post:data.data});
});
}
<ul className="w3-ul w3-card-4 w3-light-grey">
{ this.state.post.map((item, index) => {
return (
<Link to="/displaylist" style={{ textDecoration: 'none' }} key={index}>
<li className=" w3-hover-green w3-padding-16" onClick={this.handleClick(item.Id)}>
<img src={item.Image.data.data} className="w3-left w3-circle w3-margin-right" width="60px" height="40px" />
<span>{item.Firstname}</span><br/><br/>
</li>
</Link>
)}
)}
</ul>
</code></pre>
<p>This is my nodejs code snippet:</p>
<pre><code>server.get('/list', function(req, res) {
databaseInterface.listStudent(function(err, students) {
var myJSON = students;
res.json(myJSON);
// You should see the newly saved student here
});
});
</code></pre> | 42,399,865 | 4 | 6 | null | 2017-02-22 15:00:58.14 UTC | 28 | 2021-08-12 07:08:49.813 UTC | 2019-01-16 15:17:27.263 UTC | null | 4,312,466 | null | 7,413,709 | null | 1 | 76 | javascript|node.js|reactjs | 139,913 | <p><strong>If the binary data is represented as a <em>base64</em> string</strong>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Base64 string data
const data = 'iVBORw0KGgoAAAANSUhEUgAAAFgAAABSCAYAAADQDhNSAAAABHNCSVQICAgIfAhkiAAAFN5JREFUeJztnHl0FFW+xz/VS3rLTkJ2EkICIWEzgICIw8Ao6KCo4zDKuM04bqjPJyLqoAj6VBREHcVtBnXUcUMU3BVUhFFQQJEQkwhJyJ6Qfe10ernzRzVFd9JJukOKd857+Z6Tc6qr7vKrb27d+t3f73tLSk1NFQxBNWj+tw34v44hglXGEMEqY4hglTFEsMoYIlhlDBGsMoYIVhlDBKuMIYJVhu6UdxgaTsSkGZjiRoBGg62umtZfDtFRcliV/szJaYSMHo8hKhZcLqxVpTQe2I2jpUmV/rrjlBGsMZpJ/fPtxJ27CI0+qMd1a3U5NdvepfLDN7A3N5xUX/rwSOJ/exkxZ1+MKTaxx3WXvYuqT96m6MXHcHV2nFRf/UE6FcEeXXAoEx95heBRY/st6+y0UrHlFUrfeg6nNbCb15rMjPjDDSRceCVao6nf8m2Fefx011U4WpsD6icQnBKCx61+jmHTfg2AEIKW3P005exFOJ2YEpKJmDidoMhorzq2ump+eeo+Gr7b4VcfkdNmM/qW1fJU4IYQAntjHY0/7cFaUYKk1RI+fiphWZNBkgCo/24Hh+67fnBu1AdUJzhy6q8Y/8ALAAiXk/x1d3Hsy/e7WaEhcsoskhZdR/j4KcppIQRVH79F4fMP4eqy+Wxfozcw6oa/EnfeH5DcpAkhaD60n7K3X6Bh3y4QLq86w+dcQMayNUgaLQA5K6+j4fuvB+uWvaCNiIhYpUrLbqQtuRdTfDIIQfm7L1O++UUfpQTWyhJqtr1LW2EeoZmnobOEIEkSIaPHETnlLBr27cTZ0eZVyxAdx4SHXiRq+hwkSUIIga22ioLH7qL4xXVYK0uAnuOnvbgArclCWGY2APqQ8J7/9EGCqm6a1hxM+KQZALicTsre+Ue/dep3f8G+6xdQ/fm7IGRyQtKzyH5yE8Hp45RywenjyH5yEyHpWYA8amu2vce+6xdQv/uLfvspe2cjLocDgPBJM9CagwO+P3+gKsGhYyag0cmOSkv+AexN9X7Vc1rbKVh/N/nr71amhqDIaCY9+grhp51B+GlnMOnRV5R529llo2D93RSsvxuntd2vPuxN9bTkHwBAo9MROmZCoLfnF1R108wjRinHbYdzA65fs+09OsqKGbfqGYLCh6E1WRi/+jkANEEGALqa6sldtUQhKxC0HT5E+Lgpiq2NP34bcBv9QdURHBQ5XDnuPFY5oDZa8w9wYOlldFaXAzKxx8ntrC7nwNLLBkSubFOVT1sHE+rOwSazctz9BRUIrJUlFL20vsf5opfWu19kA4OnTZ62DibUjUW43SZAeWENBObkdEbfsqrH+dG3rMKcnD7gdr1s8rR1EKEqwZ6+q9Y4sBESFBHF+AdeQBccCoCtoRZbQy0grxDHP/AC+oioAbXtOWp787NPFqoS7LkE1YdFBFxf0geRtXIDxuHxcnvtbeSs+As5K/6Co11+vI3D4xm3cgOSj/hGf9CHnrBJreWyqgTb6muUY0N0bB8lfSP9ppWEjp0EgHA6+PnBW2kvzqe9OJ+fH7wV4ZT92NCxk0i/6b6A2/e0ydPWwYSqBB9/8wPyai4AxM67hLj5vwfkRUTh82to/OHfyvXGH/5N4QtrlN9x8y8hdt4lAfVhik9R2ve0dTChKsEdZYXKsTnF/5eROSWdtCX3Au4V2vYtVLz/ao9yFVtfpXrbe8rvtCX3BthPmk9bBxOqLjTsTQ3YGmoxREajDw7DGJtEZ3VZr+X1YZEYomLIuGMtWoNRPuly4WhvYdT1f0XS6ZE08pgQLhfCYcfR3opwOpG0WrQGI5l3PU7+2juw1dX0GVc2xiahDw4DoKuxDnvTycWge4PqAffWX3IwTJ8DyHNl57EKzEmjCB41FktKOuakUZgSkjHGJKA19IzhSlotiRde5Xd/lpR0Jm/YAoDTZqWzpgJrRQkdZYW0Hz1MW2EeHWWFytx+3Ea1oHq4MmnRtaT+eRkgu1g6k0U1p95fOK0dOKztGNyxjKKN6yjb9HdV+lKFYI3RxLDpc4ieeQ4Rk89E10+kSgihxHKPo6Ugh5bc/TjaW3F2duDqsuGyd52I7UoaNPogNEEGtEYzOksIoVmTCR0zvs92fcHR0Ubj/n9T+83n1O/5ElenNfCb7gWDSnDI6PHEL7iM6Fnz0ZosPsscf2O3HcmlrSifjtIjdJQfJeH8xcQvWAyAvbmRvdedF3BuTh8WydQXPlZ87soP36Dig39hTkzBPCKd4NQxBKdlYYxN7JV4p7Wd2l2fUvnhG4MydQwKwRHZM0levISwcVN6XBNC4LJ1Kjmyo6/8jZLXN3iVsaRmMPmpzUhaHUII8tcuH3AAfPicCxi7fK3ct9PB/lt+R3tRvleZ5MU3kXLlfwFyDlBrMPpcKjcf2kfJ68/Q+MM3A7IFTjKjYUpMJfOux0i5/BZltQUyqW2FeVS8+xKHn15N6+EcomfNB0BjMFL96SavdrLufQpjTAIAjft2UfziuoGaRHtxAaFjJmJKSEbSaLCMHEP1Z5u9yqRecweGqFj5n7luOUUvPkZXXTW60AhlXgZ5lRgzdyFhmZNpKcjB0dIYsD0DHsGJF1/NyKuXKqFDAKetk5ovtlL54eteo0ZrsjDjzW/RGowIIfj+T2cr7prniHPaOtl3/W9P2uk3xiYy5fmPFFcv79E7lCfCGJvE6S9tQ5IknLZOdl96hleQ3pKaQfyCxcTMXXjCVUSOVRS/vJ7yd18OyJaAR7Ck0zN2+VqSfncNklb28lz2Liref5Wf/+dWar/+CHtjnVcd4bDLbllyGpIk4WhtpjnnezQGI+PuewadJRghBKVvPkf9t9t9G2qyEDVjLtGz5hE+4XSCwodhq61COOw9yjraWpC0OsInTgMgdPQEKj9+E+F0kLDwSiLc5+t3b+8xFdkb62j47iuqPn0HSaslOC0TSatF0uqInDwLc+JI6vd8BS5Xj3592h0QwRoNWfc8pTzucvZ2Hzn3XMuxrz7sU8ThsncxfPYCAAwxCVRsfZWk319L1Bm/AeQ0fd7DS5X4gicSLrqKcaueJWbuQsInTiN84jSizzqX+PMX47J30eoj4N5acJCYuReis4SgswTj6rLRnLufMUsfRh8cihCC4pfWYy0v9m1vZ4fsWez8BEtqhjKFWVJGYxk5htpdn/gVgg2I4JQrbyX+3EWATG7Zpr+Tv+5Ov+amzqoy4s5dhNZkQR8cirXiKCOvvg1NkAEhBEc23E/bkZ5ppfSbV5G8eInXVHQcmiADkVNmERQeRcP3O7yuCacDe3MD0TPPAeTEqe1YFXHz5XiFvbGOw0+v7pHS7w5HaxM1X2xBow8iNDMbSZIwJ6UiabQ0/bSn3/v2m2BT4kgy73oMSaNBCMHRV56k5NW/+R9IFy70oeGKpzHs9F8pC472onyOPHN/jyrDZy8g9c+399t0yOjxWMuP0n70F6/z7Ud/IWrGXIIio9EEGRh2+q+Uaa1i62s0/uindyAETT/uRricREyaDkBY5mkc2/lJvxo3v4M9CQuvUIxr3LeL0jee9beqgsqP30I4nXLH7hEphKD4n4/7/EclL17id9s+ywpB8cuPKz+VPp1OKj9+MxDTASh941nq98oCFUmrI2HhFf3W8ZvgiOyZsnFCUPLGMwEbB2CrqaBuj7dmoTX/J5+qGmNskldWuj+YR4zC6EPo17D3a1ryvOfouj1fYBtgEtZzYB3npC/4TbAxOk45bi0Y+Aqn8oPXvX6XbfItRjEMj/N5vi8YPHzxvvrobkMgaC3IQbifNmO07/484TfBTvf6XJIkdCFhAzQPgtMyvX6HZEz0Wc5l6wyoXXnF6DuG0L2PkLSsgNr2hC4kTFlmO/2QvvpNcFtRnnJ83N0KGBotCRd4z1sJ5y9GHxbZo2h7yeGAEpHC3kV7yZEe5/VhkSScv9jrXPwFl4Nb+Bcohs/+rXLsyUlv8JvgY19+oBwn//EmjDE957v+EDVjDsZuj77WZCFp0XU9yro6rRz7+iO/2z729Uc+o2BJi67rEXgyDo8jasYcv9tW6sUkkvzHmwH5ifHkpDf4TXDNF1tod8v89SFhTHhoY69zXm+IO+9S5bjxwG7lOOH8xT7bKn5pPV3dVoW+0NVYR7EPYYohOk4ZvUIIrz49bfEHhuHxTHhoI3r39NhReoSaL7b0W89vgoXTSd6a2xXVuSkhhewnN/n1JgV59RZx2hkAuBx28h9ZRtPB72UjggyMvPq2HnW6Gmo5uOIaOmurelwDd+iztoqDK66hy62V8IRnrKQ5Zy/5jyzD5V5aR5x2Bgb36qw/RGTPJPvJTZgSUgA5YJ+3ZpnicvaFgFZy9qZ6Wn45SPSZ89Do9GhNZobPuQBjbCKtBT/1KflPWHgFEW4pa/2eL6n+7B06SguJnf97JEnCkpJOw75ddHVLn9sb66j+7B1cXTb04cPQh4aBEHSUFlH5wb/IX3unT5crZMwE0m5coeiG8x6+DWt5MSFpmZiTRiFJEvbWJppz9vZqc1BkNGlLVpJ67Z3o3NOMs9PKofuX0Jrnnx5uQNG04PQssu592itE6ey0Uvnxm1S8909sPkbc1L9/gjkpFSEEufffpGh4M+5cR8yvzwegpeAgP/73or5XhxqNfL2vMpLEaU+8rUhSa776gPxH5LTVsBlzGXef7Md3lBWx99pze1Q3RMeRcNFVxJ93qRLHPi7uzn3g5oCUogNK27cdzmX/jQup3vae4hNqjSaSLv4T017eTtbKDQybPhdJpwfAMnIM5qRUQI50NezdqbRVvHGd4u6EjplA3PxFfXfucvW7PI+bv0gh19nZQfHGE/Hlhr07sbtVPOakVCwjxwBylHDY9LlkrdzAtJe3k3Txn7zIrdm+hf03LgxYhnvSGY3QrMmkXrNMkeN7wt7WQsN3X6EJMigRuOrPN1Ow/q9e5UZcej0jr14q12ltltNFfrzcfEEfESWnjULC5JjJy49T+tbzXmXGLH2I2HN+B0Dtrk9xddmInPZr9G7923EIIWjJ+5Gijetoyd0/IHtOeo+GrbaK6s8203xoP/rQCExxIxRHXBtkIDg1A0vyCYFHV2O9PC+6nPJIEoKW/INEnTmPoLBItAYjxthEand+MiB7MpatUbYVdJQVkb/uTnnUa7SYR4wicsosQjOzFaWRJTmN4NQMtB7ROuFy0bB3J4efXsXRfz7hc8rzF4OeVTbGJBLzmwsZPnsB5qSRfZZ1dXXRUVGMtbwYXXCo4mUA5D92N3XffC5nG/qL2EmSHJCfeTYZt5+QUzX++C2OthZMiSMxJ4xEE9S7QFAIgbW8mGM7PqJm+3t01lT4d8P9QFVdhDklneRLb/Ra/QQK4XLhsllxdtkQdjvCJbtGkkaLpNejDTKgMZgUxc9AcGzHR5S8+SwdRwd/O6+qyp6Oo4ext56Il1Z9uglrZSkh6VkEj8qU0+f9ECNpNGhNll5lAP5AuL2Ozupy2gp/pvVwLqb4EYq40N7apAq5cAqkU6EZbvmp+03cfGifck1jMGFOTMGUkIIxJhHD8DgMUbEMO302klar1OsPnhoH4XRS//0ObHXV2I5V0VlTjrXiKB3lR72CQWHjpigEH7dRDahKsKTTYUkZLf9wuWjt5uK4bFbaCvNoK/QOmiRffgspl9+s1MtZeT0t+QfQ6PUguUe8cOGy2wkdO4nxq59H0mrdsepnKXntqX5taz2cq4gGLSmjkXQ6hKNnPvBkoap81ZQwUiYFeSNLb+HE7ih5fYOyjJa0WjKWrUFnsmBvasDeWCf/NTWgM1nIuH2NMtqbc/b2ELX0BpfNqmyg0ej1mBL6fiEPFCoTfEJ03VFW5H9Fl4u8NUuV+EJQRBRZ921A46FT0BiMZN23gSD3/oyuhlry1iz1O50O0FF+wiZPWwcTqhLsmQXprAlMTNLVUEvug7cqwZmQ9HFkLF8rS5wkiYw71hLi3lrrctjJffBWnwGfvtBZdcImT1sHE6oSrA8fphwHevMALbn7OfL0/YofHD3zHNJuWEHaDSuIPlNOxx9P+Q9kpdXVeMImT1sHE6q+5HTmE66Vo611QG1Uffo2psQUki65BsArkyuEoHzzi1R98vaA2na0n7BJax64G9gX1N2IqD3x/3M5e0qc/EXRxrUc2/Gh1zkhBLVff0zRxrUDbtdTdiVp1RlrqhIs7CduwNd3evxvSNDRTeIkSZL8kjqJHaSee+uEvWvA7fQFdTfBeEiqgsIGOMdJEqOuu4vEi67ucSnl8lvQWULk7VwDINrTJrtKX6FSlWDPgMnxeHAg0BjNZNzxiKIvE0LQuG8XAJFTzwIg8aKrMQxPIH/t8oC/IOVp02AFd7pD1Smi7cjPynHY+KmA/xuuzUmjyH7ibS9ya3d8xKHVSzi0eonXnBw982yyn3gbc5L/SiAkyW2TWzDuYetgQt2NiKVHsNVVA2CIiiFi8pn9V5I0JCy8guynNmNxbyoUQlD61vPkPboM4bAjHHbyHllGyZvPKbEKS0o62U9tlr0Mqf/bisg+E0NUDABd9TV0lPbUVAwGVP8oki40QvmqSHB6JjXbt/oUTQOET5xO5ooniJt3CRp3usnR0U7BuuVUbu2507PpwB46ygqJmDxL3nGk0xM59SyGTZuNtbK018WN1mQh854nCXILXiref42mA/1LUQcC1ffJ6cMiOX3jZ8rnCNoK8yj8xyM05+xDuJyYYpOIyJ5JzNkXeX03RwhBa8FB8h+9o9+Pbpjik8lYvpbQbhKploKD1Gx7j8YfvsFaXYak0RI2fiqj/rJc+Uieo62F76+Zd9JfG+wNp+TDdNGz5jP27se9Yr/HY7S+4sGO9laOvvY0FVtf8T+2oNGQsPBKUi6/GZ0lpMdl4XKBJHmHNl0u8h6+jdpdnwZ+U35C9SkC5LnYWl1O5OQzlUdf6n6zQuC0tlOx9VXyHr6NpgO7A3O9hKA1/wDVn70DkoQlZbSX7929P2enlYIn7qF2h//yrIHglIzg4zBEx5Fw4VVETj1L/vqqJNFVX0PrLznUf7eDum8+C/h7lb1BazITNXMew6bNJmT0eIKGxYAQWKtKadi7k4otvvUbg41TSvD/Rwx9oFllDBGsMoYIVhlDBKuMIYJVxhDBKmOIYJXxH4r7WLwgFoGBAAAAAElFTkSuQmCC'
const Example = ({ data }) => <img src={`data:image/jpeg;base64,${data}`} />
ReactDOM.render(<Example data={data} />, document.getElementById('container'))</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div></code></pre>
</div>
</div>
</p>
<p><strong>If you just have an image URL, you can simply do</strong>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const imageURL = 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/1280px-React-icon.svg.png'
const Example = ({ imageURL }) => <img src={imageURL} width={100} />
ReactDOM.render(<Example imageURL={imageURL} />, document.getElementById('container'))</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div></code></pre>
</div>
</div>
</p> |
42,186,537 | Resources, scopes, permissions and policies in keycloak | <p>I want to create a fairly simple role-based access control system using Keycloak's authorizaion system. The system Keycloak is replacing allows us to create a "user", who is a member of one or more "groups". In this legacy system, a user is given "permission" to access each of about 250 "capabilities" either through group membership (where groups are assigned permissions) or a direct grant of a permission to the user.</p>
<p>I would like to map the legacy system to keycloak authorizations.</p>
<p>It should be simple for me to map each "capability" in the existing system to a keycloak resource and a set of keycloak scopes. For example, a "viewAccount" capability would obviously map to an "account" resource and a "view" scope; and "viewTransaction" maps to a "transaction" resource... but is it best practice to create just one "view" scope, and use it across multiple resources (account, transaction, etc)? Or should I create a "viewAccount" scope, a "viewTransaction" scope, etc?</p>
<p>Similarly, I'm a little confused about permissions. For each practical combination of resource and scope, is it usual practice to create a permission? If there are multiple permissions matching a given resource/scope, what does Keycloak do? I'm guessing that the intention of Keycloak is to allow me to configure a matrix of permissions against resources and scopes, so for example I could have permission to access "accounts" and permission for "view" scope, so therefore I would have permission to view accounts?</p>
<p>I ask because the result of all this seems to be that my old "viewAccount" capability ends up creating an "Account" resource, with "View" scope, and a "viewAccount" permission, which seems to get me back where I was. Which is fine, if it's correct.</p>
<p>Finally, obviously I need a set of policies that determine if viewAccount should be applied. But am I right that this means I need a policy for each of the legacy groups that a user could belong to? For example, if I have a "helpdesk" role, then I need a "helpdesk membership" policy, which I could then add to the "viewAccount" permission. Is this correct?</p>
<p>Thanks,</p>
<p>Mark</p> | 58,906,945 | 4 | 14 | null | 2017-02-12 10:37:35.323 UTC | 90 | 2021-07-01 14:20:12.477 UTC | null | null | null | null | 6,716,597 | null | 1 | 170 | permissions|keycloak | 81,606 | <p>I know I'm 2+ years late but I figure I'd share what I know and hopefully alleviate some pain for future readers. Full transparency- I am by no means a Keycloak/OAuth/OIDC expert and what I know is mostly from reading the docs, books, good ol' YouTube and playing around with the tool. </p>
<p>This post will be comprised of two parts: </p>
<ol>
<li>I'll attempt to answer all your questions to the best of my ability </li>
<li>I'll show you all how you can play around with policies/scopes/permissions in Keycloak without needing to deploy a separate app in order to better understand some of the core concepts in this thread. Do note though that this is mostly meant to get you all started. I'm using <code>Keycloak 8.0.0</code>.</li>
</ol>
<h1>Part I</h1>
<p>Some terminology before we get started: </p>
<ul>
<li>In Keycloak, you can create 2 types of permissions: <a href="https://www.keycloak.org/docs/latest/authorization_services/#_permission_create_resource" rel="noreferrer">Resource-Based</a> and <a href="https://www.keycloak.org/docs/latest/authorization_services/#_permission_create_scope" rel="noreferrer">Scope-Based</a>.</li>
<li>Simply put, for <code>Resource-Based</code> permissions, you apply it directly to your resource </li>
<li>For <code>Scoped-Based</code> permission, you apply it to your scope(s) or scope(s) <strong>and</strong> resource. </li>
</ul>
<blockquote>
<p>is it best practice to create just one "view" scope, and use it across multiple resources (account, transaction, etc)? Or should I create a "viewAccount" scope, a "viewTransaction" scope, etc?</p>
</blockquote>
<p>Scopes represent a set of rights at a protected resource. In your case, you have 2 resources: <code>account</code> and <code>transaction</code>, so I would lean towards the second approach. </p>
<p>In the long run, having a global <code>view</code> scope associated with all your resources (e.g. <code>account</code>, <code>transaction</code>, <code>customer</code>, <code>settlement</code>...) makes authorization difficult to both manage and adapt to security requirement changes. </p>
<p>Here are a few examples that you can check out to get a feel for design</p>
<ul>
<li><a href="https://api.slack.com/docs/oauth-scopes" rel="noreferrer">Slack API</a></li>
<li><a href="https://developer.box.com/en/guides/api-calls/permissions-and-errors/scopes/" rel="noreferrer">Box API</a></li>
<li><a href="https://stripe.com/docs/connect/oauth-reference" rel="noreferrer">Stripe</a> </li>
</ul>
<p>Do note though - I am not claiming that you shouldn't share scopes across resources. Matter of fact, <code>Keycloak</code> allows this for resources with the same <code>type</code>. You could for instance need both <code>viewAccount</code> and <code>viewTransaction</code> scope to read a transaction under a given account (after all you might need access to the account to view transactions). Your requirements and standards will heavily influence your design. </p>
<blockquote>
<p>For each practical combination of resource and scope, is it usual practice to create a permission?</p>
</blockquote>
<p>Apologies, I don't fully understand the question so I'll be a bit broad. In order to grant/deny access to a <code>resource</code>, you need to: </p>
<ul>
<li>Define your <a href="https://www.keycloak.org/docs/latest/authorization_services/index.html#_policy_overview" rel="noreferrer">policies</a> </li>
<li>Define your <a href="https://www.keycloak.org/docs/latest/authorization_services/index.html#_permission_overview" rel="noreferrer">permissions</a></li>
<li>Apply your policies to your permissions</li>
<li>Associate your permissions to a <code>scope</code> or <code>resource</code> (or both)</li>
</ul>
<p>for policy enforcement to take effect. See <a href="https://www.keycloak.org/docs/latest/authorization_services/index.html#the-authorization-process" rel="noreferrer">Authorization Process</a>. </p>
<p>How you go about setting all this up is entirely up to you. You could for instance: </p>
<ul>
<li><p>Define individual policies, and tie each policy under the appropriate permission.</p></li>
<li><p>Better yet, define individual policies, then group all your related policies under an <code>aggregated</code> policy (a policy of policies) and then associate that aggregated policy with the <code>scope-based</code> permission. You could have that <code>scoped-based</code> permission apply to both the resource and all its associated scope.</p></li>
<li><p>Or, you could further break apart your permissions by leveraging the two separate types. You could create permissions solely for your resources via the <code>resource-based</code> permission type, and separately associate other permissions solely with a scope via the <code>scope-based</code> permission type. </p></li>
</ul>
<p>You have options. </p>
<blockquote>
<p>If there are multiple permissions matching a given resource/scope, what does Keycloak do? </p>
</blockquote>
<p>This depends on </p>
<ol>
<li>The resource server's <code>Decision Strategy</code></li>
<li>Each permission's <code>Decision Strategy</code></li>
<li>Each policy's <code>Logic</code> value. </li>
</ol>
<p>The <code>Logic</code> value is similar with Java's <code>!</code> operator. It can either be <code>Positive</code> or <code>Negative</code>. When the <code>Logic</code> is <code>Positive</code>, the policy's final evaluation remains unchanged. When its <code>Negative</code>, the final result is negated (e.g. if a policy evaluates to false and its <code>Logic</code> is <code>Negative</code>, then it will be <code>true</code>). To keep things simple, let's assume that the <code>Logic</code> is always set to <code>Positive</code>. </p>
<p>The <code>Decision Strategy</code> is what we really want to tackle. The <code>Decision Strategy</code> can either be <code>Unanimous</code> or <code>Affirmative</code>. From the docs, </p>
<blockquote>
<p><strong>Decision Strategy</strong></p>
<p>This configurations changes how the policy evaluation engine decides whether or not a resource or scope should be granted based on the outcome from all evaluated permissions. <strong>Affirmative</strong> means that at least one permission must evaluate to a positive decision in order grant access to a resource and its scopes. <strong>Unanimous</strong> means that all permissions must evaluate to a positive decision in order for the final decision to be also positive. As an example, if two permissions for a same resource or scope are in conflict (one of them is granting access and the other is denying access), the permission to the resource or scope will be granted if the chosen strategy is Affirmative. Otherwise, a single deny from any permission will also deny access to the resource or scope.</p>
</blockquote>
<p>Let's use an example to better understand the above. Suppose you have a resource with 2 permissions and someone is trying to access that resource (remember, the <code>Logic</code> is <code>Positive</code> for all policies). Now: </p>
<ol>
<li><code>Permission One</code> has a <code>Decision Strategy</code> set to <code>Affirmative</code>. It also has 3 policies where they each evaluate to:
<ul>
<li><code>true</code> </li>
<li><code>false</code> </li>
<li><code>false</code> </li>
</ul></li>
</ol>
<p>Since one of the policies is set to <code>true</code>, <code>Permission One</code> is set to <code>true</code> (Affirmative - only 1 needs to be <code>true</code>).</p>
<ol start="2">
<li><code>Permission Two</code> has a <code>Decision Strategy</code> set to <code>Unanimous</code> with 2 policies:
<ul>
<li><code>true</code> </li>
<li><code>false</code> </li>
</ul></li>
</ol>
<p>In this case <code>Permission Two</code> is <code>false</code> since one policy is false (Unanimous - they all need to be <code>true</code>). </p>
<ol start="3">
<li>Now comes the <strong>final</strong> evaluation. If the resource server's <code>Decision Strategy</code> is set to <code>Affirmative</code>, access to that resource would be granted because <code>Permission One</code> is <code>true</code>. If on the other hand, the resource server's <code>Decision Strategy</code> is set to <code>Unanimous</code>, access would be denied.</li>
</ol>
<p>See: </p>
<ul>
<li><a href="https://www.keycloak.org/docs/latest/authorization_services/index.html#resource_server_settings" rel="noreferrer">Resource Server Settings</a></li>
<li><a href="https://www.keycloak.org/docs/latest/authorization_services/index.html#_permission_overview" rel="noreferrer">Managing Permissions</a> </li>
</ul>
<p>We'll keep revisiting this. I explain how to set the resource sever's <code>Decision Strategy</code> in Part II. </p>
<blockquote>
<p>so for example I could have permission to access "accounts" and permission for "view" scope, so therefore I would have permission to view accounts? </p>
</blockquote>
<p>The short answer is yes. Now, let's expand on this a bit :)</p>
<p>If you have the following scenario: </p>
<ol>
<li>Resource server's <code>Decision Strategy</code> set to <code>Unanimous</code> or <code>Affirmative</code> </li>
<li>Permission to access the <code>account/{id}</code> resource is <code>true</code> </li>
<li>Permission to access the <code>view</code> scope is <code>true</code></li>
</ol>
<p>You will be granted access to view the account. </p>
<ul>
<li><code>true</code> + <code>true</code> is equal to <code>true</code> under the <code>Affirmative</code> or <code>Unanimous</code> <code>Decision Strategy</code>. </li>
</ul>
<p>Now if you have this </p>
<ol>
<li>Resource server's <code>Decision Strategy</code> set to <code>Affirmative</code> </li>
<li>Permission to access the <code>account/{id}</code> resource is <code>true</code></li>
<li>Permission to access the <code>view</code> scope is <code>false</code> </li>
</ol>
<p>You will <em>also</em> be granted access to view the account. </p>
<ul>
<li><code>true</code> + <code>false</code> is <code>true</code> under the <code>Affirmative</code> strategy. </li>
</ul>
<p>The point here is that access to a given resource also depends on your setup so be careful as you may not want the second scenario. </p>
<blockquote>
<p>But am I right that this means I need a policy for each of the legacy groups that a user could belong to? </p>
</blockquote>
<p>I'm not sure how Keycloak behaved 2 years ago, but you can specify a <a href="https://www.keycloak.org/docs/latest/authorization_services/#_policy_group" rel="noreferrer">Group-Based policy</a> and simply add all your groups under that policy. You certainly do not need to create one policy per group. </p>
<blockquote>
<p>For example, if I have a "helpdesk" role, then I need a "helpdesk membership" policy, which I could then add to the "viewAccount" permission. Is this correct?</p>
</blockquote>
<p>Pretty much. There are many ways you can set this up. For instance, you can: </p>
<ol>
<li>Create your resource (e.g. <code>/account/{id}</code>) and associate it with the <code>account:view</code> scope. </li>
<li>create a <a href="https://www.keycloak.org/docs/latest/authorization_services/#_policy_rbac" rel="noreferrer">Role-Based Policy</a> and add the <code>helpdesk</code> role under that policy </li>
<li>Create a <code>Scope-Based</code> permission called <code>viewAccount</code> and tie it with <code>scope</code>, <code>resource</code> and <code>policy</code></li>
</ol>
<p>We'll set up something similar in Part II. </p>
<h1>Part II</h1>
<p>Keycloak has a neat little tool which allows you test all your policies. Better yet, you actually do not need to spin up another application server and deploy a separate app for this to work. </p>
<p>Here's the scenario that we'll set up: </p>
<ol>
<li>We'll create a new realm called <code>stackoverflow-demo</code></li>
<li>We'll create a <code>bank-api</code> client under that realm </li>
<li>We will define a resource called <code>/account/{id}</code> for that client </li>
<li>The <code>account/{id}</code> will have the <code>account:view</code> scope</li>
<li>We'll create a user called <code>bob</code> under the new realm </li>
<li>We'll also create three roles: <code>bank_teller</code>, <code>account_owner</code> and <code>user</code>
<ul>
<li>We will not associate <code>bob</code> with any roles. This is not needed right now. </li>
</ul></li>
<li>We'll set up the following two <code>Role-Based</code> policies:
<ul>
<li><code>bank_teller</code> and <code>account_owner</code> have access to the <code>/account/{id}</code> resource </li>
<li><code>account_owner</code> has access to the <code>account:view</code> scope </li>
<li><code>user</code> does not have access to the resource or scope</li>
</ul></li>
<li>We'll play around with the <code>Evaluate</code> tool to see how access can be granted or
denied. </li>
</ol>
<p>Do forgive me, this example is unrealistic but I'm not familiar with the banking sector :) </p>
<h2>Keycloak setup</h2>
<h3>Download and run Keycloak</h3>
<pre><code>cd tmp
wget https://downloads.jboss.org/keycloak/8.0.0/keycloak-8.0.0.zip
unzip keycloak-8.0.0.zip
cd keycloak-8.0.0/bin
./standalone.sh
</code></pre>
<h3>Create initial admin user</h3>
<ol>
<li>Go to <code>http://localhost:8080/auth</code></li>
<li>Click on the <code>Administration Console</code> link </li>
<li>Create the admin user and login </li>
</ol>
<p>Visit <a href="https://www.keycloak.org/docs/latest/getting_started/" rel="noreferrer">Getting Started</a> for more information. For our purposes, the above is enough. </p>
<h2>Setting up the stage</h2>
<h3>Create a new realm</h3>
<ol>
<li>Hover your mouse around the <code>master</code> realm and click on the <code>Add Realm</code> button.</li>
<li>Enter <code>stackoverflow-demo</code> as the name. </li>
<li>Click on <code>Create</code>. </li>
<li>The top left should now say <code>stackoverflow-demo</code> instead of the <code>master</code> realm. </li>
</ol>
<p>See <a href="https://www.keycloak.org/docs/latest/getting_started/index.html#_create-realm" rel="noreferrer">Creating a New Realm</a> </p>
<h3>Create a new user</h3>
<ol>
<li>Click on the <code>Users</code> link on the left</li>
<li>Click on the <code>Add User</code> button </li>
<li>Enter the <code>username</code> (e.g. <code>bob</code>) </li>
<li>Ensure that <code>User Enabled</code> is turned on </li>
<li>Click <code>Save</code> </li>
</ol>
<p>See <a href="https://www.keycloak.org/docs/latest/getting_started/index.html#_create-new-user" rel="noreferrer">Creating a New User</a></p>
<h3>Create new roles</h3>
<ol>
<li>Click on the <code>Roles</code> link </li>
<li>Click on <code>Add Role</code> </li>
<li>Add the following roles: <code>bank_teller</code>, <code>account_owner</code> and <code>user</code></li>
</ol>
<p>Again, do <strong>not</strong> associate your user with the roles. For our purposes, this is not needed. </p>
<p>See <a href="https://www.keycloak.org/docs/latest/server_admin/#roles" rel="noreferrer">Roles</a></p>
<h3>Create a client</h3>
<ol>
<li>Click on the <code>Clients</code> link </li>
<li>Click on <code>Create</code></li>
<li>Enter <code>bank-api</code> for the <code>Client ID</code> </li>
<li>For the <code>Root URL</code> enter <code>http://127.0.0.1:8080/bank-api</code></li>
<li>Click on <code>Save</code> </li>
<li>Ensure that <code>Client Protocol</code> is <code>openid-connect</code> </li>
<li>Change the <code>Access Type</code> to <code>confidential</code> </li>
<li>Change <code>Authorization Enabled</code> to <code>On</code></li>
<li>Scroll down and hit <code>Save</code>. A new <code>Authorization</code> tab should appear at the top. </li>
<li>Click on the <code>Authorization</code> tab and then <code>Settings</code> </li>
<li>Ensure that the <code>Decision Strategy</code> is set to <code>Unanimous</code>
<ul>
<li>This is the resource server's <code>Decision Strategy</code></li>
</ul></li>
</ol>
<p>See:</p>
<ul>
<li><a href="https://www.keycloak.org/docs/latest/authorization_services/#_resource_server_create_client" rel="noreferrer">Creating a Client Application</a></li>
<li><a href="https://www.keycloak.org/docs/latest/authorization_services/#_resource_server_enable_authorization" rel="noreferrer">Enabling Authorization Services</a></li>
</ul>
<h3>Create Custom Scopes</h3>
<ol>
<li>Click on the <code>Authorization</code> tab </li>
<li>Click on <code>Authorization Scopes</code> > <code>Create</code> to bring up <code>Add Scope</code> page </li>
<li>Enter <code>account:view</code> in the name and hit enter. </li>
</ol>
<h3>Create "View Account Resource"</h3>
<ol>
<li>Click on <code>Authorization</code> link above </li>
<li>Click on <code>Resources</code></li>
<li>Click on <code>Create</code> </li>
<li>Enter <code>View Account Resource</code> for both the <code>Name</code> and <code>Display name</code> </li>
<li>Enter <code>account/{id}</code> for the <code>URI</code> </li>
<li>Enter <code>account:view</code> in the <code>Scopes</code> textbox</li>
<li>Click <code>Save</code></li>
</ol>
<p>See <a href="https://www.keycloak.org/docs/latest/authorization_services/#_resource_create" rel="noreferrer">Creating Resources</a></p>
<h3>Create your policies</h3>
<ol>
<li>Again under the <code>Authorization</code> tab, click on <code>Policies</code> </li>
<li>Select <code>Role</code> from the the <code>Create Policy</code> dropdown </li>
<li>In the <code>Name</code> section, type <code>Only Bank Teller and Account Owner Policy</code> </li>
<li>Under <code>Realm Roles</code> select both the <code>bank_teller</code> and <code>account_owner</code> role</li>
<li>Ensure that <code>Logic</code> is set to <code>Positive</code> </li>
<li>Click <code>Save</code> </li>
<li>Click on the <code>Policies</code> link </li>
<li>Select <code>Role</code> again from the <code>Create Policy</code> dropdown. </li>
<li>This time use <code>Only Account Owner Policy</code> for the <code>Name</code> </li>
<li>Under <code>Realm Roles</code> select <code>account_owner</code></li>
<li>Ensure that <code>Logic</code> is set to <code>Positive</code></li>
<li>Click <code>Save</code> </li>
<li>Click on the <code>Policies</code> link at the top, you should now see your newly created policies. </li>
</ol>
<p>See <a href="https://www.keycloak.org/docs/latest/authorization_services/#_policy_rbac" rel="noreferrer">Role-Based Policy</a> </p>
<p>Do note that Keycloak has much more powerful policies. See <a href="https://www.keycloak.org/docs/latest/authorization_services/#_policy_overview" rel="noreferrer">Managing Policies</a></p>
<h3>Create Resource-Based Permission</h3>
<ol>
<li>Again under the <code>Authorization</code> tab, click on <code>Permissions</code></li>
<li>Select <code>Resource-Based</code> </li>
<li>Type <code>View Account Resource Permission</code> for the <code>Name</code> </li>
<li>Under <code>Resources</code> type <code>View Account Resource Permission</code> </li>
<li>Under <code>Apply Policy</code> select <code>Only Bank Teller and Account Owner Policy</code> </li>
<li>Ensure that the <code>Decision Strategy</code> is set to <code>Unanimous</code></li>
<li>Click <code>Save</code> </li>
</ol>
<p>See <a href="https://www.keycloak.org/docs/latest/authorization_services/#_permission_create_resource" rel="noreferrer">Create Resource-Based Permissions</a> </p>
<p><em>Phew...</em> </p>
<h3>Evaluating the Resource-Based permission</h3>
<ol>
<li>Again under the <code>Authorization</code> tab, select <code>Evaluate</code> </li>
<li>Under <code>User</code> enter <code>bob</code> </li>
<li>Under <code>Roles</code> select <code>user</code>
<ul>
<li>This is where we will associate our user with our created roles. </li>
</ul></li>
<li>Under <code>Resources</code> select <code>View Account Resource</code> and click <code>Add</code> </li>
<li>Click on Evaluate. </li>
<li>Expand the <code>View Account Resource with scopes [account:view]</code> to see the results and you should see <code>DENY</code>. </li>
</ol>
<p><a href="https://i.stack.imgur.com/MyKMU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MyKMU.png" alt="enter image description here"></a></p>
<ol start="7">
<li>This makes sense because we only allow two roles access to that resource via the <code>Only Bank Teller and Account Owner Policy</code>. Let's test this to make sure this is true! </li>
<li>Click on the <code>Back</code> link right above the evaluation result </li>
<li>Change bob's role to <code>account_owner</code> and click on <code>Evaluate</code>. You should now see the result as <code>PERMIT</code>. Same deal if you go back and change the role to <code>bank_teller</code> </li>
</ol>
<p>See <a href="https://www.keycloak.org/docs/latest/authorization_services/#_policy_evaluation_overview" rel="noreferrer">Evaluating and Testing Policies</a></p>
<h3>Create Scope-Based Permission</h3>
<ol>
<li>Go back to the <code>Permissions</code> section </li>
<li>Select <code>Scope-Based</code> this time under the <code>Create Permission</code> dropdown. </li>
<li>Under <code>Name</code>, enter <code>View Account Scope Permission</code> </li>
<li>Under <code>Scopes</code>, enter <code>account:view</code> </li>
<li>Under <code>Apply Policy</code>, enter <code>Only Account Owner Policy</code> </li>
<li>Ensure that the <code>Decision Strategy</code> is set to <code>Unanimous</code></li>
<li>Click <code>Save</code></li>
</ol>
<p>See <a href="https://www.keycloak.org/docs/latest/authorization_services/index.html#_permission_create_scope" rel="noreferrer">Creating Scope-Based Permissions</a> </p>
<p>Second test run </p>
<h3>Evaluating our new changes</h3>
<ol>
<li>Go back to the <code>Authorization</code> section </li>
<li>Click on <code>Evaluate</code></li>
<li>User should be <code>bob</code> </li>
<li>Roles should be <code>bank_teller</code> </li>
<li>Resources should be <code>View Account Resource</code> and click <code>Add</code> </li>
<li>Click on <code>Evaluate</code> and we should get <code>DENY</code>.
<ul>
<li>Again this should come as no surprise as the <code>bank_teller</code> has access to the <code>resource</code> but not the <code>scope</code>. Here one permission evaluates to true, and the other to false. Given that the resource server's <code>Decision Strategy</code> is set to <code>Unanimous</code>, the final decision is <code>DENY</code>. </li>
</ul></li>
<li>Click on <code>Settings</code> under the <code>Authorization</code> tab, and change the <code>Decision Strategy</code> to <code>Affirmative</code> and go back to steps 1-6 again. This time, the final result should be <code>PERMIT</code> (one permission is true, so final decision is true). </li>
<li>For the sake of completeness, turn the resource server's <code>Decision Strategy</code> back to <code>Unanimous</code>. Again, go back to steps 1 through 6 but this time, set the role as <code>account_owner</code>. This time, the final result is again <code>PERMIT</code> which makes sense, given that the <code>account_owner</code> has access to both the <code>resource</code> and <code>scope</code>.</li>
</ol>
<p>Neat :) Hope this helps. </p> |
12,282,936 | mssql_connect() with PHP5 and MSSQL2012 Express | <p>I'm having heavy issues trying to connect to my MSSQL 2012 Express database, with PHP5 running on an Apache.
I have as a test setup just installed a XAMPP with PHP 5.4.4 and Apache running on a Windows 7 machine.</p>
<p>My PHP code (phpmssql_genxml.php):</p>
<pre><code>$connection = mssql_connect('192.168.40.150', $username, $password);
if (!$connection) { die('Not connected : ' . mssql_get_last_message());}
$db_selected = mssql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mssql_get_last_message());
}
$query = "SELECT * FROM Cust WHERE 1";
$result = mssql_query($query);
if (!$result) {
die('Invalid query: ' . mssql_get_last_message());
}
</code></pre>
<p>Output when trying to enter the site:</p>
<pre><code>Fatal error: Call to undefined function mssql_connect() in C:\xampp\htdocs\phpmssql_genxml.php on line 13
</code></pre>
<p>Even if I try to hardcode the username and password into the string, I still get the same result.
Have search a lot on google, but havn't found that post that fixed my issue yet :/
Have enable TCP/IP for the DB instance pipe, even try'd to assign a specific TCP port for it. Have created a rule in the Win7 firewall allowing all traffic to the standard port 1433. Still no luck.</p>
<p>any1 have an idea?? What does the 'Fatal error' part means? Is it the Apache error, PHP or a Database error when trying to connect to it??</p> | 12,293,581 | 2 | 6 | null | 2012-09-05 13:46:20.037 UTC | 1 | 2014-05-23 11:05:34.523 UTC | 2012-09-06 05:17:01.673 UTC | null | 569,101 | null | 1,396,343 | null | 1 | 2 | php|sql-server | 47,899 | <p>You are missing MSSQL driver from your PHP setup. Download it from <a href="http://www.microsoft.com/en-us/download/details.aspx?id=20098" rel="nofollow">here</a>, assuming you have the required system configuration mentioned on the page.</p>
<p>Setting up, from their instructions:</p>
<blockquote>
<ol>
<li>Download SQLSRV30.EXE to a temporary directory</li>
<li>Run SQLSRV30.EXE</li>
<li>When prompted, enter the path to the PHP extensions directory</li>
<li>After extracting the files, read the Installation section of the SQLSRV30_Readme.htm file for next steps</li>
</ol>
</blockquote>
<p>I would also recommend using standard Apache + PHP installation, if you plan to work with MSSQL, instead of any *AMP package.</p> |
45,545,013 | System.ServiceModel not found in .NET Core project | <p>I have a .NET Core xUnit project. I'm trying to call a WCF service from it but get the following exception:</p>
<pre class="lang-none prettyprint-override"><code>System.InvalidOperationException occurred
HResult=0x80131509
Message=An error occurred while loading attribute 'ServiceContractAttribute' on type 'IMyContract'. Please see InnerException for more details.
Inner Exception 1:
FileNotFoundException: Could not load file or assembly 'System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.
</code></pre>
<p>It works with a Framework 4.7 project with the same Nuget Package <code>System.ServiceModel.Http.4.3.0</code>.</p> | 45,549,243 | 4 | 5 | null | 2017-08-07 10:43:36.613 UTC | 13 | 2022-04-29 09:18:27.783 UTC | null | null | null | null | 442,351 | null | 1 | 101 | c#|.net|wcf|.net-core | 100,655 | <p>Microsoft has made available the relevant assemblies as packages on NuGet now.</p>
<p><strong>System.ServiceModel.Primitives</strong> is the base package; add the others if necessary to your project.</p>
<p><a href="https://i.stack.imgur.com/O1g9k.png" rel="noreferrer"><img src="https://i.stack.imgur.com/O1g9k.png" alt="enter image description here" /></a></p>
<p><strong>Update (April 28th, 2022)</strong>:</p>
<p>WCF has been partially ported to .NET 5+ with an official library called <em>CoreWCF</em>: <a href="https://devblogs.microsoft.com/dotnet/corewcf-v1-released/" rel="noreferrer">https://devblogs.microsoft.com/dotnet/corewcf-v1-released/</a></p> |
41,398,489 | What is the difference between repository and branch in git? | <p>Someone who is well versed in git could help me to understand the difference between repo and branch. I am recently introduced to git and having a bit hard time to understand them. I was told to clone a remote repo (e.g. foo) to my local box. Then create a local branch out of it. Work (update/create/delete files) on the branch and add/commit/push to the remote server (e.g. bitbucket). After 2nd set of eyes review the branch and says ok. Then it gets merged to development or master branch.</p>
<p>Then what role, a repository plays in this picture? To me all the operations I ran is against branch...</p> | 41,398,581 | 3 | 2 | null | 2016-12-30 15:17:13.907 UTC | 10 | 2018-07-04 15:26:46.863 UTC | null | null | null | null | 1,056,958 | null | 1 | 12 | git | 29,713 | <p>A <em>repository</em> is your whole project (directories and files) that you clone on your computer. A <em>branch</em> is a version of your repository, or in other words, an independent line of development.</p>
<p>A repository can contain multiple <em>branches</em>, which means there are multiple versions of the repository. The purpose of versioning your code after all, is that you can work on multiple aspects of your project at the same time - each of those evolving in different <em>branches</em>. Git uses the expression "working tree" (representing your workbench) alongside "branches".</p>
<p>Related: If you want to know more about the <a href="https://stackoverflow.com/q/16408300">local and remote branches</a>.</p>
<hr>
<p>Concerning the way of dealing with branches in your initial question:</p>
<blockquote>
<p>Clone a remote repo (e.g. foo) to my local box. Then create a local branch out of it. Work (update/create/delete files) on the branch and add/commit/push to the remote server</p>
</blockquote>
<p>This is a nice and clean way to work with git. I suggest you always proceed like this :</p>
<pre><code>----A---B---C-- (REMOTE, master)
|
| (Pull to local : `git pull origin master`)
v
----A---B---C-- (LOCAL, master)
</code></pre>
<p>Then create a branch from your local master (<code>git checkout -b branch1</code>), work on it, commit your changes and push to remote :</p>
<pre><code>----A---B---C------ (REMOTE, master)
----A---B---C---D-- (REMOTE, branch1)
^
|
| (Push to remote : `git push origin branch1`)
----A---B---C------ (LOCAL, master)
\
D---- (LOCAL, branch1)
</code></pre>
<p>Then, when you're happy with your feature/fix/whatever, you can merge <code>branch1</code> into <code>master</code>.</p> |
57,673,825 | How to force GCC to assume that a floating-point expression is non-negative? | <p>There are cases where you know that a certain floating-point expression will always be non-negative. For example, when computing the length of a vector, one does <code>sqrt(a[0]*a[0] + ... + a[N-1]*a[N-1])</code> (NB: I <em>am</em> aware of <code>std::hypot</code>, this is not relevant to the question), and the expression under the square root is clearly non-negative. However, GCC <a href="https://godbolt.org/z/SsrYUu" rel="noreferrer">outputs</a> the following assembly for <code>sqrt(x*x)</code>:</p>
<pre><code> mulss xmm0, xmm0
pxor xmm1, xmm1
ucomiss xmm1, xmm0
ja .L10
sqrtss xmm0, xmm0
ret
.L10:
jmp sqrtf
</code></pre>
<p>That is, it compares the result of <code>x*x</code> to zero, and if the result is non-negative, it does the <code>sqrtss</code> instruction, otherwise it calls <code>sqrtf</code>.</p>
<p>So, my question is: <strong>how can I force GCC into assuming that <code>x*x</code> is always non-negative so that it skips the comparison and the <code>sqrtf</code> call, without writing inline assembly?</strong></p>
<p>I wish to emphasize that I am interested in a local solution, and not doing things like <code>-ffast-math</code>, <code>-fno-math-errno</code>, or <code>-ffinite-math-only</code> (though these do indeed solve the issue, thanks to ks1322, harold, and Eric Postpischil in the comments).</p>
<p>Furthemore, "force GCC into assuming <code>x*x</code> is non-negative" should be interpreted as <code>assert(x*x >= 0.f)</code>, so this also excludes the case of <code>x*x</code> being NaN.</p>
<p>I am OK with compiler-specific, platform-specific, CPU-specific, etc. solutions.</p> | 57,674,631 | 4 | 12 | null | 2019-08-27 11:35:25.68 UTC | 13 | 2021-12-22 20:57:54.323 UTC | 2019-08-27 12:54:28.647 UTC | null | 224,132 | null | 2,315,602 | null | 1 | 62 | c++|gcc|assembly|floating-point|micro-optimization | 4,323 | <p>You can write <code>assert(x*x >= 0.f)</code> as a compile-time promise instead of a runtime check as follows in GNU C:</p>
<pre><code>#include <cmath>
float test1 (float x)
{
float tmp = x*x;
if (!(tmp >= 0.0f))
__builtin_unreachable();
return std::sqrt(tmp);
}
</code></pre>
<p>(related: <a href="https://stackoverflow.com/questions/54764535/what-optimizations-does-builtin-unreachable-facilitate">What optimizations does __builtin_unreachable facilitate?</a> You could also wrap <code>if(!x)__builtin_unreachable()</code> in a macro and call it <code>promise()</code> or something.)</p>
<p>But gcc doesn't know how to take advantage of that promise that <code>tmp</code> is non-NaN and non-negative. We still get (<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,lang:c%2B%2B,source:%27%23include+%3Ccmath%3E%0A%0Afloat+test1+(float+x)%0A%7B%0A++++float+tmp+%3D+x*x%3B%0A++++if+(!!(tmp+%3E%3D+0.0f))+%0A++++++++__builtin_unreachable()%3B++++%0A++++return+std::sqrt(tmp)%3B%0A%7D%0A%0Afloat+test2+(float+x)%0A%7B%0A++++return+std::sqrt(x*x)%3B%0A%7D%0A%27),l:%275%27,n:%270%27,o:%27C%2B%2B+source+%231%27,t:%270%27)),k:36.64524356415925,l:%274%27,m:100,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:g92,filters:(b:%270%27,binary:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%271%27,intel:%270%27,libraryCode:%271%27,trim:%271%27),lang:c%2B%2B,libs:!((name:rangesv3,ver:%27036%27)),options:%27-fno-math-errno+-std%3Dgnu%2B%2B17+-O3%27,source:1),l:%275%27,n:%270%27,o:%27x86-64+gcc+9.2+(Editor+%231,+Compiler+%231)+C%2B%2B%27,t:%270%27)),header:(),k:30.021423102507427,l:%274%27,m:100,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:gsnapshot,filters:(b:%270%27,binary:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%271%27,intel:%270%27,libraryCode:%271%27,trim:%271%27),lang:c%2B%2B,libs:!((name:rangesv3,ver:%27036%27)),options:%27-std%3Dgnu%2B%2B17+-O3+-fno-trapping-math%27,source:1),l:%275%27,n:%270%27,o:%27x86-64+gcc+(trunk)+(Editor+%231,+Compiler+%232)+C%2B%2B%27,t:%270%27)),k:33.33333333333333,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%272%27,m:100,n:%270%27,o:%27%27,t:%270%27)),version:4" rel="nofollow noreferrer">Godbolt</a>) the same canned asm sequence that checks for <code>x>=0</code> and otherwise calls <code>sqrtf</code> to set <code>errno</code>. <strong>Presumably that expansion into a compare-and-branch happens after other optimization passes,</strong> so it doesn't help for the compiler to know more.</p>
<p>This is a missed-optimization in the logic that speculatively inlines <code>sqrt</code> when <code>-fmath-errno</code> is enabled (on by default unfortunately).</p>
<h2>What you want instead is <code>-fno-math-errno</code>, which is safe globally</h2>
<p><strong>This is 100% safe if you don't rely on math functions ever setting <code>errno</code></strong>. Nobody wants that, that's what NaN propagation and/or sticky flags that record masked FP exceptions are for. e.g. C99/C++11 <a href="https://en.cppreference.com/w/cpp/numeric/fenv" rel="nofollow noreferrer"><code>fenv</code></a> access via <code>#pragma STDC FENV_ACCESS ON</code> and then functions like <a href="https://en.cppreference.com/w/cpp/numeric/fenv/fetestexcept" rel="nofollow noreferrer"><code>fetestexcept()</code></a>. See the example in <a href="https://en.cppreference.com/w/cpp/numeric/fenv/feclearexcept" rel="nofollow noreferrer"><code>feclearexcept</code></a> which shows using it to detect division by zero.</p>
<p>The FP environment is part of thread context while <code>errno</code> is global.</p>
<p>Support for this obsolete misfeature is not free; you should just turn it off unless you have old code that was written to use it. Don't use it in new code: use <code>fenv</code>. Ideally support for <code>-fmath-errno</code> would be as cheap as possible but the rarity of anyone actually using <code>__builtin_unreachable()</code> or other things to rule out a NaN input presumably made it not worth developer's time to implement the optimization. Still, you could report a missed-optimization bug if you wanted.</p>
<p>Real-world FPU hardware does in fact have these sticky flags that stay set until cleared, e.g. <a href="http://softpixel.com/%7Ecwright/programming/simd/sse.php" rel="nofollow noreferrer">x86's <code>mxcsr</code></a> status/control register for SSE/AVX math, or hardware FPUs in other ISAs. On hardware where the FPU can detect exceptions, a quality C++ implementation will support stuff like <code>fetestexcept()</code>. And if not, then math-<code>errno</code> probably doesn't work either.</p>
<p><code>errno</code> for math was an old obsolete design that C / C++ is still stuck with by default, and is now widely considered a bad idea. It makes it harder for compilers to inline math functions efficiently. Or maybe we're not as stuck with it as I thought: <a href="https://stackoverflow.com/questions/56243525/why-errno-is-not-set-to-edom-even-sqrt-takes-out-of-domain-arguement">Why errno is not set to EDOM even sqrt takes out of domain arguement?</a> explains that setting errno in math functions is <em>optional</em> in ISO C11, and an implementation can indicate whether they do it or not. Presumably in C++ as well.</p>
<p><strong>It's a big mistake to lump <code>-fno-math-errno</code> in with value-changing optimizations like <code>-ffast-math</code> or <code>-ffinite-math-only</code>.</strong> You should strongly consider enabling it globally, or at least for the whole file containing this function.</p>
<pre><code>float test2 (float x)
{
return std::sqrt(x*x);
}
</code></pre>
<pre><code># g++ -fno-math-errno -std=gnu++17 -O3
test2(float): # and test1 is the same
mulss xmm0, xmm0
sqrtss xmm0, xmm0
ret
</code></pre>
<hr />
<p>You might as well use <code>-fno-trapping-math</code> as well, if you aren't ever going to unmask any FP exceptions with <code>feenableexcept()</code>. (Although that option isn't required for this optimization, it's only the <code>errno</code>-setting crap that's a problem here.).</p>
<p><code>-fno-trapping-math</code> doesn't assume no-NaN or anything, it only assumes that FP exceptions like Invalid or Inexact won't ever actually invoke a signal handler instead of producing NaN or a rounded result. <code>-ftrapping-math</code> is the default but <a href="https://stackoverflow.com/questions/56670132/simd-for-float-threshold-operation#comment99952463_56681744">it's broken and "never worked" according to GCC dev Marc Glisse</a>. (Even with it on, GCC does some optimizations which can change the number of exceptions that would be raised from zero to non-zero or vice versa. And it blocks some safe optimizations). But unfortunately, <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54192" rel="nofollow noreferrer">https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54192</a> (make it off by default) is still open.</p>
<p>If you actually ever did unmask exceptions, it might be better to have <code>-ftrapping-math</code>, but again it's very rare that you'd ever want that instead of just checking flags after some math operations, or checking for NaN. And it doesn't actually preserve exact exception semantics anyway.</p>
<p>See <a href="https://stackoverflow.com/questions/56670132/simd-for-float-threshold-operation">SIMD for float threshold operation</a> for a case where the <code>-ftrapping-math</code> default incorrectly blocks a safe optimization. (Even after hoisting a potentially-trapping operation so the C does it unconditionally, gcc makes non-vectorized asm that does it conditionally! So not only does GCC block vectorization, it changes the exception semantics vs. the C abstract machine.) <code>-fno-trapping-math</code> enables the expected optimization.</p> |
15,707,688 | Why is calling vector.reserve(required + 1) faster than vector.reserve(required)? | <p>I am doing some tests measuring the performance of standard containers under various conditions, and I came across something odd. When I am inserting many items into the middle of a <code>std::vector</code>, if I first call reserve with the exact number of elements that I will be adding, I see essentially no performance difference in most circumstances compared with not calling reserve, which is surprising. More surprising, however, is that if I call reserve with the exact number of elements I need <code>+ 1</code>, then I get a significant performance improvement. This is a sample table of results that I just got (all time are in seconds):</p>
<pre><code>+---------------+--------+-------------------+-----------------------+
| # of elements | vector | vector (reserved) | vector (reserved + 1) |
+---------------+--------+-------------------+-----------------------+
| 10000 | 0.04 | 0.04 | 0.03 |
| 20000 | 0.14 | 0.14 | 0.11 |
| 30000 | 0.32 | 0.32 | 0.25 |
| 40000 | 0.55 | 0.55 | 0.44 |
| 50000 | 0.87 | 0.85 | 0.66 |
| 60000 | 1.24 | 1.24 | 0.96 |
| 70000 | 1.69 | 1.68 | 1.31 |
| 80000 | 2.17 | 2.21 | 1.71 |
| 90000 | 2.78 | 2.75 | 2.16 |
| 100000 | 3.43 | 3.44 | 2.68 |
| 110000 | 4.13 | 4.15 | 3.23 |
| 120000 | 4.88 | 4.89 | 3.86 |
| 130000 | 5.79 | 5.8 | 4.51 |
| 140000 | 6.71 | 6.71 | 5.24 |
| 150000 | 7.7 | 7.7 | 6.02 |
| 160000 | 8.76 | 8.67 | 6.86 |
| 170000 | 9.9 | 9.91 | 7.74 |
| 180000 | 11.07 | 10.98 | 8.64 |
| 190000 | 12.34 | 12.35 | 9.64 |
| 200000 | 13.64 | 13.56 | 10.72 |
| 210000 | 15.1 | 15.04 | 11.67 |
| 220000 | 16.59 | 16.41 | 12.89 |
| 230000 | 18.05 | 18.06 | 14.13 |
| 240000 | 19.64 | 19.74 | 15.36 |
| 250000 | 21.34 | 21.17 | 16.66 |
| 260000 | 23.08 | 23.06 | 18.02 |
| 270000 | 24.87 | 24.89 | 19.42 |
| 280000 | 26.5 | 26.58 | 20.9 |
| 290000 | 28.51 | 28.69 | 22.4 |
| 300000 | 30.69 | 30.74 | 23.97 |
| 310000 | 32.73 | 32.81 | 25.57 |
| 320000 | 34.63 | 34.99 | 27.28 |
| 330000 | 37.12 | 37.17 | 28.99 |
| 340000 | 39.36 | 39.43 | 30.83 |
| 350000 | 41.7 | 41.48 | 32.45 |
| 360000 | 44.11 | 44.22 | 34.55 |
| 370000 | 46.62 | 46.71 | 36.22 |
| 380000 | 49.09 | 48.91 | 38.46 |
| 390000 | 51.71 | 51.98 | 40.22 |
| 400000 | 54.45 | 54.56 | 43.03 |
| 410000 | 57.23 | 57.29 | 44.84 |
| 420000 | 60 | 59.73 | 46.67 |
| 430000 | 62.9 | 63.03 | 49.3 |
+---------------+--------+-------------------+-----------------------+
</code></pre>
<p>I checked the implementation, and it doesn't appear to have an off-by-one error. I then further tested by printing the size and the capacity immediately after calling reserve, and then I printed them again after filling up the vector, and everything looks good.</p>
<pre><code>before:
size: 0
capacity: 10000
after:
size: 10000
capacity: 10000
before:
size: 0
capacity: 20000
after:
size: 20000
capacity: 20000
...
</code></pre>
<p>Compiler is gcc 4.7.2 on Fedora Linux x86_64. Compiler options are <code>-std=c++11 -Ofast -march=native -funsafe-loop-optimizations -flto=4 - fwhole-program</code></p>
<p>The code is below.</p>
<pre><code>#include <algorithm>
#include <array>
#include <cstdint>
#include <vector>
#include <random>
#include <string>
#include <iostream>
#include <fstream>
#include <boost/timer.hpp>
namespace {
constexpr size_t array_size = 1;
unsigned number() {
static std::random_device rd;
static std::mt19937 random_engine(rd());
static std::uniform_int_distribution<uint32_t> distribution(0, std::numeric_limits<uint32_t>::max());
return distribution(random_engine);
}
class Class {
public:
Class() {
x[0] = number();
}
std::string to_string() const {
return std::to_string(x[0]);
}
inline friend bool operator<=(Class const & lhs, Class const & rhs) {
return lhs.x[0] <= rhs.x[0];
}
private:
std::array<uint32_t, array_size> x;
};
template<typename Container>
void add(Container & container, Class const & value) {
auto const it = std::find_if(std::begin(container), std::end(container), [&](Class const & c) {
return value <= c;
});
container.emplace(it, value);
}
// Do something with the result
template<typename Container>
void insert_to_file(Container const & container) {
std::fstream file("file.txt");
for (auto const & value : container) {
file << value.to_string() << '\n';
}
}
template<typename Container>
void f(std::vector<Class> const & values) {
Container container;
container.reserve(values.size());
for (auto const & value : values) {
add(container, value);
}
insert_to_file(container);
}
}
int main(int argc, char ** argv) {
std::size_t const size = (argc == 1) ? 1 : std::stoul(argv[1]);
// Default constructor of Class fills in values here
std::vector<Class> const values_to_be_copied(size);
typedef std::vector<Class> Container;
boost::timer timer;
f<Container>(values_to_be_copied);
std::cerr << "Finished in " << timer.elapsed() << " seconds.\n";
}
</code></pre>
<p>I created a C++03 version to try and help other people reproduce it, but I cannot reproduce it in this version, despite trying to make it show the problem by making it as direct of a translation as possible:</p>
<pre><code>#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <boost/array.hpp>
#include <boost/cstdint.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/timer.hpp>
namespace {
unsigned number() {
static boost::random::mt19937 random_engine;
static boost::random::uniform_int_distribution<boost::uint32_t> distribution(0, std::numeric_limits<boost::uint32_t>::max());
return distribution(random_engine);
}
class Class {
public:
Class() {
x[0] = number();
}
inline friend bool operator<=(Class const & lhs, Class const & rhs) {
return lhs.x[0] <= rhs.x[0];
}
std::string to_string() const {
return boost::lexical_cast<std::string>(x[0]);
}
private:
boost::array<boost::uint32_t, 1> x;
};
class Less {
public:
Less(Class const & c):
value(c) {
}
bool operator()(Class const & c) const {
return value <= c;
}
private:
Class value;
};
void add(std::vector<Class> & container, Class const & value) {
std::vector<Class>::iterator it = std::find_if(container.begin(), container.end(), Less(value));
container.insert(it, value);
}
// Do something with the result
void insert_to_file(std::vector<Class> const & container) {
std::fstream file("file.txt");
for (std::vector<Class>::const_iterator it = container.begin(); it != container.end(); ++it) {
file << it->to_string() << '\n';
}
}
void f(std::vector<Class> const & values) {
std::vector<Class> container;
container.reserve(values.size() + 1);
for (std::vector<Class>::const_iterator it = values.begin(); it != values.end(); ++it) {
add(container, *it);
}
insert_to_file(container);
}
}
int main(int argc, char ** argv) {
std::size_t const size = (argc == 1) ? 1 : boost::lexical_cast<std::size_t>(argv[1]);
// Default constructor of Class fills in values here
std::vector<Class> const values_to_be_copied(size);
boost::timer timer;
f(values_to_be_copied);
std::cerr << "Finished in " << timer.elapsed() << " seconds.\n";
}
</code></pre>
<p>The line that currently calls reserve was changed to include a <code>+ 1</code> or was completely removed, depending on which test I was running. The entire thing was run from a shell script that started at 10000 elements and increased up to 430000 elements, going one version at a time.</p>
<p>My processor is an Intel i5 4-core processor, and I have 4 GiB of memory. I will try and simplify the C++11 version of the code as much as possible to see if I can isolate the problem.</p>
<p>Does anyone know why reserving one more element than I need is causing this increase in speed?</p> | 15,733,585 | 2 | 19 | null | 2013-03-29 16:50:54.33 UTC | 12 | 2013-03-31 20:04:31.55 UTC | 2013-03-29 18:35:55.703 UTC | null | 852,254 | null | 852,254 | null | 1 | 47 | c++|performance|memory|stdvector | 1,880 | <p>I made the following modification to the program:</p>
<pre><code>size_t a = getenv("A") ? 1 : 0;
void f(std::vector<Class> const & values) {
...
container.reserve(values.size() + a);
...
}
</code></pre>
<p>Now the performance is same (fast) regardless if a is 0 or 1. The conclusion must be that the reservation of an extra item has no performance impact (which was assumed in the question). Also other small changes to the source code or compiler flags toggles the performance between fast and slow, so it looks like the code optimizer just has better luck in some cases than in others.</p>
<p>The following implementation of f() triggers the opposite behaviour with same compiler flags, thus it is fast when exact size is reserved and slow when an extra item is reserved:</p>
<pre><code>template<typename Container>
void f(std::vector<Class> const & values) {
Container container;
container.reserve(values.size());
for (auto it = values.begin(); it != values.end(); ++it) {
add(container, *it);
}
insert_to_file(container);
}
</code></pre> |
15,960,729 | Abstract Class vs. Interface | <p>I have searched around SO as well as the rest of the web for a good answer but I have't found one that I really understand. I am going to present this in a different way and hopefully the answers will help others as well. </p>
<p>As far as I understand, the two concepts have the same rules except an abstract class is more flexible due to the method implementation ability. Also, I am aware you can implement multiple interfaces and only extend a single class but I'm sure there are more differences than the two I mentioned.</p>
<p>Please look at the two snippets of code and give me an example what I can do with each of my examples that would make me want or not want to use the other. </p>
<h1>Abstract Class</h1>
<pre><code>abstract class Foo {
abstract public function getValue();
abstract public function setValue($value);
}
class myObj extends Foo {
function getValue() {
}
function setValue($value) {
}
}
</code></pre>
<h1>Interface</h1>
<pre><code>interface Foo {
public function getValue();
public function setValue($value);
}
class myObj implements Foo {
function getValue() {
}
function setValue($value) {
}
}
</code></pre> | 15,960,845 | 4 | 1 | null | 2013-04-11 23:40:22.353 UTC | 39 | 2014-11-05 21:33:23.95 UTC | null | null | null | null | 204,263 | null | 1 | 62 | php|interface|abstract-class|conceptual | 58,856 | <p>To resume the idea (globally, not in detail):</p>
<pre><code>inheritance
</code></pre>
<p>is the notion to <code>extend from something</code>, and optionally add some new feature or override some existing feature (to do differently). But using inheritance, you share a big part of code with the parent. <strong>You are</strong> a parent + some other things.</p>
<pre><code>interface
</code></pre>
<p>is representing some abilities (we says a class is <em>implementing</em> an interface to says that it has these abilities). An interface can be implemented by 2 classes which are completely different and do not share their code (except for methods they implements). When A and B are implementing interface C, A is not a B and B is not a A.</p>
<p>And one of the reason for <code>interface</code> is indeed to allow programmer to do the same as they could do with multi-inheritance, but without multi-inheritance problems.</p>
<p>This notion is used in some programming languages like JAVA, PHP...</p> |
10,456,728 | Is there an equivalent to memcpy() that works inside a CUDA kernel? | <p>I'm trying to break apart and reshape the structure of an array asynchronously using the CUDA kernel. <code>memcpy()</code> doesn't work inside the kernel, and neither does <code>cudaMemcpy()</code>*; I'm at a loss.</p>
<p>Can anyone tell me the preferred method for copying memory from within the CUDA kernel?</p>
<p><strong>It is worth noting, <code>cudaMemcpy(void *to, void *from, size, cudaMemcpyDeviceToDevice)</code> will NOT work for what I am trying to do, because it can only be called from outside of the kernel and does not execute asynchronously.</strong></p> | 10,468,720 | 3 | 3 | null | 2012-05-04 22:07:05.933 UTC | 12 | 2019-09-09 07:45:24.423 UTC | 2016-06-12 10:19:03.983 UTC | null | 681,865 | null | 365,338 | null | 1 | 22 | cuda | 23,999 | <p>Yes, there is an equivalent to <code>memcpy</code> that works inside cuda kernels. It is called <code>memcpy</code>. As an example:</p>
<pre><code>__global__ void kernel(int **in, int **out, int len, int N)
{
int idx = threadIdx.x + blockIdx.x*blockDim.x;
for(; idx<N; idx+=gridDim.x*blockDim.x)
memcpy(out[idx], in[idx], sizeof(int)*len);
}
</code></pre>
<p>which compiles without error like this:</p>
<pre><code>$ nvcc -Xptxas="-v" -arch=sm_20 -c memcpy.cu
ptxas info : Compiling entry function '_Z6kernelPPiS0_ii' for 'sm_20'
ptxas info : Function properties for _Z6kernelPPiS0_ii
0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads
ptxas info : Used 11 registers, 48 bytes cmem[0]
</code></pre>
<p>and emits PTX:</p>
<pre><code>.version 3.0
.target sm_20
.address_size 32
.file 1 "/tmp/tmpxft_00000407_00000000-9_memcpy.cpp3.i"
.file 2 "memcpy.cu"
.file 3 "/usr/local/cuda/nvvm/ci_include.h"
.entry _Z6kernelPPiS0_ii(
.param .u32 _Z6kernelPPiS0_ii_param_0,
.param .u32 _Z6kernelPPiS0_ii_param_1,
.param .u32 _Z6kernelPPiS0_ii_param_2,
.param .u32 _Z6kernelPPiS0_ii_param_3
)
{
.reg .pred %p<4>;
.reg .s32 %r<32>;
.reg .s16 %rc<2>;
ld.param.u32 %r15, [_Z6kernelPPiS0_ii_param_0];
ld.param.u32 %r16, [_Z6kernelPPiS0_ii_param_1];
ld.param.u32 %r2, [_Z6kernelPPiS0_ii_param_3];
cvta.to.global.u32 %r3, %r15;
cvta.to.global.u32 %r4, %r16;
.loc 2 4 1
mov.u32 %r5, %ntid.x;
mov.u32 %r17, %ctaid.x;
mov.u32 %r18, %tid.x;
mad.lo.s32 %r30, %r5, %r17, %r18;
.loc 2 6 1
setp.ge.s32 %p1, %r30, %r2;
@%p1 bra BB0_5;
ld.param.u32 %r26, [_Z6kernelPPiS0_ii_param_2];
shl.b32 %r7, %r26, 2;
.loc 2 6 54
mov.u32 %r19, %nctaid.x;
.loc 2 4 1
mov.u32 %r29, %ntid.x;
.loc 2 6 54
mul.lo.s32 %r8, %r29, %r19;
BB0_2:
.loc 2 7 1
shl.b32 %r21, %r30, 2;
add.s32 %r22, %r4, %r21;
ld.global.u32 %r11, [%r22];
add.s32 %r23, %r3, %r21;
ld.global.u32 %r10, [%r23];
mov.u32 %r31, 0;
BB0_3:
add.s32 %r24, %r10, %r31;
ld.u8 %rc1, [%r24];
add.s32 %r25, %r11, %r31;
st.u8 [%r25], %rc1;
add.s32 %r31, %r31, 1;
setp.lt.u32 %p2, %r31, %r7;
@%p2 bra BB0_3;
.loc 2 6 54
add.s32 %r30, %r8, %r30;
ld.param.u32 %r27, [_Z6kernelPPiS0_ii_param_3];
.loc 2 6 1
setp.lt.s32 %p3, %r30, %r27;
@%p3 bra BB0_2;
BB0_5:
.loc 2 9 2
ret;
}
</code></pre>
<p>The code block at <code>BB0_3</code> is a byte sized <code>memcpy</code> loop emitted automagically by the compiler. It might not be a great idea from a performance point-of-view to use it, but it is fully supported (and has been for a long time on all architectures).</p>
<hr>
<p>Edited four years later to add that since the device side runtime API was released as part of the CUDA 6 release cycle, it is also possible to directly call something like</p>
<pre><code>cudaMemcpyAsync(void *to, void *from, size, cudaMemcpyDeviceToDevice)
</code></pre>
<p>in device code for all architectures which support it (Compute Capability 3.5 and newer hardware using separate compilation and device linking).</p> |
10,553,597 | cin and getline skipping input | <p>earlier i posted a question about <code>cin</code> skipping input, and I got results to flush, and use <code>istringstream</code>, but now I tried every possible solution but none of them work.</p>
<p>here is my code:</p>
<pre><code>void createNewCustomer () {
string name, address;
cout << "Creating a new customer..." << endl;
cout << "Enter the customer's name: "; getline(cin, name);
cout << "Enter the customer's address: "; getline(cin, address);
Customer c(name, address, 0);
CustomerDB::addCustomer(c);
cout << endl;
}
</code></pre>
<p>but I'm still getting the same thing, skipping input, and when it does take input, it takes them and stores in name empty nothing, and in address it takes what i wrote in name but from the 2nd letter to the end</p>
<p>what is wrong with my code?</p>
<p>I tried the <code>cin.ignore()</code>, <code>cin.get()</code>, and <code>cin.clear()</code> all of them together and alone, none of them worked</p>
<p>EDIT:</p>
<p>main method in main.cpp invokes <code>mainMenu()</code> only</p>
<pre><code>void mainMenu () {
char choice;
do {
system("cls");
mainMenuDisplay();
cin >> choice;
system("cls");
switch (choice) {
case '1':
customerMenu();
break;
case '2':
dvdMenu();
break;
case '3':
receiptMenu();
break;
case '4':
outro();
break;
default:
cout << '\a';
}
cin.ignore();
cin.get();
} while (choice != '4');
}
</code></pre>
<p>i will choose 1 for the customer example, this is <code>customerMenu()</code></p>
<pre><code>void customerMenu () {
char choice;
do {
system("cls");
manageCustomerMenu();
cin >> choice;
system("cls");
switch (choice) {
case '1':
createNewCustomer();
break;
case '2':
deleteCustomer();
break;
case '3':
updateCustomerStatus();
break;
case '4':
viewCustomersList();
break;
case '5':
mainMenu();
break;
default:
cout << '\a';
}
cin.ignore();
cin.get();
} while (choice != '5');
}
</code></pre>
<p>I choose 1 again to create a new customer object, which will now go to the MainFunctions.cpp which will invoke the function <code>createNewCustomer()</code> which is the first one.</p>
<pre><code>void createNewCustomer () {
string name, address;
cout << "Creating a new customer..." << endl;
cout << "Enter the customer's name: "; cin.getline(name,256);
cout << "Enter the customer's address: "; cin.getline(address,256);
Customer c(name, address, 0);
CustomerDB::addCustomer(c);
cout << endl;
}
</code></pre> | 10,553,849 | 4 | 3 | null | 2012-05-11 14:43:51.89 UTC | 19 | 2014-12-11 09:35:24.587 UTC | 2012-05-11 14:56:24.567 UTC | null | 1,001,335 | null | 1,001,335 | null | 1 | 48 | c++|input|getline|cin | 143,054 | <p>If you're using <code>getline</code> after <code>cin >> something</code>, you need to flush the newline out of the buffer in between.</p>
<p>My personal favourite for this if no characters past the newline are needed is <code>cin.sync()</code>. However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use <code>cin.ignore()</code>. Or make use of <code>std::ws</code> to remove leading whitespace if desirable:</p>
<pre><code>int a;
cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
//discard characters until newline is found
//my method: cin.sync(); //discard unread characters
string s;
getline (cin, s); //newline is gone, so this executes
//other method: getline(cin >> ws, s); //remove all leading whitespace
</code></pre> |
46,412,734 | How should I manage DbContext Lifetime in MVC Core? | <p>From the <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection" rel="noreferrer">Documentation</a></p>
<blockquote>
<p>Entity Framework contexts <strong>should</strong> be added to the services container
using the <code>Scoped</code> lifetime. This is taken care of automatically if you
use the helper methods as shown above. Repositories that will make use
of Entity Framework should use the same lifetime.</p>
</blockquote>
<p>I always thought, that I should create a new <code>Context</code> for every single unit of work I have to process. This let me think, if I have a <code>ServiceA</code> and <code>ServiceB</code>, which are applying different actions on the <code>DbContext</code> that they should get a different Instance of <code>DbContext</code>.</p>
<p>The <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection" rel="noreferrer">documentation</a> reads as following:</p>
<blockquote>
<ul>
<li><p><code>Transient</code> objects are always different; a new instance is provided to every controller and every service.</p></li>
<li><p><code>Scoped</code> objects are the same within a request, but different across different request</p></li>
</ul>
</blockquote>
<p>Going back to <code>ServiceA</code> and <code>ServiceB</code>, it sounds to me, <code>Transient</code> is more suitable.</p>
<p>I have researched, that the Context should only saved once per <code>HttpRequest</code>, but I really do not understand how this does work.</p>
<p>Especially if we take a look at one Service:</p>
<pre><code>using (var transaction = dbContext.Database.BeginTransaction())
{
//Create some entity
var someEntity = new SomeEntity();
dbContext.SomeEntity.Add(someEntity);
//Save in order to get the the id of the entity
dbContext.SaveChanges();
//Create related entity
var relatedEntity = new RelatedEntity
{
SomeEntityId = someEntity.Id
};
dbContext.RelatedEntity.Add(relatedEntity)
dbContext.SaveChanges();
transaction.Commit();
}
</code></pre>
<p>Here we need to Save the context in order to get the ID of an Entity which is related to another one we just have created.</p>
<p>At the same time another service could update the same context. From what I have read, <code>DbContext</code> is not thread safe.</p>
<p>Should I use <code>Transient</code> in this case? Why does the documentation suggest, I <strong>should</strong> use <code>Scoped</code>?</p>
<p>Do I miss some important part of the framework?</p> | 46,414,787 | 2 | 9 | null | 2017-09-25 19:25:34.907 UTC | 9 | 2018-06-21 01:46:02.733 UTC | 2018-06-21 01:46:02.733 UTC | null | 1,264,356 | null | 2,441,442 | null | 1 | 28 | c#|asp.net-core|asp.net-core-mvc|.net-core|entity-framework-core | 16,219 | <p>As others already explained, you <em>should</em> use a scoped dependency for database contexts to make sure it will be properly reused. For concurrency, remember that you can query the database asynchronously too, so you might not need actual threads.</p>
<p>If you do <em>need</em> threads, i.e. background workers, then it’s likely that those will have a different lifetime than the request. As such, those threads should <em>not</em> use dependencies retrieved from the request scope. When the request ends and its dependency scope is being closed, disposable dependencies will be properly disposed. For other threads, this would mean that their dependencies might end up getting disposed although they still need them: Bad idea.</p>
<p>Instead, you should explicitly open a new dependency scope for every thread you create. You can do that by injecting the <a href="https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.extensions.dependencyinjection.iservicescopefactory" rel="noreferrer"><code>IServiceScopeFactory</code></a> and creating a scope using <a href="https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.extensions.dependencyinjection.iservicescopefactory#Microsoft_Extensions_DependencyInjection_IServiceScopeFactory_CreateScope" rel="noreferrer"><code>CreateScope</code></a>. The resulting object will then contain a service provider which you can retrieve your dependencies from. Since this is a seperate scope, scoped dependencies like database contexts will be recreated for the lifetime of this scope.</p>
<p>In order to avoid getting into the service locator pattern, you should consider having one central service your thread executes that brings together all the necessary dependencies. The thread could then do this:</p>
<pre><code>using (var scope = _scopeFactory.CreateScope())
{
var service = scope.ServiceProvider.GetService<BackgroundThreadService>();
service.Run();
}
</code></pre>
<p>The <code>BackgroundThreadService</code> and all its dependency can then follow the common dependency injection way of receiving dependencies.</p> |
31,925,712 | Android getting an image from gallery comes rotated | <p>I am trying to let users select a profile picture from gallery. My issue is that some pictures come as rotated to the right.</p>
<p>I start the image picker like so:</p>
<pre><code>Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(photoPickerIntent, "Select profile picture"), Global.CODE_SELECT_PICTURE);
</code></pre>
<p>I get the image from onActivityResult like so:</p>
<pre><code>Uri selectedPicture = data.getData();
profilePic = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), selectedPicture);
</code></pre>
<p>How can i make have images not to be rotated?</p>
<p>UPDATE:</p>
<p>Following some of the helpful answers i have received, i managed to come up with the following working solution (It's just a working code, not well written). I would love to get your feedback on how i can improve it!</p>
<pre><code>public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == Global.CODE_SELECT_PICTURE) {
// Get selected gallery image
Uri selectedPicture = data.getData();
// Get and resize profile image
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = activity.getContentResolver().query(selectedPicture, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);
ExifInterface exif = null;
try {
File pictureFile = new File(picturePath);
exif = new ExifInterface(pictureFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = ExifInterface.ORIENTATION_NORMAL;
if (exif != null)
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
loadedBitmap = rotateBitmap(loadedBitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
loadedBitmap = rotateBitmap(loadedBitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
loadedBitmap = rotateBitmap(loadedBitmap, 270);
break;
}
}
}
public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
</code></pre> | 31,927,359 | 6 | 4 | null | 2015-08-10 17:31:27.437 UTC | 28 | 2021-02-24 02:17:11.173 UTC | 2016-03-03 20:17:48.833 UTC | null | 1,039,278 | null | 1,039,278 | null | 1 | 60 | android|android-gallery | 46,069 | <p>You could use <a href="http://developer.android.com/reference/android/media/ExifInterface.html" rel="noreferrer">ExifInterface</a> to modify the orientation:</p>
<pre><code>public static Bitmap modifyOrientation(Bitmap bitmap, String image_absolute_path) throws IOException {
ExifInterface ei = new ExifInterface(image_absolute_path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotate(bitmap, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotate(bitmap, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotate(bitmap, 270);
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
return flip(bitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
return flip(bitmap, false, true);
default:
return bitmap;
}
}
public static Bitmap rotate(Bitmap bitmap, float degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
public static Bitmap flip(Bitmap bitmap, boolean horizontal, boolean vertical) {
Matrix matrix = new Matrix();
matrix.preScale(horizontal ? -1 : 1, vertical ? -1 : 1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
</code></pre>
<p>In order to get absolute path of your images from their uri, check <a href="https://stackoverflow.com/a/20559175/1922137">this answer</a></p> |
50,605,327 | How to mock/spy an imported function in Angular unit testing | <p>Let's say i have an angular 6 component with a method <code>test</code> which returns some value:</p>
<pre><code>import { doSomething } from './helper';
@Component({
...
})
export class AppComponent {
test() {
const data = doSomething(1);
return data.something ? 1: 2;
}
}
</code></pre>
<p><code>doSomething</code> is just a simple helper function:</p>
<pre><code>export function doSomething() {
return { something: 1 };
}
</code></pre>
<p>Is it possible to mock or spy this function in a unit test (so i can control its returnValue)? Or do i have to change my approach in the component?</p>
<p>Please note: <code>doSomething()</code> can be a lodash function, a const, a class etc. I just tried to keep the example as simple as possible.</p>
<hr>
<p>Things i've tried:</p>
<ul>
<li><p><code>SpyOn</code> doesn't work because function is not attached to anything</p></li>
<li><p>Importing an mock-function into the <code>imports</code> array of <code>TestBed.configureTestingModule</code> gives <code>Unexpected value 'doSomething' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.</code></p></li>
<li><p>Creating a service for it works but it feels silly to have to create services for each imported function</p></li>
</ul> | 50,642,096 | 2 | 9 | null | 2018-05-30 12:56:41.91 UTC | 2 | 2021-07-14 12:29:49.693 UTC | 2020-07-27 09:36:33.46 UTC | null | 542,251 | null | 7,995,820 | null | 1 | 31 | javascript|angular|unit-testing|mocking|spy | 23,894 | <p>In your spec file import the helper this way:</p>
<pre><code>import * as helper from './helper';
</code></pre>
<p>And in your it() you can spy on the helper object and return the requested value: </p>
<pre><code>spyOn(helper, 'doSomething').and.returnValue({});
</code></pre> |
33,775,011 | How to annotate Count with a condition in a Django queryset | <p>Using Django ORM, can one do something like <code>queryset.objects.annotate(Count('queryset_objects', gte=VALUE))</code>. Catch my drift? </p>
<hr>
<p>Here's a quick example to use for illustrating a possible answer:</p>
<p>In a Django website, content creators submit articles, and regular users view (i.e. read) the said articles. Articles can either be published (i.e. available for all to read), or in draft mode. The models depicting these requirements are:</p>
<pre><code>class Article(models.Model):
author = models.ForeignKey(User)
published = models.BooleanField(default=False)
class Readership(models.Model):
reader = models.ForeignKey(User)
which_article = models.ForeignKey(Article)
what_time = models.DateTimeField(auto_now_add=True)
</code></pre>
<p><strong>My question is:</strong> How can I get all published articles, sorted by unique readership from the last 30 mins? I.e. I want to count how many distinct (unique) views each published article got in the last half an hour, and then produce a list of articles sorted by these distinct views.</p>
<hr>
<p>I tried:</p>
<pre><code>date = datetime.now()-timedelta(minutes=30)
articles = Article.objects.filter(published=True).extra(select = {
"views" : """
SELECT COUNT(*)
FROM myapp_readership
JOIN myapp_article on myapp_readership.which_article_id = myapp_article.id
WHERE myapp_readership.reader_id = myapp_user.id
AND myapp_readership.what_time > %s """ % date,
}).order_by("-views")
</code></pre>
<p>This sprang the error: <strong>syntax error at or near "01"</strong> (where "01" was the datetime object inside extra). It's not much to go on.</p> | 33,777,815 | 2 | 7 | null | 2015-11-18 08:28:41.197 UTC | 27 | 2019-05-25 10:35:13.583 UTC | 2017-03-17 19:50:50.033 UTC | null | 4,936,905 | null | 4,936,905 | null | 1 | 81 | python|django|django-queryset | 65,571 | <h3>For django >= 1.8</h3>
<p>Use <a href="https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/#conditional-aggregation" rel="noreferrer">Conditional Aggregation</a>:</p>
<pre><code>from django.db.models import Count, Case, When, IntegerField
Article.objects.annotate(
numviews=Count(Case(
When(readership__what_time__lt=treshold, then=1),
output_field=IntegerField(),
))
)
</code></pre>
<p><strong>Explanation:</strong>
normal query through your articles will be annotated with <code>numviews</code> field. That field will be constructed as a CASE/WHEN expression, wrapped by Count, that will return 1 for readership matching criteria and <code>NULL</code> for readership not matching criteria. Count will ignore nulls and count only values.</p>
<p>You will get zeros on articles that haven't been viewed recently and you can use that <code>numviews</code> field for sorting and filtering.</p>
<p>Query behind this for PostgreSQL will be:</p>
<pre><code>SELECT
"app_article"."id",
"app_article"."author",
"app_article"."published",
COUNT(
CASE WHEN "app_readership"."what_time" < 2015-11-18 11:04:00.000000+01:00 THEN 1
ELSE NULL END
) as "numviews"
FROM "app_article" LEFT OUTER JOIN "app_readership"
ON ("app_article"."id" = "app_readership"."which_article_id")
GROUP BY "app_article"."id", "app_article"."author", "app_article"."published"
</code></pre>
<p>If we want to track only unique queries, we can add distinction into <code>Count</code>, and make our <code>When</code> clause to return value, we want to distinct on.</p>
<pre><code>from django.db.models import Count, Case, When, CharField, F
Article.objects.annotate(
numviews=Count(Case(
When(readership__what_time__lt=treshold, then=F('readership__reader')), # it can be also `readership__reader_id`, it doesn't matter
output_field=CharField(),
), distinct=True)
)
</code></pre>
<p>That will produce:</p>
<pre><code>SELECT
"app_article"."id",
"app_article"."author",
"app_article"."published",
COUNT(
DISTINCT CASE WHEN "app_readership"."what_time" < 2015-11-18 11:04:00.000000+01:00 THEN "app_readership"."reader_id"
ELSE NULL END
) as "numviews"
FROM "app_article" LEFT OUTER JOIN "app_readership"
ON ("app_article"."id" = "app_readership"."which_article_id")
GROUP BY "app_article"."id", "app_article"."author", "app_article"."published"
</code></pre>
<h3>For django < 1.8 and PostgreSQL</h3>
<p>You can just use <code>raw</code> for executing SQL statement created by newer versions of django. Apparently there is no simple and optimized method for querying that data without using <code>raw</code> (even with <code>extra</code> there are some problems with injecting required <code>JOIN</code> clause).</p>
<pre><code>Articles.objects.raw('SELECT'
' "app_article"."id",'
' "app_article"."author",'
' "app_article"."published",'
' COUNT('
' DISTINCT CASE WHEN "app_readership"."what_time" < 2015-11-18 11:04:00.000000+01:00 THEN "app_readership"."reader_id"'
' ELSE NULL END'
' ) as "numviews"'
'FROM "app_article" LEFT OUTER JOIN "app_readership"'
' ON ("app_article"."id" = "app_readership"."which_article_id")'
'GROUP BY "app_article"."id", "app_article"."author", "app_article"."published"')
</code></pre> |
13,416,761 | How to remove or hide particular column in a datatable? | <p>I am using C#. I want to hide or remove the column from DataTable or DataSet . I attach my partial code:</p>
<pre><code>DataTable dt = new DataTable();
DataView dv = new DataView();
dv = (DataView)Session["map_hi"];
dt = dv.ToTable();
dt.Columns[0].ColumnMapping = MappingType.Hidden;
dt.AcceptChanges();
</code></pre> | 13,416,799 | 4 | 1 | null | 2012-11-16 12:39:46.693 UTC | 2 | 2020-12-29 00:58:34.547 UTC | 2012-11-16 12:42:50.027 UTC | null | 64,976 | null | 1,315,290 | null | 1 | 9 | c# | 41,545 | <p>try this </p>
<pre><code> DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
</code></pre> |
13,621,998 | How to send redirect to JSP page in Servlet | <p>When I'm done processing in a servlet, and the result is valid, then I need to redirect the response to another JSP page, say <code>welcome.jsp</code> in web content folder. How can I do it?</p>
<p>For example:</p>
<pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// Some processing code here ...
// How do I redirect to another JSP here when I'm ready?
} catch (Exception e) {
throw new ServletException(e);
}
}
</code></pre> | 13,622,320 | 3 | 0 | null | 2012-11-29 08:55:19.513 UTC | 8 | 2019-09-19 09:30:34.207 UTC | 2019-09-19 09:28:11.967 UTC | null | 157,882 | null | 1,835,784 | null | 1 | 29 | jsp|redirect|servlets | 153,564 | <p>Look at the <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpServletResponse.html#sendRedirect-java.lang.String-" rel="noreferrer"><code>HttpServletResponse#sendRedirect(String location)</code></a> method. </p>
<p>Use it as:</p>
<pre><code>response.sendRedirect(request.getContextPath() + "/welcome.jsp")
</code></pre>
<p>Alternatively, look at <a href="https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpServletResponse.html#setHeader-java.lang.String-java.lang.String-" rel="noreferrer"><code>HttpServletResponse#setHeader(String name, String value)</code></a> method.</p>
<p>The redirection is set by adding the location header:</p>
<pre><code>response.setHeader("Location", request.getContextPath() + "/welcome.jsp");
</code></pre> |
13,502,733 | "Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application | <p>I'm setting up a pretty simple app with backbone, and I'm getting an error.</p>
<pre><code>Uncaught TypeError: undefined is not a function example_app.js:7
ExampleApp.initialize example_app.js:7
(anonymous function)
</code></pre>
<p>This is where the error is showing up in Chrome Inspector (init file - example_app.js):</p>
<pre><code>var ExampleApp = {
Models: {},
Collections: {},
Views: {},
Routers: {},
initialize: function() {
var tasks = new ExampleApp.Collections.Tasks(data.tasks);
new ExampleApp.Routers.Tasks({ tasks: tasks });
Backbone.history.start();
}
};
</code></pre>
<p>Here's my tasks index.haml file</p>
<pre><code>- content_for :javascript do
- javascript_tag do
ExampleApp.initialize({ tasks: #{raw @tasks.to_json} });
= yield :javascript
</code></pre>
<p>models / task.js</p>
<pre><code>var Task = Backbone.Model.extend({});
</code></pre>
<p>collections / tasks.js</p>
<pre><code>var Tasks = Backbone.Collection.extend({
model: Task,
url: '/tasks'
});
</code></pre>
<p>routers / tasks.js</p>
<pre><code>ExampleApp.Routers.Tasks = Backbone.Router.extend({
routes: {
"": "index"
},
index: function() {
alert('test');
// var view = new ExampleApp.Views.TaskIndex({ collection: ExampleApp.tasks });
// $('body').html(view.render().$el);
}
});
</code></pre>
<p>And here's proof that I'm calling all of the files (I think):</p>
<pre><code><script src="/assets/jquery.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery-ui.js?body=1" type="text/javascript"></script>
<script src="/assets/underscore.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone-support/support.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone-support/composite_view.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone-support/swapping_router.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone-support.js?body=1" type="text/javascript"></script>
<script src="/assets/example_app.js?body=1" type="text/javascript"></script>
<script src="/assets/easing.js?body=1" type="text/javascript"></script>
<script src="/assets/modernizr.js?body=1" type="text/javascript"></script>
<script src="/assets/models/task.js?body=1" type="text/javascript"></script>
<script src="/assets/collections/tasks.js?body=1" type="text/javascript"></script>
<script src="/assets/views/task_view.js?body=1" type="text/javascript"></script>
<script src="/assets/views/tasks.js?body=1" type="text/javascript"></script>
<script src="/assets/views/tasks_index.js?body=1" type="text/javascript"></script>
<script src="/assets/routers/tasks.js?body=1" type="text/javascript"></script>
<script src="/assets/tasks/index.js?body=1" type="text/javascript"></script>
<script src="/assets/tasks/task.js?body=1" type="text/javascript"></script>
<script src="/assets/application.js?body=1" type="text/javascript"></script>
</code></pre>
<p>Any ideas would be great. Thanks!</p> | 13,504,238 | 4 | 4 | null | 2012-11-21 22:00:37.32 UTC | 12 | 2021-12-09 15:30:31.133 UTC | 2012-11-22 00:15:00.573 UTC | null | 895,453 | null | 895,453 | null | 1 | 44 | javascript|ruby-on-rails|ruby-on-rails-3|backbone.js | 210,601 | <blockquote>
<p>Uncaught TypeError: undefined is not a function example_app.js:7</p>
</blockquote>
<p>This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's <code>undefined</code>.</p>
<p>So what's on <code>example_app.js</code> line 7? Looks like this:</p>
<pre><code>var tasks = new ExampleApp.Collections.Tasks(data.tasks);
</code></pre>
<p>There is only one function being run on that line. We found the problem! <code>ExampleApp.Collections.Tasks</code> is <code>undefined</code>.</p>
<p>So lets look at where that is declared:</p>
<pre><code>var Tasks = Backbone.Collection.extend({
model: Task,
url: '/tasks'
});
</code></pre>
<p>If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called <code>Tasks</code>. But you never add it to the <code>ExampleApp.Collections</code> object, a place you later expect it to be.</p>
<p>Change that to this, and I bet you'd be good.</p>
<pre><code>ExampleApp.Collections.Tasks = Backbone.Collection.extend({
model: Task,
url: '/tasks'
});
</code></pre>
<p>See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.</p>
<hr>
<p>In Javascript, when you execute a function, it's evaluated like:</p>
<pre><code>expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does
</code></pre>
<p>That expression can be complex. So when you see <code>undefined is not a function</code> it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.</p>
<p>And in this case, it was because you didn't put something where you thought you did.</p> |
13,551,829 | Escape percent in bat file | <p>I was trying to write a VPN dialer/disconnector using a batch file, but I got stuck. After some investigation I found that the presence of <code>%</code> in the password is not playing well.</p>
<p>Here is the code</p>
<pre><code>@echo OFF
SET SWITCHPARSE1=%1
SET SWITCHPARSE2=%2
REM echo %SWITCHPARSE1%
SHIFT
SHIFT
IF "SWITCHPARSE1" == "" goto Usage
IF "SWITCHPARSE1" == "/?" goto Usage
IF "SWITCHPARSE2" == "" goto Usage
IF "SWITCHPARSE2" == "/?" goto Usage
IF "%SWITCHPARSE1%" == "sl" (
IF "%SWITCHPARSE2%" == "conn" (
echo "inside sl conn"
rasdial sl employee1 K%%Pxev3=)g:{#Swc9
goto end
) ELSE IF "%SWITCHPARSE2%" == "disconn" (
rasdial sl /disconnect
goto end
) ELSE (
goto Usage
)
) ELSE IF "%SWITCHPARSE1%" == "off" (
IF "%SWITCHPARSE2%" == "conn" (
rasdial Office employee1 office123
goto end
) ELSE IF "%SWITCHPARSE2%" == "disconn" (
rasdial Office /disconnect
goto end
) ELSE (
goto Usage
)
) ELSE (
goto Usage
)
:Usage
echo "Usage is vpnconn.bat /[sl|off] /[conn|disconn]"
:end
</code></pre>
<p>In the above script I am trying to escape <code>%</code> using <code>%</code> (i.e. <code>%%</code>, reference from <a href="http://www.robvanderwoude.com/escapechars.php" rel="noreferrer">here</a>), but the bat script gives <strong>g:{#Swc9 was unexpected at this time.</strong>.</p>
<p>To root cause further, I tried to double <code>%%</code> (escape <code>%</code>) in a different batch file, and it worked:</p>
<pre><code>@echo OFF
rasdial sl employee1 K%%Pxev3=)g:{#Swc9
</code></pre>
<p>Why does the same script when integrated to work with different connections not work?</p> | 13,552,702 | 1 | 1 | null | 2012-11-25 14:16:22.147 UTC | 4 | 2020-10-11 15:20:52.423 UTC | 2020-10-11 15:20:52.423 UTC | null | 5,047,996 | null | 129,206 | null | 1 | 67 | windows|batch-file|cmd|escaping | 41,542 | <p>Two <strong>%%</strong> equals to one <strong>%</strong>. That's right (but only in a script, not directly in the cmd), no need to use the escape operator <strong>^</strong>.</p>
<p>But you are missing the agrupation operator <strong>)</strong>. That's the problem; the IF closes when it finds the <strong>)</strong> at your command.</p>
<p>Use this:</p>
<pre><code>rasdial sl employee1 K%%%%Pxev3=^)g:{#Swc9
</code></pre> |
20,800,088 | Global Variable in Userform | <p>I search about this in the forum and found some answers but did not work for me.</p>
<p>I have two UserForms.</p>
<p>In the first one, I give a value to a variable called Word.</p>
<p>In the second one, I have a Label that I need the caption to become the variable Word.</p>
<p>Example:</p>
<pre><code>Public Word as String
Private Sub Userform1_Activate
Word = "Today Is Saturday"
End Sub
Private Sub Userform2_Activate
Label1.Caption = Word
End Sub
</code></pre>
<p>But this does not work. The Label caption gets Zero for value.
Could anybody help me on this?</p>
<p>Thanks.</p>
<pre><code>First Form
Private Sub CommandButton5_Click()
Db = "C:\Users\Desktop\db.txt"
Set File1 = CreateObject("Scripting.FileSystemObject")
Set File2 = File1.OpenTextFile(Db, 1)
Do Until File2.AtEndOfStream
If (File2.Readline = TextBox1) Then Exit Do
If File2.AtEndOfStream Then WordNotFound.Show
If File2.AtEndOfStream Then TextBox1.Value = ""
If File2.AtEndOfStream Then Exit Sub
Loop
Word = File2.Readline
MsgBox Word
TextBox1.Value = ""
End Sub
</code></pre>
<p>Second Form</p>
<pre><code>Private Sub UserForm_Click()
Label1.Caption = Word
End Sub
</code></pre> | 20,800,471 | 1 | 3 | null | 2013-12-27 11:41:52.917 UTC | 1 | 2013-12-27 12:20:27.643 UTC | 2013-12-27 12:18:58.007 UTC | null | 2,682,736 | null | 2,682,736 | null | 1 | 3 | vba|global-variables|userform | 53,432 | <p>As I said in my comment, that your method should work. Here is the test code that I tried</p>
<p>1- In <code>Module1</code></p>
<pre><code>Public Word As String
</code></pre>
<p>2- Create 2 user forms - <code>UserForm1</code> and <code>UserForm2</code></p>
<p>2a- In UserForm1</p>
<pre><code>Private Sub UserForm_Activate()
Word = "This is Saturday"
End Sub
</code></pre>
<p>2b- In UserForm2</p>
<pre><code>Private Sub UserForm_Activate()
Label1.Caption = Word
End Sub
</code></pre>
<p>3- Then in <code>ThisWorkbook</code></p>
<pre><code>Private Sub Workbook_Open()
UserForm1.Show
UserForm2.Show
End Sub
</code></pre>
<p>So when you close UserForm1, the UserForm2 would be displayed as below</p>
<p><img src="https://i.stack.imgur.com/xOuSr.jpg" alt="enter image description here"></p> |
9,553,162 | What is the "cut-and-paste" proof technique? | <p>I've seen references to <em>cut-and-paste</em> proofs in certain texts on algorithms analysis and design. It is often mentioned within the context of Dynamic Programming when proving <em>optimal substructure</em> for an optimization problem (See Chapter 15.3 CLRS). It also shows up on graphs manipulation.</p>
<p>What is the main idea of such proofs? How do I go about using them to prove the correctness of an algorithm or the convenience of a particular approach?</p> | 9,553,252 | 5 | 2 | null | 2012-03-04 07:29:07.09 UTC | 12 | 2022-06-04 08:01:40.917 UTC | 2018-10-17 17:55:55.147 UTC | null | 1,451,787 | null | 214,849 | null | 1 | 34 | algorithm|math|dynamic-programming | 12,275 | <p>The term "cut and paste" shows up in algorithms sometimes when doing dynamic programming (and other things too, but that is where I first saw it). The idea is that in order to use dynamic programming, the problem you are trying to solve probably has some kind of underlying redundancy. You use a table or similar technique to avoid solving the same optimization problems over and over again. Of course, before you start trying to use dynamic programming, it would be nice to prove that the problem has this redundancy in it, otherwise you won't gain anything by using a table. This is often called the "optimal subproblem" property (e.g., in CLRS). </p>
<p>The "cut and paste" technique is a way to prove that a problem has this property. In particular, you want to show that when you come up with an optimal solution to a problem, you have necessarily used optimal solutions to the constituent subproblems. The proof is by contradiction. Suppose you came up with an optimal solution to a problem by using suboptimal solutions to subproblems. Then, if you were to replace ("cut") those suboptimal subproblem solutions with optimal subproblem solutions (by "pasting" them in), you would improve your optimal solution. But, since your solution was optimal by assumption, you have a contradiction. There are some other steps involved in such a proof, but that is the "cut and paste" part.</p> |
9,105,505 | Differences between Just in Time compilation and On Stack Replacement | <p>Both of them pretty much do the same thing. Identify that the method is hot and compile it instead of interpreting. With OSR, you just move to the compiled version right after it gets compiled, unlike with JIT, where the compiled code gets called when the method is called for the second time. </p>
<p>Other than this, are there any other differences?</p> | 9,105,846 | 2 | 2 | null | 2012-02-02 00:29:39.987 UTC | 16 | 2019-10-28 13:21:30.08 UTC | 2015-06-14 09:41:15.57 UTC | null | 317,266 | null | 374,499 | null | 1 | 56 | java|compiler-construction|jvm|jit|vm-implementation | 10,646 | <p>In general, <em>Just-in-time</em> compilation refers to compiling native code at runtime and executing it instead of (or in addition to) interpreting. Some VMs, such as Google V8, don't even have an interpreter; they JIT compile every function that gets executed (with varying degrees of optimization).</p>
<p>On Stack Replacement (OSR) is a technique for switching between different implementations of the same function. For example, you could use OSR to switch from interpreted or unoptimized code to JITed code as soon as it finishes compiling.</p>
<p>OSR is useful in situations where you identify a function as "hot" while it is running. This might not necessarily be because the function gets called frequently; it might be called only once, but it spends a lot of time in a big loop which could benefit from optimization. When OSR occurs, the VM is paused, and the stack frame for the target function is replaced by an equivalent frame which may have variables in different locations. </p>
<p>OSR can also occur in the other direction: from optimized code to unoptimized code or interpreted code. Optimized code may make some assumptions about the runtime behavior of the program based on past behavior. For instance, you could convert a virtual or dynamic method call into a static call if you've only ever seen one type of receiver object. If it turns out later that these assumptions were wrong, OSR can be used to fall back to a more conservative implementation: the optimized stack frame gets converted into an unoptimized stack frame. If the VM supports inlining, you might even end up converting an optimized stack frame into <em>several</em> unoptimized stack frames.</p> |
16,425,260 | Changing a links href after click with jQuery | <p>I am trying to create a link that when clicked on, switches its href attribute, and then goes to that location.</p>
<p>My html is:</p>
<pre><code><a href="http://google.com" rel="group" data-wpurl="http://yahoo.com"></a>
</code></pre>
<p>When clicked, I would like the browser to go to the data-wpurl location, not href location. The reason I am using a data attribute is because of the application I am using requires use of the href...not relevant here.</p>
<p>My jQuery is:</p>
<pre><code>$('a[rel="group"]').on('click', function(e) {
e.preventDefault();
var wpurl = $(this).attr("data-wpurl");
$(this).attr('href', wpurl);
});
</code></pre>
<p>I am using e.preventDefault(); to prevent the browser from taking the user to the href. After the data attribute is assigned to the href, how do I then trigger a click? Using <code>trigger('click')</code> and <code>click();</code> do not work!</p>
<p>Any ideas?</p> | 16,425,288 | 4 | 2 | null | 2013-05-07 17:40:14.193 UTC | 2 | 2015-09-07 13:03:36.81 UTC | null | null | null | null | 121,630 | null | 1 | 23 | jquery|attributes | 51,367 | <p>It would be easier to just change the location immediately:</p>
<pre><code>e.preventDefault();
location.href = $(this).data('wpurl');
</code></pre> |
16,102,436 | what are the values in _ga cookie? | <p>I am using <a href="https://support.google.com/analytics/answer/2790010?hl=en&ref_topic=2790009">universal analytics</a>. universal analytics creates first party cookie <code>_ga</code></p>
<pre><code> _ga=1.2.286403989.1366364567;
</code></pre>
<p>286403989 is clientId</p>
<p>1366364567 is timestamp</p>
<p>what is <code>1</code> and <code>2</code> in _ga cookie?</p> | 16,107,194 | 3 | 1 | null | 2013-04-19 10:22:10.99 UTC | 33 | 2019-11-21 09:38:24.597 UTC | 2014-09-04 05:05:48.147 UTC | null | 2,147,188 | null | 2,147,188 | null | 1 | 63 | cookies|google-analytics|analytics|web-analytics|analytics.js | 93,148 | <pre><code>_ga=1.2.286403989.1366364567;
</code></pre>
<h2>1st Field</h2>
<p>This is a versioning number. In case the cookie format changes in the future. Seems to be fixed at 1 at the moment. The one above is an old format. Newer cookies have this value set at "GA1"</p>
<h2>2nd Field</h2>
<p>This field is used to figure out the correct cookie in case multiple cookies are setup in different paths or domains.</p>
<p>By default cookie are setup at path <code>/</code> and at the domain on document.location.hostname (with the www. prefix removed).</p>
<p>You could have a _ga cookie set at sub.example.com and another cookie set at example.com. Because the way the cookie API on browsers works there's no way to tell which is the correct cookie you use.</p>
<p>So the second number is the number of components (dot separated) at the domain.</p>
<ul>
<li>for sub.example.com the number would be 3</li>
<li>for example.com the number would be 2</li>
</ul>
<p>The path defaults to <code>/</code> but you can also change it by passing the <code>cookiePath</code> option to the <code>ga.create</code> method. If you pass it this field becomes 2 numbers dash separated. And the second number is the number slashes in the path.</p>
<p>Using these numbers the analytics.js script can correctly identify the cookie to be used in case there are multiple cookies set.</p>
<p>eg:
Imagine that you have a site that lives at sub1.sub2.example.com/folder1 in case you want to store the cookie only on your site and not make it visible to other subdomains or folders you can use the following configs:</p>
<pre><code>ga('create', 'UA-XXXX-Y', {
'cookiePath': '/folder1/',
'cookieDomain': 'sub1.sub2.example.com'
});
</code></pre>
<p>In this case the cookie will look somoething like this;</p>
<pre><code>_ga=1.4-2.XXXXXXXX.YYYYYYY
</code></pre>
<h2>3rd Field</h2>
<p>This is a random generated user ID. Used to identify different users.</p>
<h2>4th Field</h2>
<p>It's a timestamp of the first time the cookie was set for that user.</p>
<pre><code>new Date(1366364567*1000)
> Fri Apr 19 2013 06:42:47 GMT-0300 (BRT)
</code></pre>
<p>This is also used to uniquely identify users in case of userId collisions.</p>
<p>Worth mentioning that a cookie is not an API. In the future it may completely change. Google doesn't recommend reading/writing the _ga cookie directly. You should interact with Google Analytics through one of the tracking libraries such as analytics.js. There's not a lot of use for this information other than curiosity.</p>
<p>If you are reading/writing directly the cookie you are doing it wrong.</p> |
58,260,465 | Unexpected exec permission from mmap when assembly files included in the project | <p>I am banging my head into the wall with this.</p>
<p>In my project, when I'm allocating memory with <code>mmap</code> the mapping (<code>/proc/self/maps</code>) shows that it is an readable and executable region <strong>despite</strong> I requested only readable memory.</p>
<p>After looking into strace (which was looking good) and other debugging, I was able to identify the only thing that seems to avoid this strange problem: removing assembly files from the project and leaving only pure C. (what?!)</p>
<p>So here is my strange example, I am working on Ubunbtu 19.04 and default gcc.</p>
<p>If you compile the target executable with the ASM file (which is empty) then <code>mmap</code> returns a readable and executable region, if you build without then it behave correctly. See the output of <code>/proc/self/maps</code> which I have embedded in my example.</p>
<p><strong>example.c</strong></p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
int main()
{
void* p;
p = mmap(NULL, 8192,PROT_READ,MAP_ANONYMOUS|MAP_PRIVATE,-1,0);
{
FILE *f;
char line[512], s_search[17];
snprintf(s_search,16,"%lx",(long)p);
f = fopen("/proc/self/maps","r");
while (fgets(line,512,f))
{
if (strstr(line,s_search)) fputs(line,stderr);
}
fclose(f);
}
return 0;
}
</code></pre>
<p><strong>example.s</strong>: Is an empty file!</p>
<p><strong>Outputs</strong></p>
<p>With the ASM included version</p>
<pre><code>VirtualBox:~/mechanics/build$ gcc example.c example.s -o example && ./example
7f78d6e08000-7f78d6e0a000 r-xp 00000000 00:00 0
</code></pre>
<p>Without the ASM included version</p>
<pre><code>VirtualBox:~/mechanics/build$ gcc example.c -o example && ./example
7f1569296000-7f1569298000 r--p 00000000 00:00 0
</code></pre> | 58,260,711 | 2 | 5 | null | 2019-10-06 19:13:05.987 UTC | 12 | 2021-10-08 04:08:34.143 UTC | 2021-10-08 03:13:30.45 UTC | null | 224,132 | null | 3,948,912 | null | 1 | 102 | c|linux|assembly|mmap|dep | 3,380 | <p>Linux has an <a href="http://man7.org/linux/man-pages/man2/personality.2.html" rel="nofollow noreferrer">execution domain</a> called <code>READ_IMPLIES_EXEC</code>, which causes all pages allocated with <code>PROT_READ</code> to also be given <code>PROT_EXEC</code>. Older Linux kernels <a href="https://stackoverflow.com/questions/64833715/linux-default-behavior-of-executable-data-section-changed-between-5-4-and-5-9">used to use this</a> for executables that used the equivalent of <code>gcc -z execstack</code>. This program will show you whether that's enabled for itself:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <sys/personality.h>
int main(void) {
printf("Read-implies-exec is %s\n", personality(0xffffffff) & READ_IMPLIES_EXEC ? "true" : "false");
return 0;
}
</code></pre>
<p>If you compile that along with an empty <code>.s</code> file, you'll see that it's enabled, but without one, it'll be disabled. The initial value of this <a href="https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/fs/binfmt_elf.c?h=v5.3.4#n874" rel="nofollow noreferrer">comes from the ELF meta-information in your binary</a>. Do <code>readelf -Wl example</code>. You'll see this line when you compiled without the empty <code>.s</code> file:</p>
<pre class="lang-none prettyprint-override"><code> GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10
</code></pre>
<p>But this one when you compiled with it:</p>
<pre class="lang-none prettyprint-override"><code> GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RWE 0x10
</code></pre>
<p>Note <code>RWE</code> instead of just <code>RW</code>. The reason for this is that the linker assumes that your assembly files require read-implies-exec unless it's explicitly told that they don't, and if any part of your program requires read-implies-exec, then it's enabled for your whole program. The assembly files that GCC compiles tell it that it doesn't need this, with this line (you'll see this if you compile with <code>-S</code>):</p>
<pre class="lang-none prettyprint-override"><code> .section .note.GNU-stack,"",@progbits
</code></pre>
<p>The default section permissions don't include e<code>x</code>ec. See the ELF part of the <a href="https://sourceware.org/binutils/docs/as/Section.html" rel="nofollow noreferrer"><code>.section</code> documentation</a> for the meaning of the "flags" and @attributes.</p>
<p>(And don't forget to switch to another section like <code>.text</code> or <code>.data</code> after that <code>.section</code> directive, if your <code>.s</code> was relying on <code>.text</code> because the default section at the top of the file.)</p>
<p>Put that line in <code>example.s</code> (and every other <code>.s</code> file in your project). The presence of that <code>.note.GNU-stack</code> section will serve to tell the linker that this object file doesn't depend on an executable stack, so the linker will use <code>RW</code> instead of <code>RWE</code> on the <code>GNU_STACK</code> metadata, and your program will then work as expected.</p>
<p>Similarly <a href="https://stackoverflow.com/questions/7863200/why-data-and-stack-segments-are-executable">for NASM</a>, a <code>section</code> directive with the right flags specifies non-executable stacks.</p>
<hr />
<p><strong>Modern Linux kernels between 5.4 and 5.8 changed the behaviour</strong> of the ELF program-loader. For x86-64, nothing turns on <code>READ_IMPLIES_EXEC</code> anymore. At most (with an RWE <code>GNU_STACK</code> added by <code>ld</code>), you'll get the stack itself being executable, not every readable page. (<a href="http://man7.org/linux/man-pages/man2/personality.2.html" rel="nofollow noreferrer">This answer</a> covers the last change, in 5.8, but there must have been other changes before that, since that question shows successful execution of code in <code>.data</code> on x86-64 Linux 5.4)</p>
<p><code>exec-all</code> (<code>READ_IMPLIES_EXEC</code>) only happens for legacy 32-bit executables where the linker didn't add a <code>GNU_STACK</code> header entry at all. But as shown here, modern <code>ld</code> always adds that with one setting or the other, even when an input <code>.o</code> file is missing a note.</p>
<p>You should still use this <code>.note</code> section to signal non-executable stacks in normal programs. But if you were hoping to test self-modifying code in <code>.data</code> or following some old tutorial for <a href="https://stackoverflow.com/questions/9960721/how-to-get-c-code-to-execute-hex-machine-code">testing shellcode</a>, that's not an option on modern kernels.</p> |
17,589,008 | excel charts not accepting date-time series in x axis | <p>How to make excel accept the following as different data points on the x-axis.<br></p>
<pre><code> Time Licenses Used
2013-07-09 11:34 512
2013-07-09 11:36 523
2013-07-09 11:40 621
2013-07-09 11:43 125
2013-07-10 09:30 526
2013-07-10 10:30 589
2013-07-10 11:30 546
2013-07-11 10:40 549
</code></pre>
<p>Why does Excel charts club all the times on a date together, why cant it interpret it a different time entries?</p> | 17,589,507 | 2 | 3 | null | 2013-07-11 08:49:22.927 UTC | 1 | 2013-07-11 09:14:04.027 UTC | null | null | null | null | 1,288,207 | null | 1 | 14 | excel | 74,419 | <p>if you are using a line chart, change to an XY scatter chart with lines instead; a date axis on a line chart will ignore the time portion</p> |
27,190,447 | pass JSON to HTTP POST Request | <p>I'm trying to make a HTTP POST request to the google QPX Express API [1] using <strong><em>nodejs</em></strong> and <strong><em>request</em></strong> [2].</p>
<p>My code looks as follows:</p>
<pre><code> // create http request client to consume the QPX API
var request = require("request")
// JSON to be passed to the QPX Express API
var requestData = {
"request": {
"slice": [
{
"origin": "ZRH",
"destination": "DUS",
"date": "2014-12-02"
}
],
"passengers": {
"adultCount": 1,
"infantInLapCount": 0,
"infantInSeatCount": 0,
"childCount": 0,
"seniorCount": 0
},
"solutions": 2,
"refundable": false
}
}
// QPX REST API URL (I censored my api key)
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=myApiKey"
// fire request
request({
url: url,
json: true,
multipart: {
chunked: false,
data: [
{
'content-type': 'application/json',
body: requestData
}
]
}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body)
}
else {
console.log("error: " + error)
console.log("response.statusCode: " + response.statusCode)
console.log("response.statusText: " + response.statusText)
}
})
</code></pre>
<p>What I'm trying to do is passing the JSON using the multipart argument [3].
But instead of the proper JSON response I got an error (400 undefined).</p>
<p>When I make a request using the same JSON and API Key using CURL instead, it works fine. So there's nothing wrong with my API key or JSON.</p>
<p>What's wrong with my code?</p>
<p><strong>EDIT</strong>:</p>
<p>working CURL example:</p>
<p>i) I saved the JSON which I would pass to my request into a file called "request.json":</p>
<pre><code>{
"request": {
"slice": [
{
"origin": "ZRH",
"destination": "DUS",
"date": "2014-12-02"
}
],
"passengers": {
"adultCount": 1,
"infantInLapCount": 0,
"infantInSeatCount": 0,
"childCount": 0,
"seniorCount": 0
},
"solutions": 20,
"refundable": false
}
}
</code></pre>
<p>ii) then, in the terminal I switched to the directory in which the newly created request.json file was located and run (myApiKey stands for my actual API Key obviously):</p>
<pre><code>curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=myApiKey
</code></pre>
<p>[1] <a href="https://developers.google.com/qpx-express/" rel="noreferrer">https://developers.google.com/qpx-express/</a>
[2] a http request client designed for nodejs: <a href="https://www.npmjs.org/package/request" rel="noreferrer">https://www.npmjs.org/package/request</a>
[3] here is an example I found <a href="https://www.npmjs.org/package/request#multipart-related" rel="noreferrer">https://www.npmjs.org/package/request#multipart-related</a>
[4] <a href="https://stackoverflow.com/questions/27179248/qpx-express-api-is-returning-400-parse-error">QPX Express API is returning 400 parse error</a></p> | 27,190,736 | 9 | 7 | null | 2014-11-28 14:08:10.117 UTC | 25 | 2020-01-15 04:32:15.597 UTC | 2017-05-23 11:47:16.49 UTC | null | -1 | null | 4,023,065 | null | 1 | 99 | json|node.js|curl|express|node-request | 257,085 | <p>I think the following should work:</p>
<pre><code>// fire request
request({
url: url,
method: "POST",
json: requestData
}, ...
</code></pre>
<p>In this case, the <code>Content-type: application/json</code> header is automatically added.</p> |
21,520,475 | Same workspace for multiple jobs | <p>I have a job called "development" and another project called "code analysis". At the moment we have two different jobs and different workspaces, but same code; is there any way we could use the same workspace for multiple jobs?<br>I checked the plugins available in Jenkins but I haven't found any suitable one. </p> | 21,522,646 | 4 | 3 | null | 2014-02-03 05:41:02.537 UTC | 21 | 2019-10-02 18:58:40.977 UTC | 2017-01-23 13:43:05.817 UTC | null | 4,715,957 | null | 1,599,758 | null | 1 | 77 | jenkins|jenkins-plugins|jenkins-cli | 77,554 | <p>Suppose your "development" Jenkins job workspace is <code>/var/workspace/job1</code>. In the "code analysis" job configuration page, under the tab <code>General</code> click on <code>Advanced...</code> and select the option <code>Use custom workspace</code> and give the same workspace <code>/var/workspace/job1</code> as of your "development" job. </p> |
17,338,652 | Is there a Java equivalent of SignalR? | <p>I've got a really simple question but I find nothing interesting on Google. </p>
<p>Is there a Java equivalent of SignalR (.NET) ?</p>
<p>SignalR is a .NET framework that implements Websockets with a fallback for old browsers.</p>
<p>Really thx to you.</p> | 20,753,033 | 2 | 2 | null | 2013-06-27 08:47:46.713 UTC | 10 | 2018-06-05 14:22:32.657 UTC | 2015-09-24 13:48:57.177 UTC | null | 1,061,499 | null | 1,934,884 | null | 1 | 29 | java|websocket|signalr | 38,231 | <p>It seems that <a href="https://github.com/Atmosphere/atmosphere">Atmosphere</a> can be this what you are looking for.</p>
<p>From github description:</p>
<blockquote>
<p>The Atmosphere Framework contains client and server side components
for building Asynchronous Web Application.</p>
</blockquote>
<p>I didn't tried it yet, but <a href="https://github.com/Atmosphere/atmosphere/wiki/Supported-WebServers-and-Browsers">this</a> says that it supports major JEE-Servers (JBoss, Tomcat, Glassfish, Jetty) and all major browsers and transports (WebSockets, SSE, Long-Polling etc).</p>
<p><strong>UPDATE 6/4/2014:</strong>
There is another notable alternative for "Java equivalent of SignalR". As of version 4.0, Spring Framework comes with <a href="http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#websocket">support for WebSockets</a> and server-side support for the SockJS. It means that it supports also WebSocket-Fallback, used together with a browser side <a href="https://github.com/sockjs/sockjs-client">sockjs-client</a> library.
As Spring Documentation says: </p>
<blockquote>
<p>WebSocket is not supported in all browsers yet and may be precluded by restrictive network proxies. This is why Spring provides fallback options that emulate the WebSocket API as close as possible based on the SockJS protocol [...] On the browser side, applications can use the sockjs-client that emulates the W3C WebSocket API and communicates with the server to select the best transport option depending on the browser it’s running in.</p>
</blockquote>
<p>Still I'm not aware if there is support for something like SignalR Hubs (which involves JavaScript-code generation)in the Java Framework as of today, but on the other side I think you can easily imitate a SignalR-like PersistentConnection with full fallback support for older browsers.</p>
<p>Furthermore, because of <a href="http://www.oracle.com/technetwork/articles/java/jsr356-1937161.html">JSR 356</a> aka Java API for WebSocket, I think it is only a question of time when the so to say "mainstream" Java Web-frameworks will be shipped with out-of-the-box support for Websockets+Fallback, especially considering the fact that all main servlet conteiners (like Tomcat and Jetty) and JEE 7 Servers (Glassfish, Wildfly) have support for JSR 356 already.</p> |
17,431,338 | Optimistic locking in MySQL | <p>I can't find any details on optimistic locking in MySQL.
I read that starting a transaction keep updates on two entities synced, however - it doesn't stop two users updating the data at the same time causing a conflict.</p>
<p>Apparently optimistic locking will solve this issue? How is this applied in MySQL. Is there SQL syntax / keyword for this? Or does MySQL have default behavior?</p>
<p>Thanks guys.</p> | 18,806,907 | 1 | 0 | null | 2013-07-02 16:52:16.577 UTC | 62 | 2022-03-07 04:28:06.717 UTC | null | null | null | null | 1,784,109 | null | 1 | 61 | mysql|sql|locking|database|optimistic | 31,668 | <p>The point is that Optimistic Locking is not a database feature, not for MySQL nor for others: optimistic locking is a practice that is applied using the DB with standard instructions.</p>
<p>Let's have a very simple example and say that you want to do this in a code that multiple users/clients can run concurrently:</p>
<ol>
<li>SELECT data from a row having one ID field (iD) and two data fields (val1, val2)</li>
<li>optionally do your calculations with data</li>
<li>UPDATE data of that row</li>
</ol>
<h2>The NO LOCKING way to is:</h2>
<p>NOTE: all code {between curly brackets} is intended to be in the app code and not (necessarily) in the SQL side</p>
<pre><code>- SELECT iD, val1, val2
FROM theTable
WHERE iD = @theId;
- {code that calculates new values}
- UPDATE theTable
SET val1 = @newVal1,
val2 = @newVal2
WHERE iD = @theId;
- {go on with your other code}
</code></pre>
<h2>The OPTIMISTIC LOCKING way is:</h2>
<pre><code>- SELECT iD, val1, val2
FROM theTable
WHERE iD = @theId;
- {code that calculates new values}
- UPDATE theTable
SET val1 = @newVal1,
val2 = @newVal2
WHERE iD = @theId
AND val1 = @oldVal1
AND val2 = @oldVal2;
- {if AffectedRows == 1 }
- {go on with your other code}
- {else}
- {decide what to do since it has gone bad... in your code}
- {endif}
</code></pre>
<p>Note that the key point is in the structure of the UPDATE instruction and the subsequent number of affected rows check. It is these two things together that let your code realize that someone has already modified the data in between when you have executed the SELECT and UPDATE.
Notice that all has been done without transactions! This has been possible (absence of transactions) only because this is a very simple example but this tells also that the key point for Optimistic locking is not in transactions themselves.</p>
<h2>What about TRANSACTIONS then?</h2>
<pre><code> - SELECT iD, val1, val2
FROM theTable
WHERE iD = @theId;
- {code that calculates new values}
- BEGIN TRANSACTION;
- UPDATE anotherTable
SET col1 = @newCol1,
col2 = @newCol2
WHERE iD = @theId;
- UPDATE theTable
SET val1 = @newVal1,
val2 = @newVal2
WHERE iD = @theId
AND val1 = @oldVal1
AND val2 = @oldVal2;
- {if AffectedRows == 1 }
- COMMIT TRANSACTION;
- {go on with your other code}
- {else}
- ROLLBACK TRANSACTION;
- {decide what to do since it has gone bad... in your code}
- {endif}
</code></pre>
<p>This last example shows that if you check for collisions at some point and discover a collision has happened when you have already modified other tables/rows.. ..then with transactions you are able to rollback ALL the changes that you've done since the beginning.
Obviously it is up to you (that knows what your application is doing) to decide how large the amount of operations to rollback is for each possible collision and based on this decide where to put the transactions boundaries and where to check for collisions with the special UPDATE + AffectedRows check.</p>
<p>In this case with transactions we have separated the moment when we perform the UPDATE from the moment when it is committed. So what happens when an "other process" performs an update in this time frame?
To know what happens exactly requires delving into the details of isolation levels (and how they are managed on each engine).
As an example in the case of Microsoft SQL Server with READ_COMMITTED the updated rows
are locked until the COMMIT, so "other process" can't do nothing (is kept waiting) on that rows, neither a SELECT (in fact it can only READ_COMMITTED).
So since the "other process" activity is deferred it's UPDATE will fail.</p>
<h2>The VERSIONING OPTIMISTIC LOCKING option:</h2>
<pre><code> - SELECT iD, val1, val2, version
FROM theTable
WHERE iD = @theId;
- {code that calculates new values}
- UPDATE theTable
SET val1 = @newVal1,
val2 = @newVal2,
version = version + 1
WHERE iD = @theId
AND version = @oldversion;
- {if AffectedRows == 1 }
- {go on with your other code}
- {else}
- {decide what to do since it has gone bad... in your code}
- {endif}
</code></pre>
<p>Here it is shown that instead of checking if the value is still the same for all the fields we can use a dedicated field (that is modified each time we do an UPDATE) to see if anyone was quicker than us and changed the row between our SELECT and UPDATE.
Here the absence of transactions is due to the simplicity as in the first example and is not related with the version column use.
Again this column use is up to the implementation in the application code and not a database engine feature.</p>
<p>More than this there are other points which I think would make this answer too long (is already much too long) so I only mention them by now with some references:</p>
<ul>
<li>transaction isolation level (<a href="http://dev.mysql.com/doc/refman/5.6/en/dynindex-isolevel.html" rel="noreferrer">here for MySQL</a>) about transaction effect on SELECTs.</li>
<li>for the INSERT on tables with primary keys not autogenerated (or unique constraints) it will automatically fail with no need of particular checking if two processes try to insert the same values where it must be unique.</li>
<li>if you have no id column (primary key or unique constraints) also a single SELECT + UPDATE require transactions because you could have the surprise that after modifications made by others there are more rows than expected matching the criteria of the UPDATE's WHERE clause.</li>
</ul>
<h2>How to check in practice and get confident</h2>
<p>Since the isolation level value and implementation may be different the best advice (as usual in this site) is to perform a test on the used platform / environment.</p>
<p>It may seem difficult but in reality it can be done quite easily from any DB development environment using two separate windows and starting on each one a transaction then executing the commands one by one.</p>
<p>At some point you will see that the the command execution continues indefinitely.
Then when on the other window it is called COMMIT or ROLLBACK it completes the execution.</p>
<p>Here are some very basic commands ready to be tested as just described.</p>
<p>Use these for creating the table and one useful row:</p>
<pre><code>CREATE TABLE theTable(
iD int NOT NULL,
val1 int NOT NULL,
val2 int NOT NULL
);
INSERT INTO theTable (iD, val1, val2) VALUES (1, 2 ,3);
</code></pre>
<p>Then the following on two different windows and step by step:</p>
<pre><code>BEGIN TRAN
SELECT val1, val2 FROM theTable WHERE iD = 1;
UPDATE theTable
SET val1=11
WHERE iD = 1 AND val1 = 2 AND val2 = 3;
COMMIT TRAN
</code></pre>
<p>Then change the order of commands and order of execution in any order you may think.</p> |
17,671,105 | ASP MVC href to a controller/view | <p>I have this:</p>
<pre><code><li><a href="/Users/Index)" class="elements"><span>Clients</span></a></li>
</code></pre>
<p>Which works fine. But if I am already on this page or on the controller e.g. <code>/Users/Details</code> and I click on this link it redirects me to <code>/Users/Index</code>.</p>
<p>How can I get the correct path in the <code>href</code> regardless of my current position on the site?</p> | 17,671,254 | 8 | 1 | null | 2013-07-16 08:00:13.523 UTC | 17 | 2022-05-26 09:41:17.38 UTC | 2016-05-16 05:35:40.19 UTC | null | 225,799 | null | 1,331,971 | null | 1 | 102 | asp.net|asp.net-mvc|asp.net-mvc-4|razor|href | 266,107 | <p>There are a couple of ways that you can accomplish this. You can do the following:</p>
<pre><code><li>
@Html.ActionLink("Clients", "Index", "User", new { @class = "elements" }, null)
</li>
</code></pre>
<p>or this:</p>
<pre><code><li>
<a href="@Url.Action("Index", "Users")" class="elements">
<span>Clients</span>
</a>
</li>
</code></pre>
<p>Lately I do the following:</p>
<pre><code><a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, Request.Url.Scheme)">
<span>Clients</span>
</a>
</code></pre>
<p>The result would have <code>http://localhost/10000</code> (or with whatever port you are using) to be appended to the URL structure like:</p>
<pre><code>http://localhost:10000/Users
</code></pre>
<p>I hope this helps.</p> |
18,257,729 | What license(s) are the Android support libraries released under? | <p>I've been reading through the <a href="http://developer.android.com/tools/support-library/index.html">documentation</a> for the Android Support Library, but while it explicitly says that you should include it in your Android project, it doesn't mention anything about what license the library itself is under (the only license notice present applies to the contents of the documentation page, not the code it describes). The copy spat out by Eclipse does not include any licensing information either, and queries to Google mostly just link back to the same documentation pages.</p>
<p>This confuses me. Should I include a notice that the code is from Google? Not put in any license notice at all? Or am I not properly understanding how the library is meant to be used? Admittedly, I am quite new to Android development.</p> | 18,257,808 | 3 | 2 | null | 2013-08-15 17:01:38.61 UTC | 5 | 2018-10-27 07:46:06.83 UTC | null | null | null | user597474 | null | null | 1 | 33 | android | 14,018 | <p>Each source file, (like <a href="https://android.googlesource.com/platform/frameworks/support/+/master/v13/java/android/support/v13/app/FragmentCompat.java">this one</a>) contains a copyright header like this: </p>
<pre><code>/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
</code></pre>
<p>Which states an Apache license: </p>
<p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p>
<p>And, I think apache license allows derivative works to be built and sold. Still, you should:</p>
<ol>
<li>Include same license in source of the derived product as well.</li>
<li>Clearly state what parts you derived changes, built upon.</li>
</ol>
<p>You can place this in <code>Licence.txt</code> or <code>Readme.txt</code> at the root of your project.</p> |
18,482,976 | Tell Sublime Text to ignore everything in .gitignore? | <p>Vim has this <a href="http://www.vim.org/scripts/script.php?script_id=2557" rel="noreferrer">great plugin</a> to convert the current project's <code>.gitignore</code> into a syntax understandable by Vim and from there exclude all those files from opening.</p>
<p>Using Sublime Text 3's 'Go to Anything' (CMD+P), I get lots of files I'm not interested in, such as stuff under <code>.build</code> and <code>.meteor</code>.</p>
<p>Is there something similar for ST3?</p> | 26,372,261 | 4 | 4 | null | 2013-08-28 08:31:28.523 UTC | 9 | 2022-06-23 13:57:36.263 UTC | null | null | null | null | 243,157 | null | 1 | 64 | sublimetext|gitignore|sublimetext3 | 17,791 | <p>I created a quick-and-dirty plugin, <a href="https://github.com/ExplodingCabbage/sublime-gitignorer" rel="noreferrer">sublime-gitignorer</a>, to solve exactly this problem.</p>
<p>It is currently tested on Ubuntu and Windows in Sublime Text 2 and 3. I expect it will also work on any other Linux distro or on Mac.</p>
<hr>
<p><strong>To install, assuming you have <a href="https://sublime.wbond.net/" rel="noreferrer">package control</a>, just:</strong></p>
<ul>
<li>Press <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>P</kbd> (<kbd>CMD</kbd>+<kbd>SHIFT</kbd>+<kbd>P</kbd> on Mac)</li>
<li>Select "Install Package"</li>
<li>Search for the <strong><em>Gitignored File Excluder</em></strong> and press <kbd>Enter</kbd>.</li>
</ul>
<p><strong>Alternatively</strong>, if you don't have package control you can copy <a href="https://raw.githubusercontent.com/ExplodingCabbage/sublime-gitignorer/master/gitignore_plugin.py" rel="noreferrer">gitignore_plugin.py</a> to your Packages directory, which you can locate by selecting <em><code>Browse Packages...</code></em> from the <em><code>Preferences</code></em> menu in Sublime. You should really get Package Control instead, though - it's useful.</p>
<hr>
<p>I'm not kidding when I say this plugin is dirty. The way it works is that the plugin, every five seconds:</p>
<ul>
<li>Checks for Git repos located within your open folders</li>
<li>Asks Git what paths are ignored in each of those repos</li>
<li>Adds those paths to the <code>file_exclude_patterns</code> and <code>folder_exclude_patterns</code> settings.</li>
</ul>
<p>Seems to work okay for most users, though - at least as long as the folders you're opening in Sublime aren't too huge. The presence of giant folders (e.g a typical <code>node_modules</code> folder) can, in combination with this plugin, slow Sublime to a crawl.</p>
<p>Anyone looking to contribute or report bugs should check out the <a href="https://github.com/ExplodingCabbage/sublime-gitignorer/issues" rel="noreferrer">issues page</a>.</p> |
26,329,300 | How to shut down a Spring Boot command-line application | <p>I am building a Command Line java application using Spring Boot to get it working quickly.</p>
<p>The application loads different types of files (for example CSV) and loads them into a Cassandra Database. It does NOT use any web components, it is not a web application.</p>
<p>The problem I am having is to stop the application when the work is done. I am using the Spring CommandLineRunner interface with a <code>@Component</code> to run the tasks, as shown below, but when the work is completed the application does not stop, it keeps running for some reason and I can't find a way to stop it.</p>
<pre><code>@Component
public class OneTimeRunner implements CommandLineRunner {
@Autowired
private CassandraOperations cassandra;
@Autowired
private ConfigurableApplicationContext context;
@Override
public void run(String... args) throws Exception {
// do some work here and then quit
context.close();
}
}
</code></pre>
<p><strong>UPDATE</strong>: the problem seems to be <code>spring-cassandra</code>, since there is nothing else in the project. Does anyone know why it keeps threads running in the background that prevent the application from stopping?</p>
<p><strong>UPDATE</strong>: the problem disappeared by updating to the latest spring boot version.</p> | 26,329,785 | 6 | 2 | null | 2014-10-12 19:50:53.007 UTC | 13 | 2022-08-26 09:39:14.013 UTC | 2016-04-14 08:33:25.607 UTC | null | 2,597,143 | null | 2,597,143 | null | 1 | 51 | java|spring|spring-boot|spring-data-cassandra | 49,647 | <p>The answer depends on what it is that is still doing work. You can probably find out with a thread dump (eg using jstack). But if it is anything that was started by Spring you should be able to use <code>ConfigurableApplicationContext.close()</code> to stop the app in your main() method (or in the <code>CommandLineRunner</code>).</p> |
23,333,815 | Is there "Edit and Continue" in PyCharm? Reload code into running program like in Eclipse / PyDev? | <p>Hi all Python developers!</p>
<p>In Eclipse with PyDev it is possible to edit a Python file while debugging. On save, the PyDev debugger will reload the updated code into the running program and uses my new code. How can I do the same thing in JetBrains PyCharm (using Community Edition)? </p>
<p>Eclipse / PyDev writes an output like this when I do that:</p>
<pre><code>pydev debugger: Start reloading module: "MyWidget" ...
pydev debugger: Updated function code: <function close at 0x055F4E70>
pydev debugger: reload finished
</code></pre>
<p>I searched settings and web and could not find any hint. Very glad about any idea. Thx.</p>
<p>Edit: I found out in Eclipse/PyDev one has to be in debug mode to be able to use this feature. I tested in PyCharm, but there was no reload done.</p> | 24,637,113 | 4 | 7 | null | 2014-04-28 06:17:42.193 UTC | 22 | 2022-05-04 03:45:59.697 UTC | 2014-06-26 06:33:49.063 UTC | null | 2,427,749 | null | 2,427,749 | null | 1 | 59 | python|pycharm | 17,994 | <p>After all I found a useful and acceptable workaround for my question. It works in PyCharm Community Edition 3.1.2 and I assume it will do in commercial edition as well. I tested on a mid-scale project using Python 2.7.6, PySide (Qt) with one main window and 20+ widgets, tabs, whatever. Follow these steps...</p>
<ol>
<li>Work in PyCharm on a python project :-)</li>
<li>Execute your code in Debug mode (did not tried Release so far)</li>
<li>Edit some code in one your modules imported during the life of your program</li>
<li><strong>Make your program pause</strong>. To achieve this, you can click the "Pause" button of in PyCharms Debug view and then any place in your applications main window where it would need to do something (for example on a tab header). If you have a long a running task and no UI, you may place a breakpoint in a place your program often comes by.</li>
<li>In the Debug view, switch to the <strong>Console</strong> tab. There is a button on the left <strong>Show command line</strong>. Click this.</li>
<li>In the console, type in <strong>reload(MyModifiedModule)</strong> if this call fails, write <strong>import MyModifiedModule</strong> and try again.</li>
<li>Click resume in PyCharm.</li>
<li>Try the code you fixed.</li>
</ol>
<p><img src="https://i.stack.imgur.com/6oe74.png" alt="PyCharm Debug View" /></p>
<p>There are some restrictions on this... It won't fix changes in your main method or main window, cause it won't be created again. In my tests I could not reload widgets from Qt. But it worked for classes like data containers or workers.</p>
<p>May the force be with you as you try this and do not hesitate to add your experiences.</p> |
31,869,592 | Error: Incorrect number of dimensions in R | <p>Here's the data I'm using (it's a high-dimensional data set and available within the psych package): </p>
<pre><code>install.packages("psych")
data(sat.act)
</code></pre>
<p>I'm trying to clean up the data a bit more so that I can run a factor analysis on it. Here's my code so far:</p>
<pre><code>data1 <- data[,6:700]
satact <- data.frame(data1)
satact1 <- na.omit(data1)
dim(data)
</code></pre>
<p>But I'm getting an error stating there is an incorrect number of dimensions for my data[,6,700]. I have tried all possible combinations I can think of, and am not sure why it's showing up as incorrect. Any help will be greatly appreciated!</p> | 31,895,358 | 2 | 11 | null | 2015-08-07 04:12:00.977 UTC | 0 | 2020-08-19 09:44:33.247 UTC | null | null | null | null | 5,068,162 | null | 1 | 0 | r | 80,085 | <p>Elle, try this if you want to exclude the records with <code>NA</code>.</p>
<pre><code>library(psych)
data <- sat.act[complete.cases(sat.act), ]
prcomp(data)
Standard deviations:
[1] 146.8300134 68.2543504 9.5430803 3.6666452 1.1715551 0.4647055
Rotation:
PC1 PC2 PC3 PC4 PC5
gender 0.0003401435 -0.0012020541 0.0010970565 0.005788342 -0.0591625722
education -0.0004299901 -0.0002918314 -0.0850528466 0.024064095 -0.9943380906
age 0.0027020833 0.0014188342 -0.9929359565 -0.084983862 0.0824906340
ACT -0.0208448308 0.0016963799 -0.0827031922 0.995852246 0.0314096125
SATV -0.6956211490 -0.7182796666 -0.0017374908 -0.013494765 0.0003648618
SATQ -0.7181010432 0.6957498829 0.0003989952 -0.016166443 -0.0003874180
PC6
gender -0.9982301944
education 0.0589781669
age -0.0064738244
ACT 0.0038129483
SATV 0.0005261265
SATQ -0.0011528452
</code></pre>
<p>Or if you want to force <code>NA</code> to <code>0</code></p>
<pre><code>data <- sat.act
data[is.na(data)] <- 0
prcomp(data)
Standard deviations:
[1] 159.4488983 85.1587086 9.5463091 3.7961644 1.1814762 0.4653497
Rotation:
PC1 PC2 PC3 PC4 PC5
gender 0.0003915730 -7.364935e-04 0.0008193646 0.002717142 -0.0591610356
education -0.0004932616 -9.314099e-05 -0.0837084272 0.019199014 -0.9945610838
age 0.0012746540 4.606768e-03 -0.9933615141 -0.080624581 0.0817016560
ACT -0.0172578373 -1.064616e-02 -0.0788111515 0.996345023 0.0259420620
SATV -0.5500283967 -8.349310e-01 -0.0030404778 -0.018696325 0.0002655931
SATQ -0.8349664116 5.502319e-01 0.0021652104 -0.008410428 -0.0000266278
PC6
gender -0.9982440693
education 0.0589261882
age -0.0058797665
ACT 0.0011109106
SATV 0.0003311219
SATQ -0.0007530176
</code></pre> |
5,281,779 | C - how to test easily if it is prime-number? | <blockquote>
<p><strong>Possible Duplicates:</strong><br>
<a href="https://stackoverflow.com/questions/1538644/c-determine-if-a-number-is-prime">C - determine if a number is prime</a> </p>
</blockquote>
<p>Is there any way to test easily in C whether a selected number is prime or not?</p> | 5,281,794 | 3 | 6 | null | 2011-03-12 09:47:18.977 UTC | 2 | 2016-09-13 16:19:36.773 UTC | 2017-05-23 12:10:44.89 UTC | null | -1 | null | 513,956 | null | 1 | 4 | c | 46,514 | <p>The easiest way is writing a loop, like: </p>
<pre><code>int is_prime(int num)
{
if (num <= 1) return 0;
if (num % 2 == 0 && num > 2) return 0;
for(int i = 3; i < num / 2; i+= 2)
{
if (num % i == 0)
return 0;
}
return 1;
}
</code></pre>
<p>You can then optimize it, iterating to <code>floor(sqrt(num))</code>.</p> |
5,437,521 | How do I start using my repository locally and on Github? | <p>So: </p>
<p>1) I have created my account on github and I've created a repository there.</p>
<p>2) I have the keys to access the repository from my dev machine to github, using SSH, so that my local repository is synchronized with the remote one hosted on github once I do, push or pull. </p>
<p>But, I'm not understanding how will all this start.</p>
<p>I have my local files on this dev computer and from there I do:</p>
<p>3) git init</p>
<p>then</p>
<p>4) git add</p>
<p>and then I 5) commit that project to my LOCAL repository.</p>
<p>Once this is done, then I will 6) push this to github repository.</p>
<p><strong>Is this correct?</strong></p> | 5,437,611 | 3 | 4 | null | 2011-03-25 20:01:34.983 UTC | 12 | 2014-04-18 03:31:34.953 UTC | 2011-08-20 14:54:24.067 UTC | null | 600,500 | null | 378,170 | null | 1 | 21 | git|github | 34,394 | <p>That's basically correct, yes. To explain what each thing is doing...</p>
<ol>
<li><code>git init</code> basically says, "Hey, I want a repository here." You only will have to do this once per repository.</li>
<li>After that, you will want to add a remote, which GitHub probably told you to do by using <code>git remote add origin [email protected]:username/repository</code> This allows you to push to a remote. You will only have to do this once as well.</li>
<li>After that, use <code>git add</code> to add your changes, or "stage them". You can use <code>git add -i</code> for a bit of a more interactive experience.</li>
<li>Use <code>git commit -m 'message'</code> to commit locally.</li>
<li>Then use <code>git push origin master</code> This says, "Push all of the commits to the remote origin, under master.</li>
<li>If you make changes from another machine, or someone else makes changes, you can use <code>git pull</code> to get them from the remote.</li>
</ol>
<p>You might want to consider reading <a href="http://progit.org/book/" rel="noreferrer">ProGit</a> - it's free online and is a wealth of information. There you can learn more about features like branching, merging, etc.</p> |
25,709,324 | Grunt wiredep:app no such file or directory bower.json | <p>I'm trying to deploy my Yeoman's Angular app to my production server.
When I try to run the grunt build command I get this error:</p>
<blockquote>
<p>Running "wiredep:app" (wiredep) task
Warning: ENOENT, no such file or directory '/usr/share/nginx/html/data/gaia-app/app/bower.json' Use --force to continue.</p>
</blockquote>
<p>If I use <code>grunt --force</code> my app is broken...</p>
<p>I'm on Ubuntu 14.04</p>
<p>Any ideas?</p> | 25,713,634 | 5 | 4 | null | 2014-09-07 10:37:48.107 UTC | 12 | 2014-12-22 19:22:16.113 UTC | 2014-09-07 12:49:59.037 UTC | null | 1,993,402 | null | 544,574 | null | 1 | 42 | gruntjs|grunt-wiredep | 22,568 | <p>There are two solutions to this issue depending on which version of wiredep you want to use.</p>
<p>If you want to use '^1.9.0', make sure to remove the cwd property from your Gruntfile.js. This is a common issue if you are an angular-generator user which currently specifies a cwd property on the config for the wiredep task.</p>
<p>If you don't mind using '1.8.0', make sure to pin that version in your package.json. If you are including wiredep via grunt-wiredep, then you will have to add wiredep manually and pin it. In the case that you stick with '1.8.0', leave the cwd property in the config for the task.</p> |
9,600,390 | Backbone.js route optional parameter | <p>Is it possible to have optional parameters in a Backbone.js route?</p>
<p>e.g this:</p>
<pre><code>routes:
"search/[:query]": "searchIndex"
</code></pre>
<p>instead of:</p>
<pre><code>routes:
"search/": "searchIndex"
"search/:query": "searchIndex"
</code></pre> | 14,329,976 | 4 | 3 | null | 2012-03-07 11:13:21.337 UTC | 9 | 2013-09-13 16:39:31.477 UTC | null | null | null | null | 515,902 | null | 1 | 41 | javascript|backbone.js|routes | 23,970 | <p>As of Backbone 0.9.9, you can add optional paramaters with parentheses.</p>
<p>For example in your routes object you can define an optional route part like this: </p>
<pre><code>routes: {
"organize(/:action)": "displayOrganize"
}
</code></pre>
<p>Now the url path will match <code>/#organize</code> and routes like <code>/#organize/create</code>.</p>
<p>Keep in mind that if you need routes like <code>/#organize/</code> (with a trailing slash) to be recognized, you can do:</p>
<pre><code>routes: {
"organize(/)(:action)": "displayOrganize"
}
</code></pre> |
23,251,795 | How to calculate the frequency of CPU cores | <p>I am trying to use RDTSC but it seems like my approach may be wrong to get the core speed:</p>
<pre><code>#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;
struct Core
{
int CoreNumber;
};
static void startMonitoringCoreSpeeds(void *param)
{
Core core = *((Core *)param);
SetThreadAffinityMask(GetCurrentThread(), 1 << core.CoreNumber);
while (true)
{
DWORD64 first = __rdtsc();
Sleep(1000);
DWORD64 second = __rdtsc();
cout << "Core " << core.CoreNumber << " has frequency " << ((second - first)*pow(10, -6)) << " MHz" << endl;
}
}
int GetNumberOfProcessorCores()
{
DWORD process, system;
if (GetProcessAffinityMask(GetCurrentProcess(), &process, &system))
{
int count = 0;
for (int i = 0; i < 32; i++)
{
if (system & (1 << i))
{
count++;
}
}
return count;
}
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i < GetNumberOfProcessorCores(); i++)
{
Core *core = new Core {0};
core->CoreNumber = i;
_beginthread(startMonitoringCoreSpeeds, 0, core);
}
cin.get();
}
</code></pre>
<p>It always prints out values around 3.3 GHz, which is wrong because things like Turbo Boost are on from time to time and my cores jump to 4.3 GHz for sure. Let me cross-reference some articles behind this idea.</p>
<p>Firstly (<a href="http://users.utcluj.ro/~ancapop/labscs/SCS2.pdf" rel="noreferrer">http://users.utcluj.ro/~ancapop/labscs/SCS2.pdf</a>): "The TSCs on the processor’s cores are not synchronized. So it is not sure that if a process migrates during
execution from one core to another, the measurement will not be affected. To avoid this problem, the measured process’s affinity has to be set to just one core, to prevent process migration." This tells me that RDTSC should return a different value per core my thread is on using the affinity mask I set, which is great.</p>
<p>Secondly, <strong>and please check this article</strong> (<a href="http://randomascii.wordpress.com/2011/07/29/rdtsc-in-the-age-of-sandybridge/" rel="noreferrer">http://randomascii.wordpress.com/2011/07/29/rdtsc-in-the-age-of-sandybridge/</a>): "If you need a consistent timer that works across cores and can be used to measure time then this is good news. If you want to measure actual CPU clock cycles then you are out of luck. If you want consistency across a wide range of CPU families then it sucks to be you. Update: section 16.11 of the Intel System Programming Guide documents this behavior of the Time-Stamp Counter. Roughly speaking it says that on older processors the clock rate changes, but on newer processors it remains uniform. It finishes by saying, of Constant TSC, “This is the architectural behavior moving forward." Okay, this tells me that RDTSC stays consistent, which makes my above results make sense since my CPU cores are rated at a standard 3.3 GHz...</p>
<p><strong>Which REALLY begs the question, how do applications like Intel's Turbo Boost Technology Monitor and Piriform's Speccy and CPUID's CPU-Z measure a processor's clock speed while undergoing turbo boost, realtime?</strong></p> | 24,130,987 | 1 | 32 | null | 2014-04-23 17:55:36.317 UTC | 8 | 2014-06-10 14:46:05.697 UTC | null | null | null | null | 982,639 | null | 1 | 7 | c++|performance|winapi|visual-c++|rdtsc | 3,666 | <p>Full solution follows. I've adapted the <a href="http://code.msdn.microsoft.com/windowshardware/IOCTL-a583bbeb" rel="nofollow noreferrer">IOCTL sample driver on MSDN</a> to do this. Note, the IOCTL sample is <a href="https://stackoverflow.com/questions/24016441/why-is-there-no-wdm-kernel-mode-driver-template-in-windows-driver-kit">the only relative WDM sample skeleton driver I could find and also the closest thing I could find to a WDM template</a> because most kernel mode templates out of the box in WDK are WDF-based drivers (any WDM driver template is actually blank with absolutely no source code), yet <a href="http://www.codeproject.com/Articles/9575/Driver-Development-Part-Introduction-to-Implemen" rel="nofollow noreferrer">the only sample logic I've seen to do this input/output was through a WDM-based driver</a>. Also, some fun facts I've learned along the way: kernel drivers don't like floating arithmetic and you can't use "windows.h" which really limits you to "ntddk.h", a special kernel-mode header. This also means I can't do all of my computations inside of kernel mode because I can't call functions like QueryPerformanceFrequency in there, so I had to get the mean performance ratio between timestamps and return them back to user mode for some computations (without QueryPerformanceFrequency, the values you get from CPU registers that store ticks like what QueryPerformanceCounter uses are useless because you don't know the step size; maybe there's a workaround to this but I opted to just use the mean since it works pretty damn well). Also, as per the one second sleep, the reason I used that is because otherwise you're almost spin-computing shit on multiple threads, which really messes up your calculations because your frequencies will go up per core constantly checking results from QueryPerformanceCounter (you drive your cores up as you do more computations) - NOT TO MENTION - its a ratio...so the delta time is not that important since its cycles per time...<strong>you can always increase the delta, it should still give you the same ratio relative to the step size</strong>. Furthermore, this is as minimalistic as I could get it to be. Good luck making it much smaller or shorter than this. Also, if you want to install the driver, you <a href="https://stackoverflow.com/questions/24091822/how-can-i-install-this-driver">have two options</a> unless you want to buy a Code Signing certificate from some third party, both suck, so pick one and suck it up. Let's start with the driver:</p>
<p><strong>driver.c</strong>:</p>
<pre><code>//
// Include files.
//
#include <ntddk.h> // various NT definitions
#include <string.h>
#include <intrin.h>
#include "driver.h"
#define NT_DEVICE_NAME L"\\Device\\KernelModeDriver"
#define DOS_DEVICE_NAME L"\\DosDevices\\KernelModeDriver"
#if DBG
#define DRIVER_PRINT(_x_) \
DbgPrint("KernelModeDriver.sys: ");\
DbgPrint _x_;
#else
#define DRIVER_PRINT(_x_)
#endif
//
// Device driver routine declarations.
//
DRIVER_INITIALIZE DriverEntry;
_Dispatch_type_(IRP_MJ_CREATE)
_Dispatch_type_(IRP_MJ_CLOSE)
DRIVER_DISPATCH DriverCreateClose;
_Dispatch_type_(IRP_MJ_DEVICE_CONTROL)
DRIVER_DISPATCH DriverDeviceControl;
DRIVER_UNLOAD DriverUnloadDriver;
VOID
PrintIrpInfo(
PIRP Irp
);
VOID
PrintChars(
_In_reads_(CountChars) PCHAR BufferAddress,
_In_ size_t CountChars
);
#ifdef ALLOC_PRAGMA
#pragma alloc_text( INIT, DriverEntry )
#pragma alloc_text( PAGE, DriverCreateClose)
#pragma alloc_text( PAGE, DriverDeviceControl)
#pragma alloc_text( PAGE, DriverUnloadDriver)
#pragma alloc_text( PAGE, PrintIrpInfo)
#pragma alloc_text( PAGE, PrintChars)
#endif // ALLOC_PRAGMA
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
/*++
Routine Description:
This routine is called by the Operating System to initialize the driver.
It creates the device object, fills in the dispatch entry points and
completes the initialization.
Arguments:
DriverObject - a pointer to the object that represents this device
driver.
RegistryPath - a pointer to our Services key in the registry.
Return Value:
STATUS_SUCCESS if initialized; an error otherwise.
--*/
{
NTSTATUS ntStatus;
UNICODE_STRING ntUnicodeString; // NT Device Name "\Device\KernelModeDriver"
UNICODE_STRING ntWin32NameString; // Win32 Name "\DosDevices\KernelModeDriver"
PDEVICE_OBJECT deviceObject = NULL; // ptr to device object
UNREFERENCED_PARAMETER(RegistryPath);
RtlInitUnicodeString( &ntUnicodeString, NT_DEVICE_NAME );
ntStatus = IoCreateDevice(
DriverObject, // Our Driver Object
0, // We don't use a device extension
&ntUnicodeString, // Device name "\Device\KernelModeDriver"
FILE_DEVICE_UNKNOWN, // Device type
FILE_DEVICE_SECURE_OPEN, // Device characteristics
FALSE, // Not an exclusive device
&deviceObject ); // Returned ptr to Device Object
if ( !NT_SUCCESS( ntStatus ) )
{
DRIVER_PRINT(("Couldn't create the device object\n"));
return ntStatus;
}
//
// Initialize the driver object with this driver's entry points.
//
DriverObject->MajorFunction[IRP_MJ_CREATE] = DriverCreateClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = DriverCreateClose;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DriverDeviceControl;
DriverObject->DriverUnload = DriverUnloadDriver;
//
// Initialize a Unicode String containing the Win32 name
// for our device.
//
RtlInitUnicodeString( &ntWin32NameString, DOS_DEVICE_NAME );
//
// Create a symbolic link between our device name and the Win32 name
//
ntStatus = IoCreateSymbolicLink(
&ntWin32NameString, &ntUnicodeString );
if ( !NT_SUCCESS( ntStatus ) )
{
//
// Delete everything that this routine has allocated.
//
DRIVER_PRINT(("Couldn't create symbolic link\n"));
IoDeleteDevice( deviceObject );
}
return ntStatus;
}
NTSTATUS
DriverCreateClose(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
/*++
Routine Description:
This routine is called by the I/O system when the KernelModeDriver is opened or
closed.
No action is performed other than completing the request successfully.
Arguments:
DeviceObject - a pointer to the object that represents the device
that I/O is to be done on.
Irp - a pointer to the I/O Request Packet for this request.
Return Value:
NT status code
--*/
{
UNREFERENCED_PARAMETER(DeviceObject);
PAGED_CODE();
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest( Irp, IO_NO_INCREMENT );
return STATUS_SUCCESS;
}
VOID
DriverUnloadDriver(
_In_ PDRIVER_OBJECT DriverObject
)
/*++
Routine Description:
This routine is called by the I/O system to unload the driver.
Any resources previously allocated must be freed.
Arguments:
DriverObject - a pointer to the object that represents our driver.
Return Value:
None
--*/
{
PDEVICE_OBJECT deviceObject = DriverObject->DeviceObject;
UNICODE_STRING uniWin32NameString;
PAGED_CODE();
//
// Create counted string version of our Win32 device name.
//
RtlInitUnicodeString( &uniWin32NameString, DOS_DEVICE_NAME );
//
// Delete the link from our device name to a name in the Win32 namespace.
//
IoDeleteSymbolicLink( &uniWin32NameString );
if ( deviceObject != NULL )
{
IoDeleteDevice( deviceObject );
}
}
NTSTATUS
DriverDeviceControl(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
/*++
Routine Description:
This routine is called by the I/O system to perform a device I/O
control function.
Arguments:
DeviceObject - a pointer to the object that represents the device
that I/O is to be done on.
Irp - a pointer to the I/O Request Packet for this request.
Return Value:
NT status code
--*/
{
PIO_STACK_LOCATION irpSp;// Pointer to current stack location
NTSTATUS ntStatus = STATUS_SUCCESS;// Assume success
ULONG inBufLength; // Input buffer length
ULONG outBufLength; // Output buffer length
void *inBuf; // pointer to input buffer
unsigned __int64 *outBuf; // pointer to the output buffer
UNREFERENCED_PARAMETER(DeviceObject);
PAGED_CODE();
irpSp = IoGetCurrentIrpStackLocation( Irp );
inBufLength = irpSp->Parameters.DeviceIoControl.InputBufferLength;
outBufLength = irpSp->Parameters.DeviceIoControl.OutputBufferLength;
if (!inBufLength || !outBufLength || outBufLength != sizeof(unsigned __int64)*2)
{
ntStatus = STATUS_INVALID_PARAMETER;
goto End;
}
//
// Determine which I/O control code was specified.
//
switch ( irpSp->Parameters.DeviceIoControl.IoControlCode )
{
case IOCTL_SIOCTL_METHOD_BUFFERED:
//
// In this method the I/O manager allocates a buffer large enough to
// to accommodate larger of the user input buffer and output buffer,
// assigns the address to Irp->AssociatedIrp.SystemBuffer, and
// copies the content of the user input buffer into this SystemBuffer
//
DRIVER_PRINT(("Called IOCTL_SIOCTL_METHOD_BUFFERED\n"));
PrintIrpInfo(Irp);
//
// Input buffer and output buffer is same in this case, read the
// content of the buffer before writing to it
//
inBuf = (void *)Irp->AssociatedIrp.SystemBuffer;
outBuf = (unsigned __int64 *)Irp->AssociatedIrp.SystemBuffer;
//
// Read the data from the buffer
//
DRIVER_PRINT(("\tData from User :"));
//
// We are using the following function to print characters instead
// DebugPrint with %s format because we string we get may or
// may not be null terminated.
//
PrintChars(inBuf, inBufLength);
//
// Write to the buffer
//
unsigned __int64 data[sizeof(unsigned __int64) * 2];
data[0] = __readmsr(232);
data[1] = __readmsr(231);
DRIVER_PRINT(("data[0]: %d", data[0]));
DRIVER_PRINT(("data[1]: %d", data[1]));
RtlCopyBytes(outBuf, data, outBufLength);
//
// Assign the length of the data copied to IoStatus.Information
// of the Irp and complete the Irp.
//
Irp->IoStatus.Information = sizeof(unsigned __int64)*2;
//
// When the Irp is completed the content of the SystemBuffer
// is copied to the User output buffer and the SystemBuffer is
// is freed.
//
break;
default:
//
// The specified I/O control code is unrecognized by this driver.
//
ntStatus = STATUS_INVALID_DEVICE_REQUEST;
DRIVER_PRINT(("ERROR: unrecognized IOCTL %x\n",
irpSp->Parameters.DeviceIoControl.IoControlCode));
break;
}
End:
//
// Finish the I/O operation by simply completing the packet and returning
// the same status as in the packet itself.
//
Irp->IoStatus.Status = ntStatus;
IoCompleteRequest( Irp, IO_NO_INCREMENT );
return ntStatus;
}
VOID
PrintIrpInfo(
PIRP Irp)
{
PIO_STACK_LOCATION irpSp;
irpSp = IoGetCurrentIrpStackLocation( Irp );
PAGED_CODE();
DRIVER_PRINT(("\tIrp->AssociatedIrp.SystemBuffer = 0x%p\n",
Irp->AssociatedIrp.SystemBuffer));
DRIVER_PRINT(("\tIrp->UserBuffer = 0x%p\n", Irp->UserBuffer));
DRIVER_PRINT(("\tirpSp->Parameters.DeviceIoControl.Type3InputBuffer = 0x%p\n",
irpSp->Parameters.DeviceIoControl.Type3InputBuffer));
DRIVER_PRINT(("\tirpSp->Parameters.DeviceIoControl.InputBufferLength = %d\n",
irpSp->Parameters.DeviceIoControl.InputBufferLength));
DRIVER_PRINT(("\tirpSp->Parameters.DeviceIoControl.OutputBufferLength = %d\n",
irpSp->Parameters.DeviceIoControl.OutputBufferLength ));
return;
}
VOID
PrintChars(
_In_reads_(CountChars) PCHAR BufferAddress,
_In_ size_t CountChars
)
{
PAGED_CODE();
if (CountChars) {
while (CountChars--) {
if (*BufferAddress > 31
&& *BufferAddress != 127) {
KdPrint (( "%c", *BufferAddress) );
} else {
KdPrint(( ".") );
}
BufferAddress++;
}
KdPrint (("\n"));
}
return;
}
</code></pre>
<p><strong>driver.h</strong>:</p>
<pre><code>//
// Device type -- in the "User Defined" range."
//
#define SIOCTL_TYPE 40000
//
// The IOCTL function codes from 0x800 to 0xFFF are for customer use.
//
#define IOCTL_SIOCTL_METHOD_IN_DIRECT \
CTL_CODE( SIOCTL_TYPE, 0x900, METHOD_IN_DIRECT, FILE_ANY_ACCESS )
#define IOCTL_SIOCTL_METHOD_OUT_DIRECT \
CTL_CODE( SIOCTL_TYPE, 0x901, METHOD_OUT_DIRECT , FILE_ANY_ACCESS )
#define IOCTL_SIOCTL_METHOD_BUFFERED \
CTL_CODE( SIOCTL_TYPE, 0x902, METHOD_BUFFERED, FILE_ANY_ACCESS )
#define IOCTL_SIOCTL_METHOD_NEITHER \
CTL_CODE( SIOCTL_TYPE, 0x903, METHOD_NEITHER , FILE_ANY_ACCESS )
#define DRIVER_FUNC_INSTALL 0x01
#define DRIVER_FUNC_REMOVE 0x02
#define DRIVER_NAME "ReadMSRDriver"
</code></pre>
<p>Now, here is the application that loads up and uses the driver (Win32 Console Application):</p>
<p><strong>FrequencyCalculator.cpp</strong>:</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <winioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strsafe.h>
#include <process.h>
#include "..\KernelModeDriver\driver.h"
using namespace std;
BOOLEAN
ManageDriver(
_In_ LPCTSTR DriverName,
_In_ LPCTSTR ServiceName,
_In_ USHORT Function
);
HANDLE hDevice;
TCHAR driverLocation[MAX_PATH];
void InstallDriver()
{
DWORD errNum = 0;
GetCurrentDirectory(MAX_PATH, driverLocation);
_tcscat_s(driverLocation, _T("\\KernelModeDriver.sys"));
std::wcout << "Trying to install driver at " << driverLocation << std::endl;
//
// open the device
//
if ((hDevice = CreateFile(_T("\\\\.\\KernelModeDriver"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL)) == INVALID_HANDLE_VALUE) {
errNum = GetLastError();
if (errNum != ERROR_FILE_NOT_FOUND) {
printf("CreateFile failed! ERROR_FILE_NOT_FOUND = %d\n", errNum);
return;
}
//
// The driver is not started yet so let us the install the driver.
// First setup full path to driver name.
//
if (!ManageDriver(_T(DRIVER_NAME),
driverLocation,
DRIVER_FUNC_INSTALL
)) {
printf("Unable to install driver. \n");
//
// Error - remove driver.
//
ManageDriver(_T(DRIVER_NAME),
driverLocation,
DRIVER_FUNC_REMOVE
);
return;
}
hDevice = CreateFile(_T("\\\\.\\KernelModeDriver"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hDevice == INVALID_HANDLE_VALUE){
printf("Error: CreatFile Failed : %d\n", GetLastError());
return;
}
}
}
void UninstallDriver()
{
//
// close the handle to the device.
//
CloseHandle(hDevice);
//
// Unload the driver. Ignore any errors.
//
ManageDriver(_T(DRIVER_NAME),
driverLocation,
DRIVER_FUNC_REMOVE
);
}
double GetPerformanceRatio()
{
BOOL bRc;
ULONG bytesReturned;
int input = 0;
unsigned __int64 output[2];
memset(output, 0, sizeof(unsigned __int64) * 2);
//printf("InputBuffer Pointer = %p, BufLength = %d\n", &input, sizeof(&input));
//printf("OutputBuffer Pointer = %p BufLength = %d\n", &output, sizeof(&output));
//
// Performing METHOD_BUFFERED
//
//printf("\nCalling DeviceIoControl METHOD_BUFFERED:\n");
bRc = DeviceIoControl(hDevice,
(DWORD)IOCTL_SIOCTL_METHOD_BUFFERED,
&input,
sizeof(&input),
output,
sizeof(unsigned __int64)*2,
&bytesReturned,
NULL
);
if (!bRc)
{
//printf("Error in DeviceIoControl : %d", GetLastError());
return 0;
}
//printf(" OutBuffer (%d): %d\n", bytesReturned, output);
if (output[1] == 0)
{
return 0;
}
else
{
return (float)output[0] / (float)output[1];
}
}
struct Core
{
int CoreNumber;
};
int GetNumberOfProcessorCores()
{
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
}
float GetCoreFrequency()
{
// __rdtsc: Returns the processor time stamp which records the number of clock cycles since the last reset.
// QueryPerformanceCounter: Returns a high resolution time stamp that can be used for time-interval measurements.
// Get the frequency which defines the step size of the QueryPerformanceCounter method.
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
// Get the number of cycles before we start.
ULONG cyclesBefore = __rdtsc();
// Get the Intel performance ratio at the start.
float ratioBefore = GetPerformanceRatio();
// Get the start time.
LARGE_INTEGER startTime;
QueryPerformanceCounter(&startTime);
// Give the CPU cores enough time to repopulate their __rdtsc and QueryPerformanceCounter registers.
Sleep(1000);
ULONG cyclesAfter = __rdtsc();
// Get the Intel performance ratio at the end.
float ratioAfter = GetPerformanceRatio();
// Get the end time.
LARGE_INTEGER endTime;
QueryPerformanceCounter(&endTime);
// Return the number of MHz. Multiply the core's frequency by the mean MSR (model-specific register) ratio (the APERF register's value divided by the MPERF register's value) between the two timestamps.
return ((ratioAfter + ratioBefore) / 2)*(cyclesAfter - cyclesBefore)*pow(10, -6) / ((endTime.QuadPart - startTime.QuadPart) / frequency.QuadPart);
}
struct CoreResults
{
int CoreNumber;
float CoreFrequency;
};
CRITICAL_SECTION printLock;
static void printResult(void *param)
{
EnterCriticalSection(&printLock);
CoreResults coreResults = *((CoreResults *)param);
std::cout << "Core " << coreResults.CoreNumber << " has a speed of " << coreResults.CoreFrequency << " MHz" << std::endl;
delete param;
LeaveCriticalSection(&printLock);
}
bool closed = false;
static void startMonitoringCoreSpeeds(void *param)
{
Core core = *((Core *)param);
SetThreadAffinityMask(GetCurrentThread(), 1 << core.CoreNumber);
while (!closed)
{
CoreResults *coreResults = new CoreResults();
coreResults->CoreNumber = core.CoreNumber;
coreResults->CoreFrequency = GetCoreFrequency();
_beginthread(printResult, 0, coreResults);
Sleep(1000);
}
delete param;
}
int _tmain(int argc, _TCHAR* argv[])
{
InitializeCriticalSection(&printLock);
InstallDriver();
for (int i = 0; i < GetNumberOfProcessorCores(); i++)
{
Core *core = new Core{ 0 };
core->CoreNumber = i;
_beginthread(startMonitoringCoreSpeeds, 0, core);
}
std::cin.get();
closed = true;
UninstallDriver();
DeleteCriticalSection(&printLock);
}
</code></pre>
<p>It uses install.cpp which you can get from the IOCTL sample. I will post a working, fully working and ready solution (with code, obviously) on <a href="http://www.dima.to/blog" rel="nofollow noreferrer">my blog</a> over the next few days, if not tonight.</p>
<p><strong>Edit: Blogged it at <a href="http://www.dima.to/blog/?p=101" rel="nofollow noreferrer">http://www.dima.to/blog/?p=101</a> (full source code available there)...</strong></p> |
18,414,384 | Hide element by class in pure Javascript | <p>I have tried the following code, but it <a href="http://jsfiddle.net/rb7bn/207/" rel="noreferrer">doesn't work</a>. Any idea where I have gone wrong?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementsByClassName('appBanner').style.visibility='hidden';</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="appBanner">appbanner</div></code></pre>
</div>
</div>
</p>
<p>Using jQuery or changing the HTML is not possible as I am using <code>[self->webView stringByEvaluatingJavaScriptFromString:@""];</code> in Objective-C.</p> | 18,414,401 | 4 | 1 | null | 2013-08-24 02:41:52.713 UTC | 20 | 2019-11-19 00:50:20.19 UTC | 2016-06-27 23:54:25.713 UTC | null | 2,581,872 | null | 1,952,032 | null | 1 | 84 | javascript|html | 290,221 | <p><code>document.getElementsByClassName</code> returns an <code>HTMLCollection</code>(an array-like object) of all elements matching the class name. The <code>style</code> property is defined for <code>Element</code> not for <code>HTMLCollection</code>. You should access the first element using the bracket(subscript) notation. </p>
<pre><code>document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';
</code></pre>
<p><strong><a href="http://jsfiddle.net/rb7bn/208/">Updated jsFiddle</a></strong></p>
<p>To change the style rules of all elements matching the class, using the Selectors API:</p>
<pre><code>[].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
el.style.visibility = 'hidden';
});
</code></pre>
<p>If <code>for...of</code> is available:</p>
<pre><code>for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';
</code></pre> |
18,268,620 | OpenXML: Auto Size column width in Excel | <p>I have written a code to generate Excel file using OpenXML.
Below is the code which generates the Columns in the Excel.</p>
<pre><code>Worksheet worksheet = new Worksheet();
Columns columns = new Columns();
int numCols = dt1.Columns.Count;
for (int col = 0; col < numCols; col++)
{
Column c = CreateColumnData((UInt32)col + 1, (UInt32)numCols + 1, 20.42578125D);
columns.Append(c);
}
worksheet.Append(columns);
</code></pre>
<p>Also, I tried below line to create columns.</p>
<pre><code>Column c = new Column
{
Min = (UInt32Value)1U,
Max = (UInt32Value)1U,
Width = 25.42578125D,
BestFit = true,
CustomWidth = true
};
</code></pre>
<p>I thought using <code>BestFit</code> it should work. But it doesn't set the auto size.</p> | 18,305,549 | 6 | 0 | null | 2013-08-16 08:03:23.353 UTC | 7 | 2021-01-21 15:40:20.973 UTC | 2018-07-27 11:20:01.953 UTC | null | 1,548,895 | null | 2,381,956 | null | 1 | 19 | c#|openxml|openxml-sdk | 42,584 | <p>The BestFit property is an information property (possibly for optimisation by Excel). You still need to provide the Width for the Column. This means you have to actually calculate the column width depending on the cell contents. Open XML SDK doesn't do this automatically for you, so it's better that you use a third-party library for this.</p> |
14,985,798 | Python random function | <p>I'm having problems with Python's import random function. It seems that <code>import random</code> and <code>from random import random</code> are importing different things. I am currently using Python 2.7.3</p>
<pre><code>Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> random()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
random()
NameError: name 'random' is not defined
>>> random.randint(1,5)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
random.randint(1,5)
NameError: name 'random' is not defined
>>> import random
>>> random()
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
random()
TypeError: 'module' object is not callable
>>> random.randint(1,5)
2
>>> from random import random
>>> random()
0.28242411635200193
>>> random.randint(1,5)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
random.randint(1,5)
AttributeError: 'builtin_function_or_method' object has no attribute 'randint'
>>>
</code></pre> | 14,985,863 | 9 | 0 | null | 2013-02-20 17:12:09.737 UTC | 4 | 2018-08-10 19:42:12.86 UTC | 2013-02-21 10:28:45.357 UTC | null | 225,037 | null | 2,092,283 | null | 1 | 14 | python|random|import | 130,554 | <p><code>import random</code> imports the random <em>module</em>, which contains a variety of things to do with random number generation. Among these is the random() <em>function</em>, which generates random numbers between 0 and 1.</p>
<p>Doing the import this way this requires you to use the syntax <code>random.random()</code>.</p>
<p>The random function can also be imported from the module separately: </p>
<pre><code>from random import random
</code></pre>
<p>This allows you to then just call <code>random()</code> directly.</p> |
15,259,843 | How to structure REST resource hierarchy? | <p>I'm new to server side web development and recently I've been reading a lot about implementing RESTful API's. One aspect of REST API's that I'm still stuck on is how to go about structuring the URI hierarchy that identifies resources that the client can interact with. Specifically I'm stuck on deciding how detailed to make the hierarchy and what to do in the case of resources being composed of other resource types.</p>
<p>Here's an example that hopefully will show what I mean. Imagine we have a web service that lets users buy products from other users. So in this simple case, there are two top level resources <strong>users</strong> and <strong>products</strong>. Here's how I began to structure the URI hierarchy,</p>
<p><strong>For users:</strong></p>
<pre><code>/users
/{id}
/location
/about
/name
/seller_rating
/bought
/sold
</code></pre>
<p><strong>For products:</strong></p>
<pre><code>/products
/{id}
/name
/category
/description
/keywords
/buyer
/seller
</code></pre>
<p>In both of these cases objects in each hierarchy reference a subset of the objects in the other hierarchy. For example <code>/users/{id}/bought</code> is a list of the products that some user has bought, which is a subset of <code>/products</code>. Also, <code>/products/{id}/seller</code> references the user that sold a specific product.</p>
<p>Since these URI's reference other objects, or subsets of other objects, should the API support things like this: <code>/users/{id}/bought/id/description</code> and <code>/products/{id}/buyer/location</code>? Because if those types of URI's are supported, what's to stop something like this <code>/users/{id}/bought/{id}/buyer/bought/{id}/seller/name</code>, or something equally convoluted? Also, in this case, how would you handle routing since the router in the server would have to interpret URI's of arbitrary length?</p> | 15,305,053 | 2 | 1 | null | 2013-03-06 22:58:04.153 UTC | 11 | 2013-03-08 23:37:34.097 UTC | null | null | null | null | 1,037,364 | null | 1 | 23 | api|rest|uri|restful-url|restful-architecture | 12,771 | <p>The goal is to build convenient resource identifiers, don't try to cross-reference everything. You don't have to repeat your database relations in URL representation :) </p>
<p>Links like <code>/product/{id}/buyer</code> should never exist, because there already is identifier for that resource: <code>/user/{id}</code> </p>
<p>Although it's ok to have <code>/product/{id}/buyers-list</code> because list of buyers is a property of product that does not exist in other contexts.</p> |
15,222,041 | Android: What is Binder Thread? | <p>I use Debug.startMethodTracing for my purposes and in the output file I can see(I don't use IPC):</p>
<pre><code>8 Binder Thread #2
7 Binder Thread #1
</code></pre>
<p>For what it is?</p> | 15,225,390 | 3 | 0 | null | 2013-03-05 10:58:21.693 UTC | 10 | 2020-04-16 03:51:09.33 UTC | null | null | null | null | 1,549,840 | null | 1 | 25 | android | 22,105 | <p>Binder thread represents a separate thread of your service. Binder is a mechanism that provides Inter Process Communication.</p>
<p>Let's consider an example. Imagine that you have service Process B (see picture). And you have several applications that communicate with this service B (one of this application is, for instance, Process A). Thus, one service B should provide different results simultaneously to different applications. Thus, you need to run several replicas of Service B for different applications. Android runs these replicas in different threads of the Process B and these threads are called "Binder Thread #N".</p>
<p><img src="https://i.stack.imgur.com/EkzyV.png" alt="Binder communication"></p>
<p>I took the picture <a href="http://sujaiantony.wordpress.com/2011/12/28/an-android-101-an-overview-on-binder-framework/" rel="noreferrer">here</a>, where you can also read what Binder is.</p> |
15,320,550 | Why is SeCreateSymbolicLinkPrivilege ignored on Windows 8? | <p>I'd like to enable my standard user account (i.e. not elevated) to be able to call CreateSymbolicLink. </p>
<p>However, on Win8, even adding "Everyone" to the SeCreateSymbolicLinkPrivilege ("Create Symbolic Links" in secpol.msc) under local group policy still results in STATUS_PRIVILEGE_NOT_HELD. Why?</p>
<p><img src="https://dzwonsemrish7.cloudfront.net/items/3L2q2l2p1m2v0N1I0e0t/Image%202013.03.10%2012:55:01%20AM.png#png" alt=""></p> | 15,330,511 | 1 | 6 | null | 2013-03-10 08:55:31.37 UTC | 9 | 2018-10-06 18:23:46.767 UTC | 2018-10-06 18:23:46.767 UTC | null | 1,033,581 | null | 5,728 | null | 1 | 29 | windows | 9,134 | <p>It is indeed UAC, as Christian suspected.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb530410.aspx" rel="noreferrer">MSDN: Windows Vista Application Development Requirements for User Account Control Compatibility</a>:</p>
<blockquote>
<p>What privileges the filtered token contain are based on whether the original token contained any of the restricted RIDS listed above (ed: AKA if you're a non-elevated Admin). If any of the restricted RIDs were in the token, <strong>all of the privileges are removed except</strong>:</p>
<ul>
<li>SeChangeNotifyPrivilege</li>
<li>SeShutdownPrivilege</li>
<li>SeUndockPrivilege</li>
<li>SeReserveProcessorPrivilege</li>
<li>SeTimeZonePrivilege</li>
</ul>
</blockquote> |
15,458,334 | How to read POST data in rack request | <p>When I run the curl command</p>
<pre><code>curl -v -H "Content-type: application/json" -X POST -d '{"name":"abc", "id":"12", "subject":"my subject"}' http://localhost:9292
</code></pre>
<p>to send a POST request with data to my Rack application, my code prints out <code>{}</code>. That is coming from <code>puts req.POST()</code> in the code below.</p>
<p>Why does it print out <code>{}</code> instead of the POST data? And how do I correctly access the POST data in my Rack application?</p>
<pre><code>require 'json'
class Greeter
def call(env)
req = Rack::Request.new(env)
if req.post?
puts req.POST()
end
[200, {"Content-Type" => "application/json"}, [{x:"Hello World!"}.to_json]]
end
end
run Greeter.new
</code></pre> | 15,458,860 | 3 | 0 | null | 2013-03-17 06:55:59.79 UTC | 4 | 2018-02-23 06:25:39.837 UTC | 2017-03-17 21:53:52.427 UTC | null | 128,421 | null | 782,220 | null | 1 | 31 | ruby|rack | 20,446 | <p>From reading the docs for POST, looks like it is giving you parsed data based on other content types. If you want to process "application/json", you probably need to </p>
<pre><code>JSON.parse( req.body.read )
</code></pre>
<p>instead. To check this, try</p>
<pre><code>puts req.body.read
</code></pre>
<p>where you currently have <code>puts req.POST</code>.</p>
<hr>
<p><code>req.body</code> is an I/O object, not a string. See the <a href="http://rdoc.info/gems/rack/1.2.1/Rack/Request#body-instance_method" rel="noreferrer"><code>body</code></a> documentation and view the source. You can see that this is in fact the same as mudasobwa's answer.</p>
<p>Note that other code in a Rack application may expect to read the same I/O, such as the param parsers in Sinatra or Rails. To ensure that they see the same data and not get an error, you may want to call <code>req.body.rewind</code>, possibly both before and after reading the request body in your code. However, if you are in such a situation, you might instead consider whether your framework has options to process JSON directly via some option on the controller or request content-type handler declaration etc - most likely there will be an option to handle this kind of request within the framework.</p> |
15,442,292 | How to have an in-place string that updates on stdout | <p>I want to output to stdout and have the output "overwrite" the previous output.</p>
<p>For example; if I output <code>On 1/10</code>, I want the next output <code>On 2/10</code> to overwrite <code>On 1/10</code>. How can I do this?</p> | 15,442,704 | 4 | 0 | null | 2013-03-15 21:21:40.553 UTC | 23 | 2019-12-06 05:14:56.967 UTC | 2019-06-17 08:12:10.857 UTC | null | 13,860 | user1529891 | null | null | 1 | 70 | go|stdout | 34,291 | <p><code>stdout</code> is a stream (<code>io.Writer</code>). You cannot modify what was already written to it. What <em>can</em> be changed is how that stream's represented in case it is printed to a terminal. Note that there's no good reason to assume this scenario. For example, a user could redirect stdout to a pipe or to a file at will.</p>
<p>So the proper approach is to first check:</p>
<ul>
<li>if the stdout is going to a terminal</li>
<li>what is that terminal's procedure to overwrite a line/screen</li>
</ul>
<p>Both of the above are out of this question's scope, but let's assume that a terminal is our device. Then usually, printing:</p>
<pre><code>fmt.Printf("\rOn %d/10", i)
</code></pre>
<p>will overwrite the previous line in the terminal. <code>\r</code> stands for <code>carriage return</code>, implemented by many terminals as moving the cursor to the beginning of the current line, hence providing the "overwrite line" facility.</p>
<p>As an example of "other" terminal with a differently supported 'overwriting', here is an example at the <a href="http://play.golang.org/p/b1LlRwxPdu" rel="noreferrer">playground</a>.</p> |
15,166,722 | Use own username/password with git and bitbucket | <p>I'm in a team of three; two are working locally, and I am working on the server. </p>
<p>My coworker set up the account, but gave me full privileges to the repository.</p>
<p>I set my username and email in git:</p>
<pre><code>git config --global user.name "bozdoz"
git config --global user.email [email protected]
</code></pre>
<p>and they are identical to my username and email on bitbucket.org.</p>
<p>But when I pull or push to the repository it indicates their username in the prompt:</p>
<pre><code>Password for 'https://[email protected]':
</code></pre>
<p>I was able to get a prompt for my password after trying to pull by indicating the URL with my username:</p>
<pre><code>git pull https://[email protected]/path/repo.git
</code></pre>
<p>and it said up-to-date; and then when I pushed, it said no-fast-forward. </p>
<p>I read that I need to specify the branch, but I don't know how to do that in a push statement while I'm also specifying the repo URL:</p>
<pre><code>git push https://[email protected]/path/repo.git
</code></pre>
<p>I am able to pull and push if my co-worker is around and can put his password in. But this is also listing him as the author of the push, and not me.</p>
<p>How can I pull and push to a repo branch as my own username?</p> | 15,167,400 | 8 | 1 | null | 2013-03-01 20:54:13.22 UTC | 25 | 2022-01-27 07:04:51.83 UTC | 2016-01-28 14:22:55.783 UTC | null | 5,272,567 | null | 488,784 | null | 1 | 79 | git|bitbucket | 238,701 | <p>Run</p>
<pre><code>git remote -v
</code></pre>
<p>and check whether your origin's URL has your co-worker's username hardcoded in there. If so, substitute it with your own:</p>
<pre><code>git remote set-url origin <url-with-your-username>
</code></pre> |
15,207,351 | rotate3d shorthand | <p>How to combine <code>rotateX(50deg) rotateY(20deg) rotateZ(15deg)</code> in shorthand <code>rotate3d()</code>?</p> | 15,208,858 | 4 | 0 | null | 2013-03-04 17:26:38.083 UTC | 59 | 2015-07-28 14:45:48.553 UTC | 2015-07-28 14:45:48.553 UTC | null | 2,008,650 | null | 2,008,650 | null | 1 | 81 | css|css-transforms | 51,473 | <p><code>rotateX(50deg)</code> is equivalent to <code>rotate3d(1, 0, 0, 50deg)</code></p>
<p><code>rotateY(20deg)</code> is equivalent to <code>rotate3d(0, 1, 0, 20deg)</code></p>
<p><code>rotateZ(15deg)</code> is equivalent to <code>rotate3d(0, 0, 1, 15deg)</code></p>
<p>So...</p>
<p><code>rotateX(50deg) rotateY(20deg) rotateZ(15deg)</code></p>
<p>is equivalent to</p>
<p><code>rotate3d(1, 0, 0, 50deg) rotate3d(0, 1, 0, 20deg) rotate3d(0, 0, 1, 15deg)</code></p>
<hr>
<p>For a generic <code>rotate3d(x, y, z, α)</code>, you have the matrix</p>
<p><img src="https://i.stack.imgur.com/B5n9T.png" alt="generic rotate matrix"></p>
<p>where</p>
<p><img src="https://i.stack.imgur.com/YWRI3.png" alt="explanation"></p>
<hr>
<p>You now get the matrices for each of the 3 <code>rotate3d</code> transforms and you multiply them. And the resulting matrix is the matrix corresponding to the resulting single <code>rotate3d</code>. Not sure how to easy it is to extract the values for <code>rotate3d</code> out of it, but it's sure easy to extract those for a single <code>matrix3d</code>.</p>
<hr>
<p>In the first case (<code>rotateX(50deg)</code> or <code>rotate3d(1, 0, 0, 50deg)</code>), you have:</p>
<p><code>x = 1</code>, <code>y = 0</code>, <code>z = 0</code>, <code>α = 50deg</code></p>
<p>So the first row of the matrix in this case is <code>1 0 0 0</code>.</p>
<p>The second one is <code>0 cos(50deg) -sin(50deg) 0</code>.</p>
<p>The third one <code>0 sin(50deg) cos(50deg) 0</code>.</p>
<p>And the fourth one is obviously <code>0 0 0 1</code>.</p>
<hr>
<p>In the second case, you have <code>x = 0</code>, <code>y = 1</code>, <code>z = 0</code>, <code>α = 20deg</code>.</p>
<p>First row: <code>cos(20deg) 0 sin(20deg) 0</code>.</p>
<p>Second row: <code>0 1 0 0</code>.</p>
<p>Third row: <code>-sin(20) 0 cos(20deg) 0</code>.</p>
<p>Fourth: <code>0 0 0 1</code></p>
<hr>
<p>In the third case, you have <code>x = 0</code>, <code>y = 0</code>, <code>z = 1</code>, <code>α = 15deg</code>.</p>
<p>First row: <code>cos(15deg) -sin(15deg) 0 0</code>.</p>
<p>Second row <code>sin(15deg) cos(15deg) 0 0</code>.</p>
<p>And the third and the fourth row are <code>0 0 1 0</code> and <code>0 0 0 1</code> respectively.</p>
<hr>
<p><strong><em>Note</strong>: you may have noticed that the signs of the sin values for the rotateY transform are different than for the other two transforms. It's not a computation mistake. The reason for this is that, for the screen, you have the y-axis pointing down, not up.</em></p>
<hr>
<p>So these are the three <code>4x4</code> matrices that you need to multiply in order to get the <code>4x4</code> matrix for the resulting single <code>rotate3d</code> transform. As I've said, I'm not sure how easy it can be to get the 4 values out, but the 16 elements in the 4x4 matrix are exactly the 16 parameters of the <code>matrix3d</code> equivalent of the chained transform.</p>
<hr>
<p><strong>EDIT</strong>:</p>
<p>Actually, it turns out it's pretty easy... You compute the trace (sum of diagonal elements) of the matrix for the <code>rotate3d</code> matrix.</p>
<p><code>4 - 2*2*(1 - cos(α))/2 = 4 - 2*(1 - cos(α)) = 2 + 2*cos(α)</code></p>
<p>You then compute the trace for the product of the three <code>4x4</code> matrices, you equate the result with <code>2 + 2*cos(α)</code> you extract <code>α</code>. Then you compute <code>x</code>, <code>y</code>, <code>z</code>.</p>
<p>In this particular case, if I computed correctly, the trace of the matrix resulting from the product of the three <code>4x4</code> matrices is going to be:</p>
<pre><code>T =
cos(20deg)*cos(15deg) +
cos(50deg)*cos(15deg) - sin(50deg)*sin(20deg)*cos(15deg) +
cos(50deg)*cos(20deg) +
1
</code></pre>
<p>So <code>cos(α) = (T - 2)/2 = T/2 - 1</code>, which means that <code>α = acos(T/2 - 1)</code>.</p> |
15,322,391 | Django The 'image' attribute has no file associated with it | <p>When a user registers for my app.I receive this error when he reaches the profile page.</p>
<pre><code>The 'image' attribute has no file associated with it.
Exception Type: ValueError
Error during template rendering
In template C:\o\mysite\pet\templates\profile.html, error at line 6
1 <h4>My Profile</h4>
2
3 {% if person %}
4 <ul>
5 <li>Name: {{ person.name }}</li>
6 <br><img src="{{ person.image.url }}">
Traceback Switch back to interactive view
File "C:\o\mysite\pet\views.py" in Profile
71. return render(request,'profile.html',{'board':board ,'person':person})
</code></pre>
<p>I think this error happens because my template requires a image and seen he just registered he can't add a image unless he go to the edit page and adds a page then he can access the profile page.</p>
<p>My profile.html</p>
<pre><code><h4>My Profile</h4>
{% if person %}
<ul>
<li>Name: {{ person.name }}</li>
<br><img src="{{ person.image.url }}">
</ul>
{% endif %}
</code></pre>
<p>My Profile function at views.py</p>
<pre><code>def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
board = Board.objects.filter(user=request.user)
person = Person.objects.get(user=request.user)
return render(request,'profile.html',{'board':board ,'person':person})
</code></pre>
<p><em>I tried this solution by creating a 2 instance of Person object and separating them at my template with a if but it didn't succeed.</em></p>
<pre><code><h4>My Profile</h4>
{% if person %}
<ul>
<li>Name: {{ person.name }}</li>
</ul>
{% endif %}
{% if bob %}
<ul>
<br><img src="{{ bob.image.url }}">
</ul>
</code></pre>
<p><em>My solutions to the Profile function</em></p>
<pre><code>def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
board = Board.objects.filter(user=request.user)
person = Person.objects.get(user=request.user)
bob = Person.objects.get(user=request.user)
return render(request,'profile.html',{'board':board ,'person':person,'bob':bob})
</code></pre>
<p>I'm been reading the documentation for Built-in template tags and filters I think a solution here is to use ( and ) template tag but I can't seem to use it properly.</p>
<p>How can I configure this template to make picture an option. If their are no picture leave it but display the persons name.</p>
<p>Thank you for helping me</p> | 15,322,459 | 9 | 0 | null | 2013-03-10 12:47:57.677 UTC | 17 | 2022-06-08 23:53:23.133 UTC | 2013-03-10 13:26:35.117 UTC | null | 2,091,670 | null | 2,091,670 | null | 1 | 84 | django | 97,629 | <p><code>bob</code> and <code>person</code> are the same object,</p>
<pre><code>person = Person.objects.get(user=request.user)
bob = Person.objects.get(user=request.user)
</code></pre>
<p>So you can use just person for it.</p>
<p>In your template, check <code>image</code> exist or not first,</p>
<pre><code>{% if person.image %}
<img src="{{ person.image.url }}">
{% endif %}
</code></pre> |
43,663,622 | Is a date in same week, month, year of another date in swift | <p>What is the best way to know if a date is in the same week (or year or month) as another, preferably with an extension, and <strong>solely using Swift</strong>?</p>
<p>As an example, in Objective-C I have</p>
<pre><code>- (BOOL)isSameWeekAs:(NSDate *)date {
NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self];
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
return ([today weekOfYear] == [otherDay weekOfYear] &&
[today year] == [otherDay year] &&
[today era] == [otherDay era]);
}
</code></pre>
<p>Please don't propose solutions bridging <code>Date</code> to <code>NSDate</code></p> | 43,664,156 | 2 | 3 | null | 2017-04-27 16:47:06.757 UTC | 14 | 2020-03-13 02:42:48.997 UTC | null | null | null | null | 1,486,230 | null | 1 | 40 | ios|swift|date | 15,281 | <p>You can use calendar method <code>isDate(equalTo:granularity:)</code> to check it as follow:</p>
<p><strong>Xcode 11 • Swift 5.1</strong></p>
<pre><code>extension Date {
func isEqual(to date: Date, toGranularity component: Calendar.Component, in calendar: Calendar = .current) -> Bool {
calendar.isDate(self, equalTo: date, toGranularity: component)
}
func isInSameYear(as date: Date) -> Bool { isEqual(to: date, toGranularity: .year) }
func isInSameMonth(as date: Date) -> Bool { isEqual(to: date, toGranularity: .month) }
func isInSameWeek(as date: Date) -> Bool { isEqual(to: date, toGranularity: .weekOfYear) }
func isInSameDay(as date: Date) -> Bool { Calendar.current.isDate(self, inSameDayAs: date) }
var isInThisYear: Bool { isInSameYear(as: Date()) }
var isInThisMonth: Bool { isInSameMonth(as: Date()) }
var isInThisWeek: Bool { isInSameWeek(as: Date()) }
var isInYesterday: Bool { Calendar.current.isDateInYesterday(self) }
var isInToday: Bool { Calendar.current.isDateInToday(self) }
var isInTomorrow: Bool { Calendar.current.isDateInTomorrow(self) }
var isInTheFuture: Bool { self > Date() }
var isInThePast: Bool { self < Date() }
}
</code></pre> |
8,359,595 | The most efficient way to implement a phonetic search | <p>What is the most efficient way to implement a phonetic search in C++ and/or Java? By phonetic search I mean substituting vowels or consonants that sound similar. This would be especially useful for names because sometimes people's names have sort of strange spellings.</p>
<p>I am thinking it might be effective to substitue vowels and some consonants. It may also be good to include some special cases like silent E's at the end or F and PH. Would it be best to use cstrings or strings in C++? Would it be better to store a copy in memory with the substituted values or call a function every time we look for something?</p> | 8,359,636 | 2 | 0 | null | 2011-12-02 16:40:58.8 UTC | 10 | 2014-06-24 16:36:04.68 UTC | 2011-12-02 16:54:55.633 UTC | null | 1,224,599 | null | 1,224,599 | null | 1 | 18 | java|c++|string|search | 17,292 | <p><a href="http://en.wikipedia.org/wiki/Soundex" rel="noreferrer">Soundex</a> along with its variants is the standard algorithm for this. It uses phonetic rules to transform the name into an alphanumeric code. Names with the same code are grouped together.</p>
<p>As far as implementing the search, I'd use a data structure that maps each soundex code to the list of names that have that code. Depending on the data structure used (a hash table or a tree), the lookup could be done in time that is either constant on logarithmic in the number of distinct soundex codes.</p>
<p>I am not sure what exactly you mean by <code>cstring</code> (Microsoft's <code>CString</code>?) but the standard <code>std::string</code> class will be perfectly fine for this problem and would be my preferred choice.</p> |
7,751,735 | How to configure a single Jenkins job to make the release process from trunk or branches? | <p>I am currently enhancing the release process of our projects on Jenkins (1.430).</p>
<p><strong>Current release jobs</strong></p>
<p>Today, for one specific project, we have one job dedicated to the Release process.
The complete procedure is the following:</p>
<ol>
<li>The developer who is in charge of the release changes manually the version of all the pom.xml files (in fact using <code>mvn versions:set -DnewVersion=2.0</code>) to get rid of the <code>-SNAPSHOT</code>.</li>
<li>Then, he creates a tag in SVN (<a href="http://my-svn-repo/project/tags/V_2_0" rel="noreferrer">http://my-svn-repo/project/tags/V_2_0</a> for example).</li>
<li>Once this tag has been created, he logs on our Jenkins server, and starts a Release build.</li>
<li>This build will ask him which tag he wants to use for the build. The job is configured as a <em>Parameterized build</em>, with the parameter <em>List Subversion tags</em>.</li>
<li>Jenkins will then build the artifacts from this tag, and deploy them on our Nexus instance.</li>
<li>Once this is done, the developer set the pom.xml versions to the new development version (i.e. <code>2.1-SNAPSHOT</code>).</li>
</ol>
<p>The advantage of this method is that I have only Jenkins job, as the build will rely only on a tag.</p>
<p>However, this procedure involves too many human interventiosns (changes of the pom.xml, commits, tags, etc.).</p>
<p><strong>New release jobs</strong></p>
<p>Now, I use the Maven release plugin.
I've created a job that asks three information to the user who launches the build:</p>
<ul>
<li>the version of the release (parameter <code>releaseVersion</code> of the release plugin);</li>
<li>the version of development, after the release (parameter <code>developmentVersion</code> of the release plugin);</li>
<li>the name of the tag (parameter <code>tag</code> of the release plugin).</li>
</ul>
<p>This job works fine, except for one point: the job is based on the trunk or on a branch in SVN.
This means that if I have 2 branches (in addition to the trunk), I will need to create 3 release jobs: one per branch.</p>
<p>One idea to keep the best of the two worlds (i.e. using mvn release, but keeping 1 release job) it to add a build parameter that will ask the user for the path of the trunk / branch.
So instead of setting <code>http://my-svn-repo/project/trunk</code> (or <code>http://my-svn-repo/project/branches/BRANCH_V1</code>) in the job configuration, I will set <code>http://my-svn-repo/project/$FROM_BRANCH</code>, and ask the user to input the <code>FROM_BRANCH</code> parameter.</p>
<p>The problem with this solution is that the user will have to input either <code>trunk</code> or <code>branches/BRANCH_Vx</code>, which may lead to errors.</p>
<p>Ideally, I would love to have a build parameter that let me the choice of the branch (including trunk), as the parameter <em>List Subversion tags</em> exist for the choice of tags...</p>
<p>So my question: is there a better way to configure <strong>one</strong> Jenkins job that can work on all the branches?</p>
<p>Thanks.</p>
<hr/>
<p><em>Edit</em>: I found the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Validating+String+Parameter+Plugin" rel="noreferrer">Validating String</a> Jenkins plugin that can be interesting to ensure that the value defined by the user respects some regular expression. That is helpful in my case...</p> | 7,754,357 | 2 | 1 | null | 2011-10-13 09:02:47.19 UTC | 12 | 2016-12-12 15:33:56.677 UTC | 2011-10-13 11:55:44.557 UTC | null | 26,457 | null | 26,457 | null | 1 | 19 | maven|hudson|jenkins|maven-release-plugin | 49,842 | <p>You need version 1.32 of the subversion plugin. The <a href="http://issues.jenkins-ci.org/browse/JENKINS-10678">issue JENKINS-10678</a> was implemented in that version.</p>
<p>Then you only give it your project URL (which needs to contain trunk, branches, and tags) and it will offer you the trunk together with your branches.</p> |
8,365,394 | set environment variable in python script | <p>I have a bash script that sets an environment variable an runs a command</p>
<pre><code>LD_LIBRARY_PATH=my_path
sqsub -np $1 /homedir/anotherdir/executable
</code></pre>
<p>Now I want to use python instead of bash, because I want to compute some of the arguments that I am passing to the command.</p>
<p>I have tried</p>
<pre><code>putenv("LD_LIBRARY_PATH", "my_path")
</code></pre>
<p>and</p>
<pre><code>call("export LD_LIBRARY_PATH=my_path")
</code></pre>
<p>followed by</p>
<pre><code>call("sqsub -np " + var1 + "/homedir/anotherdir/executable")
</code></pre>
<p>but always the program gives up because LD_LIBRARY_PATH is not set.</p>
<p>How can I fix this?</p>
<p>Thanks for help!</p>
<p>(if I export LD_LIBRARY_PATH before calling the python script everything works, but I would like python to determine the path and set the environment variable to the correct value)</p> | 8,365,493 | 3 | 3 | null | 2011-12-03 03:56:11.36 UTC | 21 | 2022-04-14 15:28:29.07 UTC | null | null | null | null | 918,009 | null | 1 | 89 | python|export | 292,095 | <p>bash:</p>
<pre><code>LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable
</code></pre>
<p>Similar, in Python:</p>
<pre><code>import os
import subprocess
import sys
os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))
</code></pre> |
8,432,581 | How to sort a List<Object> alphabetically using Object name field | <p>I have a List of Objects like <code>List<Object> p</code>.I want to sort this list alphabetically using Object name field. Object contains 10 field and name field is one of them.</p>
<pre><code>if (list.size() > 0) {
Collections.sort(list, new Comparator<Campaign>() {
@Override
public int compare(final Object object1, final Object object2) {
return String.compare(object1.getName(), object2.getName());
}
} );
}
</code></pre>
<p>But there is nothing like String.compare..?</p> | 8,432,848 | 18 | 3 | null | 2011-12-08 14:32:51.643 UTC | 18 | 2022-04-21 16:19:32.487 UTC | 2016-03-16 15:14:37.05 UTC | null | 52,070 | null | 663,011 | null | 1 | 113 | java|list | 217,385 | <p>From your code, it looks like your <code>Comparator</code> is already parameterized with <code>Campaign</code>. This will only work with <code>List<Campaign></code>. Also, the method you're looking for is <code>compareTo</code>. </p>
<pre><code>if (list.size() > 0) {
Collections.sort(list, new Comparator<Campaign>() {
@Override
public int compare(final Campaign object1, final Campaign object2) {
return object1.getName().compareTo(object2.getName());
}
});
}
</code></pre>
<p>Or if you are using Java 1.8</p>
<pre><code>list
.stream()
.sorted((object1, object2) -> object1.getName().compareTo(object2.getName()));
</code></pre>
<p>One final comment -- there's no point in checking the list size. Sort will work on an empty list.</p> |
8,441,612 | Why is this sinon spy not being called when I run this test? | <p>I have a Backbone Model:</p>
<pre><code>class DateTimeSelector extends Backbone.Model
initialize: ->
@bind 'change:date', @updateDatetime
@bind 'change:time', @updateDatetime
updateDatetime: =>
# do some stuff with the sate and time
</code></pre>
<p>And I have some tests for that code using <a href="http://pivotal.github.com/jasmine/" rel="noreferrer">jasmin</a> and <a href="http://sinonjs.org/docs/#sinonspy" rel="noreferrer">sinon.js</a></p>
<pre><code>describe "DateTimeSelector", ->
beforeEach ->
@datetime = new DateTimeSelector()
describe "updateDatetime", ->
beforeEach ->
@updateSpy = sinon.spy(@datetime, 'updateDatetime')
afterEach ->
@datetime.updateDatetime.restore()
# passes
it "should be called when we call it", ->
@datetime.updateDatetime()
expect(@updateSpy).toHaveBeenCalledOnce()
# fails
it "should be called when we trigger it", ->
@datetime.trigger 'change:date'
expect(@updateSpy).toHaveBeenCalled()
# fails
it "should be called when we set the date", ->
@datetime.set { date: new Date() }
expect(@updateSpy).toHaveBeenCalled()
</code></pre>
<p>It seems to work when I use it in the browser but I can't seem to get the tests to pass. Can anyone enlighten me?</p> | 9,012,788 | 2 | 4 | null | 2011-12-09 05:51:39.61 UTC | 13 | 2020-09-22 07:00:04.603 UTC | 2020-09-22 07:00:04.603 UTC | null | 4,370,109 | null | 574,190 | null | 1 | 22 | javascript|backbone.js|jasmine|coffeescript|backbone-events | 21,342 | <p>duckyfuzz, you are experiencing this problem because when you are creating the spy (which actually wraps the original function and creates a level of indirection to insert its services of tracking method invocation) the binding of the events has already taken place. Which means that even though the spy wrapped the original function the event binding references the original function and not the wrapped spy. Hence, when you test, the original function gets executed on the event trigger but the spy tracking is one level above and is not executed.</p>
<p>To make sure that the event binding is actually pointing to the wrapped spy function you have to create the spy before create the model object (same goes if you are testing views). To do that create the spy on the prototype."method" of the class:</p>
<p>in the <strong>beforeEach -></strong> section before <strong>@datetime = new DateTimeSelector()</strong> create the spy: <strong>@updateSpy = sinon.spy(<em>DateTimeSelector.prototype</em>, 'updateDatetime')</strong></p>
<p>be sure to change your <strong>afterEach -></strong> section where you return the prototype back to normal, like so: <strong>@updateSpy.restore()</strong></p>
<p>this should be your code:</p>
<pre><code>describe "DateTimeSelector", ->
beforeEach ->
@updateSpy = sinon.spy(DateTimeSelector.prototype, 'updateDatetime')
@datetime = new DateTimeSelector()
afterEach ->
@updateSpy.restore()
# passes
it "should be called when we call it", ->
@datetime.updateDatetime()
expect(@updateSpy).toHaveBeenCalledOnce()
# should pass now
it "should be called when we trigger it", ->
@datetime.trigger 'change:date'
expect(@updateSpy).toHaveBeenCalled()
# should pass now
it "should be called when we set the date", ->
@datetime.set { date: new Date() }
expect(@updateSpy).toHaveBeenCalled()
</code></pre>
<p>BTW, if you are using jasmin-sinon.js plugin then your syntax is fine</p> |
4,843,495 | CSS overflow:hidden hiding a list's bullets? | <p>I've just noticed something funny. Let's say I have a HTML list:</p>
<pre><code><ol>
<li>Lorem</li>
<li>ipsum</li>
<li>dolor</li>
<li>sit amet enim. Etiam ullamcorper. Suspendisse a pellentesque dui, non felis. Maecenas malesuada elit lectus felis, malesuada ultricies. Curabitur et ligula.</li>
</ol>
</code></pre>
<p>And this CSS:</p>
<pre><code>li {
white-space: nowrap;
overflow: hidden;
}
</code></pre>
<p>The long text in the last item is indeed hacked off when it goes off the container's width, as expected. BUT! The list item numbers are affected by the <code>overflow</code> property too and are not shown.</p>
<p>However, modifying the CSS like this:</p>
<pre><code>ol {
overflow: hidden;
}
li {
white-space: nowrap;
}
</code></pre>
<p>works as intended (text won't go out of the container, but list items are shown). At least all this is true for Firefox 4 beta10.</p>
<p>Don't you think that the numbering being affected by the <code>overflow</code> is a bit illogical? Why would that happen? Is it intende behaviour? Is it in the specification or is it just some oddity someone forgot to deal with?</p> | 4,843,567 | 4 | 2 | null | 2011-01-30 14:48:16.977 UTC | 5 | 2022-04-29 09:08:46.217 UTC | null | null | null | null | 244,727 | null | 1 | 31 | html|css|overflow|html-lists | 12,509 | <p>This is the default behavior as far as I´m aware, if the <code>list-style-position</code> is <code>outside</code>, bullets of an <code>ul</code> and numbers of an <code>ol</code> do not show. At least in Firefox, I remember seeing it before in older versions.</p> |
5,020,486 | List<T> thread safety | <p>I am using the below code</p>
<pre><code>var processed = new List<Guid>();
Parallel.ForEach(items, item =>
{
processed.Add(SomeProcessingFunc(item));
});
</code></pre>
<p>Is the above code thread safe? Is there a chance of processed list getting corrupted? Or should i use a lock before adding?</p>
<pre><code>var processed = new List<Guid>();
Parallel.ForEach(items, item =>
{
lock(items.SyncRoot)
processed.Add(SomeProcessingFunc(item));
});
</code></pre>
<p>thanks.</p> | 5,020,524 | 6 | 7 | null | 2011-02-16 18:22:28.913 UTC | 6 | 2020-02-06 20:41:28.02 UTC | null | null | null | null | 237,121 | null | 1 | 35 | c#|list|c#-4.0|task-parallel-library|parallel-extensions | 17,297 | <p>No! It is not safe at all, because <code>processed.Add</code> is not. You can do following:</p>
<pre><code>items.AsParallel().Select(item => SomeProcessingFunc(item)).ToList();
</code></pre>
<p>Keep in mind that <code>Parallel.ForEach</code> was created mostly for <em>imperative</em> operations for each element of sequence. What you do is map: project each value of sequence. That is what <code>Select</code> was created for. <code>AsParallel</code> scales it across threads in most efficient manner.</p>
<p>This code works correctly:</p>
<pre><code>var processed = new List<Guid>();
Parallel.ForEach(items, item =>
{
lock(items.SyncRoot)
processed.Add(SomeProcessingFunc(item));
});
</code></pre>
<p>but makes no sense in terms of multithreading. <code>lock</code>ing at each iteration forces totally sequential execution, bunch of threads will be waiting for single thread.</p> |
4,919,912 | The HTTP request is unauthorized with client authentication scheme 'Ntlm' | <p>While calling a web service I get the following error:</p>
<blockquote>
<p>The HTTP request is unauthorized with client authentication scheme 'NTLM'. The authentication header received from the server was 'NTLM'. The HTTP request is unauthorized with client authentication scheme 'NTLM'. The authentication header received from the server was 'NTLM'.</p>
</blockquote>
<p>I have a Silverlight 4 application that calls a WCF web service, both on my IIS (7).
my WCF web service calls another ASMX web service, installed on a different web server, using NTLM (Windows Authentication).
Both servers, mine and the one hosting the ASMX web service are in the same domain.</p>
<p>When the Silverlight client opens the application from the server using <code>http://localhost/MySiteName</code> everything works fine. But when the Silverlight client opens the application from a different client, which is not the server but still in the same domain, using <code>http://MyServerName/MySiteName</code> then I get the error.</p>
<p>Windows Authentication is enabled in my IIS.
Anonymous Authentication is disabled in my IIS.</p>
<p>Binding configuration for calling my WCF web service is:</p>
<pre><code> <binding name="winAuthBasicHttpBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</code></pre>
<p>Binding configuration for calling the ASMX web service is:</p>
<pre><code> <binding name="ClNtlmBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" />
</security>
</binding>
</code></pre> | 4,920,025 | 7 | 1 | null | 2011-02-07 09:55:10.133 UTC | 6 | 2020-03-30 08:27:24.63 UTC | 2014-08-28 12:58:50.637 UTC | null | 27,756 | null | 606,212 | null | 1 | 17 | c#|.net|windows|silverlight|wcf | 124,297 | <p>OK, here are the things that come into mind:</p>
<ul>
<li>Your WCF service presumably running on IIS must be running under the security context that has the privilege that calls the Web Service. You need to make sure in the app pool with a user that is a domain user - ideally a dedicated user.</li>
<li>You can not use impersonation to use user's security token to pass back to ASMX using impersonation since <code>my WCF web service calls another ASMX web service, installed on a **different** web server</code></li>
<li>Try changing <code>Ntlm</code> to <code>Windows</code> and test again.</li>
</ul>
<hr>
<p>OK, a few words on impersonation. <s>Basically it is a known issue that you cannot use the impersonation tokens that you got to one server, to pass to another server. The reason seems to be that the token is a kind of a hash using user's password and valid for the machine generated from so it cannot be used from the middle server.</s></p>
<hr>
<h1>UPDATE</h1>
<p><strong>Delegation</strong> is possible under WCF (i.e. forwarding impersonation from a server to another server). Look at this topic <a href="http://msdn.microsoft.com/en-us/library/ms730088.aspx" rel="noreferrer">here</a>. </p> |
5,382,130 | Are instruction set and assembly language the same thing? | <p>I was wondering if <a href="http://en.wikipedia.org/wiki/Instruction_set">instruction set</a> and <a href="http://en.wikipedia.org/wiki/Assembly_language">assembly language</a> are the same thing? </p>
<p>If not, how do they differ and what are their relations?</p>
<p>Thanks and regards!</p> | 5,384,544 | 7 | 3 | null | 2011-03-21 18:44:58.213 UTC | 23 | 2017-02-01 19:56:19.707 UTC | null | null | null | null | 156,458 | null | 1 | 27 | assembly|instruction-set | 20,208 | <p>I think everyone is giving you the same answer. Instruction set is is the set (as in math) of all instructions the processor can execute or understand. Assembly language is a programming language. </p>
<p>Let me try some examples based on some of the questions you are asking. And I am going to be jumping around from processor to processor with whatever code I have handy.</p>
<p>Instruction or opcode or binary or machine language, whatever term you want to use for the bits/bytes that are loaded into the processor to be decoded and executed. An example </p>
<pre><code>0x5C0B
</code></pre>
<p>The assembly language, would be</p>
<pre><code>add r12,r11
</code></pre>
<p>For this particular processor. In this case that means r11 = r11 + r12. So I put that text, the add r12,r11 in a text file and use an assembler (a program that compiles/assembles assembly language) to assemble it into some form of binary. Like any programming language sometimes you create object files then link them together, sometimes you can go straight to a binary. And there are many forms of binaries which are in ascii and binary forms and a whole other discussion.</p>
<p>Now what can you do in assembler that is not part of the instruction set? How do they differ? Well for starters you can have macros:</p>
<pre><code>.macro add3 arg1, arg2, arg3
add \arg1,\arg3
add \arg2,\arg3
.endm
.text
add3 r10,r11,r12
</code></pre>
<p>Macros are like inline functions, they are not functions that are called but generate code in line. No different than a C macro for example. So you might use them to save some typing or you might use them to abstract something that you want to do over and over again and want the ability to change in one place and not have to touch every instance. The above example essentially generates this:</p>
<pre><code>add r10,r12
add r11,r12
</code></pre>
<p>Another difference between the instruction set and assembly langage are pseudo instructions, for this particular instruction set for example there is no pop instruction for popping things off the stack at least not by that name, and I will explain why. But you are allowed to save some typing and use a pop in your code:</p>
<pre><code>pop r12
</code></pre>
<p>The reason why there is no pop is because the addressing modes are flexible enough to have a read from the address in the source register put the value in the destination register and increment the source register by a word. Which in assembler for this instruction set is</p>
<pre><code>mov @r1+,r12
</code></pre>
<p>both the pop and the mov result in the opcode 0x413C.</p>
<p>Another example of differences between the instruction set and assembler, switching instruction sets, is something like this:</p>
<pre><code>ldr r0,=bob
</code></pre>
<p>Which to this assembly language means load the address of bob into register 0, there is no instruction for that, what the assembler does with it is generate something that would look like this if you were to write it in assembler by hand:</p>
<pre><code>ldr r0,ZZ123
...
ZZ123: .word bob
</code></pre>
<p>Essentially, in a reachable place from that instruction, not in the execution path, a word is created which the linker will fill in with the address for bob. The ldr instruction likewise by the assembler or linker will get encoded with an ldr of a pc relative instruction. </p>
<p>That leads to a whole category of differences between the instruction set and the assembly language</p>
<pre><code>call fun
</code></pre>
<p>Machine code has no way of knowing what fun is or where to find it. For this instruction set with its many addressing modes (note I am specifically and intentionally avoiding naming the instruction sets I am using as that is not relevant to the discussion) the assembler or linker as the case may be (depending on where the fun function ends up being relative to this instruction).</p>
<p>The assembler may choose to encode that instruction as pc relative, if the fun function is 40 bytes ahead of the call instruction it may encode it with the equivalent of call pc+36 (take four off because the pc is one instruction ahead at execution time and this is a 4 byte instruction).</p>
<p>Or the assembler may not know where or what fun is and leave it up to the linker, and in that case the linker may put the absolute address of the function something that would be similar to call #0xD00D.</p>
<p>Same goes for loads and stores, some instruction sets have near and far pc relative, some have absolute address, etc. And you may not care to choose, you may just say </p>
<pre><code>mov bob,r1
</code></pre>
<p>and the assembler or linker or a combination of the two takes care of the rest.</p>
<p>Note that for some instruction sets the assembler and linker may happen at once in one program. These days we are used to the model of compiling to objects and then linking objects, but not all assemblers follow that model.</p>
<p>Some more cases where the assembly language can take some shortcuts:</p>
<pre><code>hang: b hang
b .
b 2f
1:
b 1b
b 1f
1:
b 1b
2:
</code></pre>
<p>The hang: b hang makes sense, branch to the label called hang. Essentially a branch to self. And as the name implies this is an infinite loop. But for this assembly language b . means branch to self, an infinite loop but I didnt have to invent a label, type it and branch to it. Another shortcut is using numbers b 1b means branch to 1 back, the assembler looks for the label number 1 behind or above the instruction. The b 1f, which is not a branch to self, means branch 1 forward, this is perfectly valid code for this assembler. It will look forward or below the line of code for a label number 1: And you can re-use number 1 like crazy in your assembly language program for this assembler, saves on having to invent label names for simple short branches. The second b 1b branches to the second 1. and is a branch to self.</p>
<p>It is important to understand that the company that created the processor defines the instruction set, and the machine code or opcodes or whatever term they or you use for the bits and bytes the processor decodes and executes. Very often that company will produce a document with assembly language for those instructions, a syntax. Often that company will produce an assembler program to compile/assemble that assembly language...using that syntax. But that doesnt mean that any other person on the planet that chooses to write an assembler for that instruction set has to use that syntax. This is very evident with the x86 instruction set. Likewise any psuedo instructions like the pop above or macro syntax or other short cuts like the b 1b have to be honored from one assembler to another. And very often are not, you see this with ARM for example the universal comment symbol of ; does not work with gnu assembler you have to use @ instead. ARMs assembler does use the ; (note I write my arm assembler with ;@ to make it portable). It gets even worse with gnu tools for example you can can put C language things like #define and /* comment */ in your assembler and use the C compiler instead of the assembler and it will work. I prefer to stay as pure as I can for maximum portability, but naturally you may choose to use whatever features the tool offers.</p> |
4,887,668 | How to update a single attribute without touching the updated_at attribute? | <p>How can I achieve this?</p>
<p>tried to create 2 methods, called </p>
<pre><code>def disable_timestamps
ActiveRecord::Base.record_timestamps = false
end
def enable_timestamps
ActiveRecord::Base.record_timestamps = true
end
</code></pre>
<p>and the update method itself:</p>
<pre><code>def increment_pagehit
update_attribute(:pagehit, pagehit+1)
end
</code></pre>
<p>turn timestamps on and off using callbacks like:</p>
<pre><code>before_update :disable_timestamps, :only => :increment_pagehit
after_update :enable_timestamps, :only => :increment_pagehit
</code></pre>
<p>but it's not updating anything, even the desired attribute (pagehit).</p>
<p>Any advice? I don't want to have to create another table just to count the pagehits.</p> | 4,887,798 | 7 | 2 | null | 2011-02-03 14:52:59.547 UTC | 7 | 2019-11-02 04:47:34.49 UTC | 2019-11-02 04:47:34.49 UTC | null | 266,087 | null | 585,101 | null | 1 | 50 | ruby-on-rails|ruby|ruby-on-rails-3 | 37,398 | <p><a href="https://stackoverflow.com/questions/861448/is-there-a-way-to-avoid-automatically-updating-rails-timestamp-fields">Is there a way to avoid automatically updating Rails timestamp fields?</a></p>
<p>Or closer to your question:</p>
<p><a href="http://blog.bigbinary.com/2009/01/21/override-automatic-timestamp-in-activerecord-rails.html" rel="nofollow noreferrer">http://blog.bigbinary.com/2009/01/21/override-automatic-timestamp-in-activerecord-rails.html</a></p> |
5,419,459 | How to allow only one radio button to be checked? | <pre><code>{% for each in AnswerQuery %}
<form action={{address}}>
<span>{{each.answer}}</span><input type='radio'>
<span>Votes:{{each.answercount}}</span>
<br>
</form>
{% endfor %}
</code></pre>
<p>This is a part my <a href="https://www.djangoproject.com/" rel="noreferrer">django</a> template, what it supposed to do is to print out several radio buttons, corresponding to the answers assigned to the buttons. But I don't know why I can check multiple radio buttons, which messed me up. It is supposed to only let me check on one radio button and I had that somehow but I lost it. Any help? Thank you. </p> | 5,419,479 | 8 | 0 | null | 2011-03-24 12:54:35.44 UTC | 40 | 2021-10-30 13:37:21.42 UTC | 2018-12-28 11:25:17.153 UTC | user8554766 | null | null | 624,392 | null | 1 | 188 | html|django|forms | 435,983 | <p>Simply give them the same name:</p>
<pre><code><input type="radio" name="radAnswer" />
</code></pre> |
5,285,711 | Is it possible to run a single test in MiniTest? | <p>I can run all tests in a single file with:</p>
<pre><code>rake test TEST=path/to/test_file.rb
</code></pre>
<p>However, if I want to run just one test in that file, how would I do it?</p>
<p>I'm looking for similar functionality to:</p>
<pre><code>rspec path/to/test_file.rb -l 25
</code></pre> | 10,328,441 | 15 | 1 | null | 2011-03-12 21:45:31.993 UTC | 40 | 2022-02-08 11:27:40.16 UTC | 2016-06-05 19:25:14.217 UTC | null | 102,401 | null | 283,952 | null | 1 | 201 | ruby|ruby-on-rails-3|minitest | 72,449 | <blockquote>
<p>I'm looking for similar functionality to rspec path/to/file.rb -l 25</p>
</blockquote>
<p>With <a href="http://github.com/qrush/m" rel="nofollow noreferrer">Nick Quaranto's "m" gem</a>, you can say:</p>
<pre><code>m spec/my_spec.rb:25
</code></pre> |
5,067,619 | JPA: what is the proper pattern for iterating over large result sets? | <p>Let's say I have a table with millions of rows. Using JPA, what's the proper way to iterate over a query against that table, such that <strong>I don't have all an in-memory List</strong> with millions of objects?</p>
<p>For example, I suspect that the following will blow up if the table is large:</p>
<pre><code>List<Model> models = entityManager().createQuery("from Model m", Model.class).getResultList();
for (Model model : models)
{
System.out.println(model.getId());
}
</code></pre>
<p>Is pagination (looping and manually updating <code>setFirstResult()</code>/<code>setMaxResult()</code>) really the best solution?</p>
<p><strong>Edit</strong>: the primary use-case I'm targeting is a kind of batch job. It's fine if it takes a long time to run. There is no web client involved; I just need to "do something" for each row, one (or some small N) at a time. I'm just trying to avoid having them all in memory at the same time.</p> | 5,071,436 | 16 | 1 | null | 2011-02-21 15:13:30.783 UTC | 55 | 2022-06-08 11:18:20.717 UTC | 2011-02-21 17:02:48.957 UTC | null | 93,995 | null | 93,995 | null | 1 | 124 | java|hibernate|jpa | 108,911 | <p>Page 537 of <a href="https://rads.stackoverflow.com/amzn/click/com/1932394885" rel="noreferrer" rel="nofollow noreferrer">Java Persistence with Hibernate</a> gives a solution using <code>ScrollableResults</code>, but alas it's only for Hibernate. </p>
<p>So it seems that using <code>setFirstResult</code>/<code>setMaxResults</code> and manual iteration really is necessary. Here's my solution using JPA:</p>
<pre><code>private List<Model> getAllModelsIterable(int offset, int max)
{
return entityManager.createQuery("from Model m", Model.class).setFirstResult(offset).setMaxResults(max).getResultList();
}
</code></pre>
<p>then, use it like this:</p>
<pre><code>private void iterateAll()
{
int offset = 0;
List<Model> models;
while ((models = Model.getAllModelsIterable(offset, 100)).size() > 0)
{
entityManager.getTransaction().begin();
for (Model model : models)
{
log.info("do something with model: " + model.getId());
}
entityManager.flush();
entityManager.clear();
em.getTransaction().commit();
offset += models.size();
}
}
</code></pre> |
5,404,839 | How do I refresh a page using JavaScript? | <p>How do I refresh a page using JavaScript?</p> | 5,404,869 | 32 | 4 | null | 2011-03-23 11:55:31.87 UTC | 371 | 2022-09-23 09:34:22.497 UTC | 2022-07-17 06:23:26.007 UTC | null | 365,102 | null | 505,762 | null | 1 | 2,681 | javascript|jquery|refresh|reload | 2,948,835 | <p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/reload" rel="noreferrer"><code>location.reload()</code></a>.</p>
<p>For example, to reload whenever an element with <code>id="something"</code> is clicked:</p>
<pre><code>$('#something').click(function() {
location.reload();
});
</code></pre>
<p>The <code>reload()</code> function takes an optional parameter that can be set to <code>true</code> to force a reload from the server rather than the cache. The parameter defaults to <code>false</code>, so by default the page may reload from the browser's cache.</p> |
16,702,011 | Tomcat deploying the same application twice in netbeans | <p>I'm using <a href="https://netbeans.org" rel="noreferrer">NetBeans</a> and <a href="https://tomcat.apache.org" rel="noreferrer">Tomcat</a> seems to be deploying in <a href="https://en.wikipedia.org/wiki/WAR_(file_format)" rel="noreferrer">.war</a> application twice, a double launch of the web app.</p>
<p>I've tried both Tomcat 6 and 7 and the same result.</p>
<p>I've got a Spring MVC, Hibernate and Thymeleaf application.
Context.xml under META-INF has the following content:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<Context path="/website"/>
</code></pre>
<p>Here is the log.</p>
<pre class="lang-none prettyprint-override"><code>**First deployment starts**
[ INFO] 07:13:09 ContextLoader - Root WebApplicationContext: initialization started
[ INFO] 07:13:09 XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Thu May 23 07:13:09 EST 2013]; root of context hierarchy
2013-05-23 07:13:10 JRebel: Monitoring Spring bean definitions in '/Users/pack/NetBeansProjects/mysite/site/src/main/webapp/WEB-INF/applicationContext- data.xml'.
[ INFO] 07:13:10 XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext-data.xml]
[ INFO] 07:13:10 ClassPathScanningCandidateComponentProvider - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
***(tomcat initializes hibernate and other spring beans)***
...
May 23, 2013 7:13:17 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 15552 ms
***Tomcat started***
***Tomcat tries to shut down the context***
[ INFO] 07:13:18 XmlWebApplicationContext - Closing WebApplicationContext for namespace 'spring-mvc-servlet': startup date [Thu May 23 07:13:15 EST 2013]; parent: Root WebApplicationContext
[ INFO] 07:13:18 DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5bbe2de2: defining beans [blHeadProcessor,blHeadProcessorExtensionManager,navigationProcessor,blPaginationPageLinkPro cessor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,blRegisterCustomerValidator,blCategoryController,com.package.ui.thymeleaf.CategoryHandlerMapping#0,templateResolver,templateEngine,org.thymeleaf.spring3.view.ThymeleafViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@521e7f21
[ INFO] 07:13:18 XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Thu May 23 07:13:09 EST 2013]; root of context hierarchy
[ INFO] 07:13:18 DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@521e7f21: defining beans [org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0,blCategoryDao,blCustomerDao,blIdGenerationDao,nlpDao,jpaTemplate,webDS,entityManagerFactory,transactionManager,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.web.DefaultSecurityFilterChain#1,org.springframework.security.web.DefaultSecurityFilterChain#2,org.springframework.security.web.DefaultSecurityFilterChain#3,org.springframework.security.web.DefaultSecurityFilterChain#4,org.springframework.security.web.DefaultSecurityFilterChain#5,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.PortResolverImpl#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.web.access.channel.ChannelDecisionManagerImpl#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#6,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager,blUserDetailsService,blCatalogService,blCustomerService,entityService,fbPageService,blIdGenerationService,blLoginService,nlpService,priceIncreaseValidator,searchFacetService,blEntityConfiguration,blPasswordEncoder,solrIndexService,solrEmbedded,textEncryptor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
[ INFO] 07:13:18 LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'blPU'
[ INFO] 07:13:18 SessionFactoryImpl - closing
May 23, 2013 7:13:18 AM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
SEVERE: The web application [/website] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
May 23, 2013 7:13:19 AM org.apache.catalina.startup.HostConfig deleteRedeployResources
INFO: Undeploying context [/website]
May 23, 2013 7:13:19 AM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /Users/pack/Servers/apache-tomcat- 7.0.34/conf/Catalina/localhost/website.xml
2013-05-23 07:13:23 JRebel: Monitoring Log4j configuration in 'file:/Users/pack/NetBeansProjects/mysite/site/target/mycompany/WEB-INF/classes/log4j.xml'.
***Tomcat tries to restart again***
[ INFO] 07:13:23 ContextLoader - Root WebApplicationContext: initialization started
[ INFO] 07:13:23 XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Thu May 23 07:13:23 EST 2013]; root of context hierarchy
2013-05-23 07:13:24 JRebel: Monitoring Spring bean definitions in '/Users/pack/NetBeansProjects/mysite/site/src/main/webapp/WEB-INF/applicationContext- data.xml'.
[ INFO] 07:13:24 XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext-data.xml]
</code></pre>
<p>and it start successfully.</p>
<p>What I don't understand is why is Tomcat is deploying the application twice.
This does not occur the first time I deploy the application on a new tomcat instance because the website.xml file is not in tomcats /conf/catalina/localhost folder yet. But when I stop and run tomcat from netbeans again the website.xml file is still in the /conf/catalina/localhost folder but get deleted and re-deployed just before the second deployment is about to happen.</p>
<p>I've tried setting <code>autoDeploy</code> in server.xml file of Tomcat to false but it didn't help.</p>
<pre><code><Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="false">
</code></pre>
<p>May be Tomcat should be deleting the website.xml file under /conf/catalina/localhost folder everytime tomcat stops. </p>
<p>This is how website.xml file under localhost folder looks like</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<Context
docBase="/Users/pack/NetBeansProjects/mysite/site/target/mycompany"
path="/website"
/>
</code></pre> | 21,418,409 | 4 | 0 | null | 2013-05-22 21:39:09.763 UTC | 11 | 2020-12-22 11:09:11.35 UTC | 2016-04-18 06:22:10.587 UTC | null | 642,706 | null | 1,378,771 | null | 1 | 9 | maven|tomcat|netbeans | 6,709 | <p>I found that deleting the file conf/localhost/myappname.xml prevents the app from initializing twice. Basically Tomcat is restarting, and restarting the old version of your app. Then it starts again when Netbeans deploys it. As a workaround, I added a few lines of code in my ContextListener contextDestroyed() event:</p>
<pre><code>public void contextDestroyed(ServletContextEvent sce) {
...
String delme = sce.getServletContext().getInitParameter("eraseOnExit");
if (delme != null && delme.length() > 0) {
File del = new File(delme);
if (del.exists()) {
System.out.println("Deleting file " + delme);
del.delete();
}
}
</code></pre>
<p>In the web.xml add the following in a dev environment:</p>
<pre><code><context-param>
<description>Workaround for Tomcat starting webapp twice</description>
<param-name>eraseOnExit</param-name>
<param-value>/Users/xxx/apache-tomcat-7.0.42/conf/Catalina/localhost/myappname.xml</param-value>
</context-param>
</code></pre>
<p>Then the next time the app is deployed, it won't be started again prior to the deployment, hence will not start twice. Any other ideas for deleting a file prior to deploying, or on shutdown, would be appreciated.</p> |
29,544,738 | Xcode 6.3 freezes/hangs after opening XIB file | <p>After upgrading to Xcode 6.3 (release version), Xcode now freeze every time I open a XIB/Storyboard file that includes an <code>IB_DESIGNABLE</code> view <del>that uses a custom font</del> for any projects and includes a custom font (not necessarily to have reference to that font in that XIB/Storyboard). The freeze occurs after opening the .xib file and then attempting to switch to any other file. Xcode hangs and must be force quit.</p>
<p>I have opened a bug report with Apple. (Bug 20483867).</p>
<p>Right now, I have two work arounds.</p>
<ol>
<li>Download and use Xcode 6.2 from Apple.</li>
<li>Remove the IB_DESIGNABLE tags from the custom view header files.</li>
</ol>
<p>This is likely an Apple bug, but does anyone have a better work around or solution?</p> | 29,781,554 | 10 | 11 | null | 2015-04-09 17:05:58.547 UTC | 25 | 2018-04-12 13:18:13.293 UTC | 2018-04-12 13:18:13.293 UTC | null | 600,753 | null | 600,753 | null | 1 | 82 | ios|xcode|xcode6.3 | 14,117 | <p>Xcode 6.3.1 fixes the problem with custom fonts and <code>IB_DESIGNABLE</code> views in a Storyboard. Update via the Mac App Store, and you should be good.</p> |
12,340,470 | Compare containers with GoogleTest | <p>I'm trying to get a working googletest test that compares two vectors. For this I'm using google mock with its <a href="https://github.com/google/googletest/blob/master/docs/gmock_cheat_sheet.md#matchers-matcherlist" rel="nofollow noreferrer">matchers</a> but I get a C3861 error saying "ContainerEq identifier not found" and also C2512 saying "testing::AssertionResult has not a proper default constructor available". Why?</p>
<pre><code>TEST(MyTestSuite, MyTest)
{
std::vector<int> test1;
std::vector<int> test2;
...
EXPECT_THAT(test1, ContainerEq(test2));
}
</code></pre> | 12,340,578 | 2 | 0 | null | 2012-09-09 15:42:03.63 UTC | 8 | 2022-08-05 04:21:24.9 UTC | 2021-01-25 12:06:20.103 UTC | null | 5,970,163 | null | 410,560 | null | 1 | 14 | c++|googletest|googlemock | 21,701 | <p>You're just missing gtest's <code>testing</code> namespace qualifier:</p>
<pre><code>EXPECT_THAT(test1, ::testing::ContainerEq(test2));
</code></pre> |
12,569,833 | Generic methods returning dynamic object types | <p>Possibly a question which has been asked before, but as usual the second you mention the word generic you get a thousand answers explaining type erasure. I went through that phase long ago and know now a lot about generics and their use, but this situation is a slightly more subtle one.</p>
<p>I have a container representing a cell of data in an spreadsheet, which actually stores the data in two formats: as a string for display, but also in another format, dependent on the data (stored as object). The cell also holds a transformer which converts between the type, and also does validity checks for type (e.g. an IntegerTransformer checks if the string is a valid integer, and if it is returns an Integer to store and vice versa). </p>
<p>The cell itself is not typed as I want to be able to change the format (e.g. change the secondary format to float instead of integer, or to raw string) without having to rebuild the cell object with a new type. a previous attempt did use generic types but unable to change the type once defined the coding got very bulky with a lot of reflection. </p>
<p>The question is: how do I get the data out of my Cell in a typed way? I experimented and found that using a generic type could be done with a method even though no constraint was defined</p>
<pre><code>public class Cell {
private String stringVal;
private Object valVal;
private Transformer<?> trans;
private Class<?> valClass;
public String getStringVal(){
return stringVal;
}
public boolean setStringVal(){
//this not only set the value, but checks it with the transformer that it meets constraints and updates valVal too
}
public <T> T getValVal(){
return (T) valVal;
//This works, but I don't understand why
}
}
</code></pre>
<p>The bit that puts me off is: that is ? it can't be casting anything, there is no input of type T which constrains it to match anything, actually it doesn't really say anything anywhere. Having a return type of Object does nothing but give casting complications everywhere.</p>
<p>In my test I set a Double value, it stored the Double (as an object), and when i did Double testdou = testCell.getValVal(); it instantly worked, without even an unchecked cast warning. however, when i did String teststr = testCell.getValVal() I got a ClassCastException. Unsurprising really.</p>
<p>There are two views I see on this:</p>
<p>One: using an undefined Cast to seems to be nothing more than a bodge way to put the cast inside the method rather than outside after it returns. It is very neat from a user point of view, but the user of the method has to worry about using the right calls: all this is doing is hiding complex warnings and checks until runtime, but seems to work.</p>
<p>The second view is: I don't like this code: it isn't clean, it isn't the sort of code quality I normaly pride myself in writing. Code should be correct, not just working. Errors should be caught and handled, and anticipated, interfaces should be foolproof even if the only expecter user is myself, and I always prefer a flexible generic and reusable technique to an awkward one off. The problem is: is there any normal way to do this? Is this a sneaky way to achieve the typeless, all accepting ArrayList which returns whatever you want without casting? or is there something I'm missing here. Something tells me I shouldn't trust this code!</p>
<p>perhaps more of a philosophical question than I intended but I guess that's what I'm asking.</p>
<p>edit: further testing.</p>
<p>I tried the following two interesting snippets:</p>
<pre><code>public <T> T getTypedElem() {
T output = (T) this.typedElem;
System.out.println(output.getClass());
return output;
}
public <T> T getTypedElem() {
T output = null;
try {
output = (T) this.typedElem;
System.out.println(output.getClass());
} catch (ClassCastException e) {
System.out.println("class cast caught");
return null;
}
return output;
}
</code></pre>
<p>When assigning a double to typedElem and trying to put it into a String I get an exception NOT on the cast to , but on the return, and the second snippet does not protect. The output from the getClass is java.lang.Double, suggesting that is being dynamically inferred from typedElem, but that compiler level type checks are just forced out of the way. </p>
<p>As a note for the debate: there is also a function for getting the valClass, meaning it's possible to do an assignability check at runtime.</p>
<p>Edit2: result</p>
<p>After thinking about the options I've gone with two solutions: one the lightweight solution, but annotated the function as @depreciated, and second the solution where you pass it the class you want to try to cast it as. this way it's a choice depending on the situation. </p> | 12,570,045 | 3 | 3 | null | 2012-09-24 17:21:15.22 UTC | 14 | 2012-09-25 05:59:31.47 UTC | 2012-09-25 05:59:31.47 UTC | null | 581,580 | null | 581,580 | null | 1 | 27 | java|generics|methods|casting | 52,878 | <p>You could try type tokens:</p>
<pre><code>public <T> T getValue(Class<T> cls) {
if (valVal == null) return null;
else {
if (cls.isInstance(valVal)) return cls.cast(valVal);
return null;
}
}
</code></pre>
<p>Note, that this does not do any conversion (i.e., you cannot use this method to extract a <code>Double</code>, if <code>valVal</code> is an instance of <code>Float</code> or <code>Integer</code>). </p>
<p>You should get, btw., a compiler warning about your definition of <code>getValVal</code>. This is, because the cast cannot be checked at run-time (Java generics work by "erasure", which essentially means, that the generic type parameters are forgotten after compilation), so the generated code is more like:</p>
<pre><code>public Object getValVal() {
return valVal;
}
</code></pre> |
12,134,200 | How to integrate d3.js chart in C# application? | <p>I am a big fan of Mike Bostock's d3.js chart library: d3js.org.</p>
<p>I would like to use it to display charts in a C# .Net application, but I don't know if it is possible.</p>
<p>It may be possible by generating HTM+JS codes and rendering it in a webbrowser window.
However, I understood d3.js library cannot be used locally without a webserver (However I did not understood what works without a webserver and what requires a webserver), therefore a simple solution does not work. </p>
<p>Has anybody tried to develop that kind of deployment of d3.js charts?
Do you have an idea on where to start in order to have the most simple solution?</p> | 12,159,427 | 3 | 2 | null | 2012-08-26 21:51:10.307 UTC | 18 | 2019-04-06 10:40:11.123 UTC | 2012-10-17 02:06:45.497 UTC | null | 76,337 | null | 1,626,386 | null | 1 | 37 | c#|.net|d3.js | 27,078 | <p>A web server definitely isn't required to use a client side JavaScript library like d3.js.</p>
<p>For C#, you'll need to embed a web browser control (in either WindowsForms or WPF).</p>
<p>You'll need to make sure that the browser is working in IE9 Standards mode as shown <a href="http://www.wiredprairie.us/blog/index.php/archives/1720" rel="noreferrer">here</a>.</p>
<p>Create your web pages as you would normally. Navigate to them using webbrowser.navigate (as just files on the file system.)</p>
<p>This should work.</p> |
12,362,901 | Doctrine2 one-to-one relation auto loads on query | <p>I have a query that looks like this:</p>
<p>My user entity has a one-to-one relation that looks like this:</p>
<pre><code>/**
* @var UserProfile
*
* @ORM\OneToOne(targetEntity="UserProfile",mappedBy="user")
*/
private $userProfile;
</code></pre>
<p>Anytime I make a query to select multiple user objects, it creates an additional select statement per user to query for the UserProfile data even though I am not accessing it through a get method. I don't always need the UserProfile data, and I certainly don't want to load this data every single time I'm displaying a list of users.</p>
<p>Any idea why these queries are executed at run time?</p> | 22,253,783 | 6 | 0 | null | 2012-09-11 04:45:24.223 UTC | 16 | 2021-10-26 13:32:02.41 UTC | null | null | null | null | 5,865 | null | 1 | 40 | doctrine-orm | 16,884 | <p>Here is solutions explain with details :</p>
<p><a href="https://groups.google.com/forum/#!topic/doctrine-user/fkIaKxifDqc">https://groups.google.com/forum/#!topic/doctrine-user/fkIaKxifDqc</a></p>
<blockquote>
<p>"fetch" in the mapping is a <em>hint</em>, that is, if it is possible
Doctrine does that, but if its not possible, obviously it does not.
Proxying for lazy-loading is simply not always possible, technically.
The situations where its not possible are:</p>
<p>1) one-to-one from inverse to owning side (appears only in
bidirectional one-to-one associations). Precondition a) above can not
be met. 2) one-to-one/many-to-one association to a hierarchy and the
targeted class has subclasses (is not a leaf in the class hierarchy).
Precondition b) above can not be met.</p>
<p>In these cases, proxying is technically not possible.</p>
<p>Your options to avoid this n+1 problem:</p>
<p>1) fetch-join via DQL: "select c,ca from Customer join c.cart ca".
Single query but join, however, joins on to-one associations are
relatively cheap. </p>
<p>2) force partial objects. No additional queries but
also no lazy-load: $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD,
true)</p>
<p>3) if an alternative result format (i.e. getArrayResult()) is
sufficient for a use-case, these also avoid this problem.</p>
<p>Benjamin had some ideas about automatic batching of these loads to
avoid n+1 queries but this does not change the fact that proxying is
not always possible.</p>
</blockquote> |
12,325,454 | How to get text of an element in Selenium WebDriver, without including child element text? | <pre><code><div id="a">This is some
<div id="b">text</div>
</div>
</code></pre>
<p>Getting "This is some" is non-trivial. For instance, this returns "This is some text":</p>
<pre><code>driver.find_element_by_id('a').text
</code></pre>
<p>How does one, in a general way, get the text of a specific element without including the text of it's children?</p>
<p>(I'm providing an answer below but will leave the question open in case someone can come up with a less hideous solution).</p> | 19,040,341 | 5 | 1 | null | 2012-09-07 21:11:21.513 UTC | 16 | 2020-04-15 05:18:17.94 UTC | 2019-05-29 16:24:54.12 UTC | null | 5,780,109 | null | 534,086 | null | 1 | 54 | python|html|selenium|selenium-webdriver | 150,305 | <p>Here's a general solution:</p>
<pre><code>def get_text_excluding_children(driver, element):
return driver.execute_script("""
return jQuery(arguments[0]).contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
""", element)
</code></pre>
<p>The element passed to the function can be something obtained from the <code>find_element...()</code> methods (i.e. it can be a <code>WebElement</code> object).</p>
<p>Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:</p>
<pre><code>return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
if (child.nodeType === Node.TEXT_NODE)
ret += child.textContent;
child = child.nextSibling;
}
return ret;
""", element)
</code></pre>
<p>I'm actually using this code in a test suite.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.