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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,567,326 | How does getContentResolver() work? | <p>I watched a course about <code>ContentProvider</code> on the Internet demonstrating how to define and use a <code>ContentProvider</code>.</p>
<p>I was confused about using the method named <code>getContentResolver()</code>. What does this method return?</p>
<p>My <code>ContentProvider</code> is not instanced and the code just writes that <code>getContentProvider().query()</code>.</p>
<p>I don't understand how <code>ContentProvider</code> works.</p> | 17,567,462 | 2 | 1 | null | 2013-07-10 09:41:01.643 UTC | 11 | 2016-08-06 02:28:10.827 UTC | 2016-08-06 02:28:10.827 UTC | null | 2,305,826 | null | 2,315,009 | null | 1 | 22 | android|android-contentresolver | 30,803 | <p>It returns Content Resolver. </p>
<hr>
<p><strong>What is the Content Resolver?</strong></p>
<p>The Content Resolver is the single, global instance in your application that provides access to your (and other applications') content providers. The Content Resolver behaves exactly as its name implies: it accepts requests from clients, and resolves these requests by directing them to the content provider with a distinct authority. To do this, the Content Resolver stores a mapping from authorities to Content Providers. This design is important, as it allows a simple and secure means of accessing other applications' Content Providers.</p>
<p>The Content Resolver includes the CRUD (create, read, update, delete) methods corresponding to the abstract methods (insert, delete, query, update) in the Content Provider class. The Content Resolver does not know the implementation of the Content Providers it is interacting with (nor does it need to know); each method is passed an URI that specifies the Content Provider to interact with.</p>
<hr>
<p><strong>What is the Content Provider?</strong></p>
<p>Whereas the Content Resolver provides an abstraction from the application's Content Providers, Content Providers provides an abstraction from the underlying data source (i.e. a <code>SQLite database</code>). They provide mechanisms for defining data security (i.e. by enforcing read/write permissions) and offer a standard interface that connects data in one process with code running in another process.</p>
<p>Content Providers provide an interface for publishing and consuming data, based around a simple URI addressing model using the <code>content:// schema</code>. They enable you to decouple your application layers from the underlying data layers, making your application data-source agnostic by abstracting the underlying data source.</p>
<p>Source - <a href="http://www.androiddesignpatterns.com/2012/06/content-resolvers-and-content-providers.html" rel="noreferrer">androiddesignpatterns</a></p> |
17,453,105 | Android open pdf file | <p>I'm developing an Android application and I have to open some files.</p>
<p>This is my code using intent:</p>
<pre><code>public class FacturaActivity extends Activity {
(...)
public void downloadInvoice(View view) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
}
</code></pre>
<p>File is in the root directory of the SD card and I can manually open it.</p>
<p><strong>Problem</strong></p>
<p>Application is closed when it arrives at startActivity(intent). I think the problem is in AndroidManifest.xml file, but I don't know how to put it correctly.</p>
<p><strong>AndroidManifest.xml</strong></p>
<pre><code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name="###.MyApplication" > <!--cant show complete name-->
<activity
android:name="###.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FacturaActivity" >
</activity>
</application>
</code></pre>
<p></p>
<p><strong>LogCat</strong></p>
<pre><code>07-03 15:49:13.094: E/AndroidRuntime(1032): FATAL EXCEPTION: main
07-03 15:49:13.094: E/AndroidRuntime(1032): java.lang.IllegalStateException: Could not execute method of the activity
(...)
07-03 15:49:13.094: E/AndroidRuntime(1032): Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///mnt/sdcard/201209_F2012212782.PDF typ=application/pdf flg=0x40000000 }
07-03 15:49:13.094: E/AndroidRuntime(1032): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1408)
07-03 15:49:13.094: E/AndroidRuntime(1032): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1378)
07-03 15:49:13.094: E/AndroidRuntime(1032): at android.app.Activity.startActivityForResult(Activity.java:2817)
07-03 15:49:13.094: E/AndroidRuntime(1032): at android.app.Activity.startActivity(Activity.java:2923)
</code></pre>
<p>Can you help me to complete AndroidManifest? Or how can I open that pdf?</p> | 17,453,242 | 6 | 3 | null | 2013-07-03 16:16:21.62 UTC | 18 | 2022-04-02 13:47:00.797 UTC | 2014-01-12 16:30:17.097 UTC | null | 321,731 | null | 1,088,643 | null | 1 | 40 | android|file|pdf|android-manifest | 140,473 | <p>The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:</p>
<pre><code>File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
</code></pre> |
30,355,650 | Define buildconfigfield for an specific flavor AND buildType | <p>I have 2 flavors, lets say Vanilla and Chocolate. I also have Debug and Release build types, and I need Vanilla Release to have a field true, while the other 3 combinations should be false.</p>
<pre><code>def BOOLEAN = "boolean"
def VARIABLE = "VARIABLE"
def TRUE = "true"
def FALSE = "false"
VANILLA {
debug {
buildConfigField BOOLEAN, VARIABLE, FALSE
}
release {
buildConfigField BOOLEAN, VARIABLE, TRUE
}
}
CHOCOLATE {
buildConfigField BOOLEAN, VARIABLE, FALSE
}
</code></pre>
<p>I'm having an error, so I guess the debug and release trick doesnt work. It is possible to do this?</p> | 30,486,355 | 8 | 3 | null | 2015-05-20 16:40:52.74 UTC | 11 | 2020-02-06 09:56:43.16 UTC | 2015-05-27 13:46:48.777 UTC | null | 1,398,731 | null | 1,398,731 | null | 1 | 62 | android|gradle|android-gradle-plugin|build-tools | 25,398 | <p>Loop the variants and check their names:</p>
<pre><code>productFlavors {
vanilla {}
chocolate {}
}
applicationVariants.all { variant ->
println("Iterating variant: " + variant.getName())
if (variant.getName() == "chocolateDebug") {
variant.buildConfigField "boolean", "VARIABLE", "true"
} else {
variant.buildConfigField "boolean", "VARIABLE", "false"
}
}
</code></pre> |
18,503,096 | Python Integer Partitioning with given k partitions | <p>I'm trying to find or develop Integer Partitioning code for Python.</p>
<p>FYI, Integer Partitioning is representing a given integer n as a sum of integers smaller than n. For example, an integer 5 can be expressed as <code>4 + 1 = 3 + 2 = 3 + 1 + 1 = 2 + 2 + 1 = 2 + 1 + 1 + 1 = 1 + 1 + 1 + 1 + 1</code></p>
<p>I've found a number of solutions for this. <a href="http://homepages.ed.ac.uk/jkellehe/partitions.php" rel="noreferrer">http://homepages.ed.ac.uk/jkellehe/partitions.php</a> and <a href="http://code.activestate.com/recipes/218332-generator-for-integer-partitions/" rel="noreferrer">http://code.activestate.com/recipes/218332-generator-for-integer-partitions/</a></p>
<p>However, what I really want is to restrict the number of partitions.</p>
<p>Say, # of partition <em>k</em> = 2, a program only need to show <code>5 = 4 + 1 = 3 + 2</code>,</p>
<p>if <em>k</em> = 3, <code>5 = 3 + 1 + 1 = 2 + 2 + 1</code></p> | 18,503,391 | 4 | 5 | null | 2013-08-29 05:41:26.843 UTC | 15 | 2022-01-10 20:10:27.937 UTC | 2015-05-18 05:43:07.76 UTC | null | 1,048,572 | user2211319 | null | null | 1 | 24 | python|algorithm|integer-partition | 13,384 | <p>I've written a generator solution</p>
<pre><code>def partitionfunc(n,k,l=1):
'''n is the integer to partition, k is the length of partitions, l is the min partition element size'''
if k < 1:
raise StopIteration
if k == 1:
if n >= l:
yield (n,)
raise StopIteration
for i in range(l,n+1):
for result in partitionfunc(n-i,k-1,i):
yield (i,)+result
</code></pre>
<p>This generates all the partitions of <code>n</code> with length <code>k</code> with each one being in order of least to greatest.</p>
<p>Just a quick note: Via <code>cProfile</code>, it appears that using the generator method is much faster than using falsetru's direct method, using the test function <code>lambda x,y: list(partitionfunc(x,y))</code>. On a test run of <code>n=50,k-5</code>, my code ran in .019 seconds vs the 2.612 seconds of the direct method.</p> |
26,347,394 | Node.js (with express & bodyParser): unable to obtain form-data from post request | <p>I can't seem to recover the form-data of a post request sent to my Node.js server. I've put below the server code and the post request (sent using postman in chrome):</p>
<p><strong>Post request</strong></p>
<pre><code>POST /api/login HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="userName"
jem
----WebKitFormBoundaryE19zNvXGzXaLvS5C
</code></pre>
<p><strong>NodeJS server code</strong></p>
<pre><code>var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser());
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,accept,access_token,X-Requested-With');
next();
});
var port = process.env.PORT || 8080; // set our port
var router = express.Router(); // get an instance of the express Router
router.get('/', function(req, res) {
res.json({ message: 'I am groot!' });
});
// Login
router.route('/login')
.post(function(req, res){
console.log('Auth request recieved');
// Get the user name
var user = req.body.userName;
var aToken = getToken(user);
res.json({
'token':'a_token'
});
});
app.use('/api', router);
app.listen(port);
</code></pre>
<p>The login method tries to obtain the <code>req.body.userName</code>, however, <code>req.body</code> is always empty.
I've seen other cases on SO describing such behavior but none of the related answers did apply here.</p>
<p>Thanks for helping out.</p> | 26,347,677 | 6 | 3 | null | 2014-10-13 19:23:39.533 UTC | 9 | 2021-12-01 04:36:46.177 UTC | 2018-04-01 18:28:56.84 UTC | null | 3,539,857 | null | 987,818 | null | 1 | 45 | node.js|express|post|multipartform-data|body-parser | 109,612 | <p>In general, an express app needs to specify the appropriate <a href="https://github.com/expressjs/body-parser">body-parser middleware</a> in order for <code>req.body</code> to contain the body.</p>
<p>[EDITED]</p>
<ol>
<li><p>If you required parsing of url-encoded (non-multipart) form data, as well as JSON, try adding:</p>
<pre><code>// Put this statement near the top of your module
var bodyParser = require('body-parser');
// Put these statements before you define any routes.
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
</code></pre>
<p>First, you'll need to add <a href="https://www.npmjs.org/package/body-parser">body-parser</a> to the <code>dependencies</code> property of your <code>package.json</code>, and then perform a <code>npm update</code>.</p></li>
<li><p>To handle multi-part form data, the <code>bodyParser.urlencoded()</code> body parser will not work. See the <a href="https://www.npmjs.org/package/body-parser#readme">suggested modules here</a> for parsing multipart bodies.</p></li>
</ol> |
10,035,030 | How can I make a LDAP query that returns only groups having OU=Groups from all levels? | <p>If I am looking for all <code>Groups</code>, I get too much garbage. </p>
<p>If I try to narrow down the base, I get too few.</p>
<p>Here is an example:</p>
<pre><code>CN=A Team,OU=Groups,OU=Americas,DC=example,DC=com
CN=B TEAM,OU=Groups,OU=EMEA,DC=example,DC=com
CN=C Team,OU=Legacy Groups,DC=example,DC=com
CN=D Team,OU=Groups,OU=Bangalore,OU=APAC,DC=example,DC=com
CN=E Team,OU=Common Groups,DC=example,DC=com
</code></pre>
<p>I am looking for a LDAP <code>filter</code> that returns A B D E (without C) - mainly the logic would be get me all groups that do have last <code>OU=Groups</code> or <code>OU=Common Groups</code></p>
<p>My current search is using:</p>
<pre><code> Search base: CN=Users,DC=citrite,DC=net
Filter: (objectCategory=Group)
</code></pre> | 10,041,875 | 1 | 2 | null | 2012-04-05 19:48:01.14 UTC | 4 | 2019-03-29 12:52:41.483 UTC | null | null | null | null | 99,834 | null | 1 | 2 | ldap|ldap-query | 42,187 | <p>First, on Microsoft Active Directory is impossible to do this in a single search, that's because AD is not fully LDAP compatible.</p>
<p>LDAP-compliant servers support an <code>extensible-match</code> filter which provides the necessary
filtering. From <a href="https://www.rfc-editor.org/rfc/rfc4511#section-4.5" rel="nofollow noreferrer">RFC4511</a>:</p>
<blockquote>
<p>If the dnAttributes field is set to TRUE, the match is additionally
applied against all the AttributeValueAssertions in an entry's
distinguished name, and it evaluates to TRUE if there is at least
one attribute or subtype in the distinguished name for which the
filter item evaluates to TRUE. The dnAttributes field is present
to alleviate the need for multiple versions of generic matching
rules (such as word matching), where one applies to entries and
another applies to entries and DN attributes as well.</p>
</blockquote>
<p>Note that the <em>extensible-match</em> filter technique only works with LDAP-compliant servers,
of which AD is not one.</p>
<p>For example, I added the following entries to a server:</p>
<pre><code>dn: ou=legacy groups,o=training
objectClass: top
objectClass: organizationalUnit
ou: legacy groups
dn: ou=common groups,o=training
objectClass: top
objectClass: organizationalUnit
ou: common groups
dn: ou=groups,o=training
objectClass: top
objectClass: organizationalUnit
ou: groups
dn: cn=a,ou=common groups,o=training
objectClass: top
objectClass: groupOfUniqueNames
uniqueMember: uid=user.0,ou=people,o=training
cn: a
dn: cn=b,ou=groups,o=training
objectClass: top
objectClass: groupOfUniqueNames
uniqueMember: uid=user.0,ou=people,o=training
cn: b
dn: cn=c,ou=legacy groups,o=training
objectClass: top
objectClass: groupOfUniqueNames
uniqueMember: uid=user.0,ou=people,o=training
cn: c
</code></pre>
<p>Examine the filter in the following search after the above entries were added:</p>
<pre><code>ldapsearch --propertiesFilePath ds-setup/11389/ldap-connection.properties \
--baseDN o=training \
--searchScope sub '(|(ou:dn:=groups)(ou:dn:=common groups))' 1.1
dn: ou=common groups,o=training
dn: cn=a,ou=common groups,o=training
dn: ou=groups,o=training
dn: cn=b,ou=groups,o=training
</code></pre>
<p>Note that <code>ou=common groups</code>, <code>ou=groups</code>, and their subordinates are returned, but not
<code>ou=legacy groups</code> and subordinates.</p>
<p><em>This example uses the modern syntax of the ldapsearch command line tool. If the user is
utilizing the legacy OpenLDAP version of ldapsearch, the parameters to the command line tool are
somewhat different, but that does not matter. What matters is the filter.</em></p> |
23,013,274 | shutting down computer (linux) using python | <p>I am trying to write a script that will shut down the computer if a few requirements are filled with the command</p>
<pre><code> os.system("poweroff")
</code></pre>
<p>also tried</p>
<pre><code> os.system("shutdown now -h")
</code></pre>
<p>and a few others. but nothing happens when I run it, the computer goes through the code without crashing or producing any error messages and terminates the script normally, without shutting down the computer.</p>
<p>How does one shutdown the computer in python?</p>
<p>edit:</p>
<p>Seems that the commands I have tried requires root access. Is there any way to shut down the machine from the script without elevated privileges?</p> | 23,013,969 | 10 | 6 | null | 2014-04-11 12:58:45.47 UTC | 5 | 2022-02-20 15:45:54.697 UTC | 2014-04-11 13:06:36.08 UTC | null | 3,522,859 | null | 3,522,859 | null | 1 | 18 | python|linux|python-2.7|system-shutdown | 47,542 | <p>Many of the linux distributions out there require super user privileges to execute <code>shutdown</code> or <code>halt</code>, but then, how come that if you're sitting on your computer you can power it off without being root? You open a menu, hit <em>Shutdown</em> and it shutdowns without you becoming <code>root</code>, right?</p>
<p>Well... the <em>rationale</em> behind this is that if you have physical access to the computer, you could pretty much pull the power cord and power it off anyways, so nowadays, many distributions allow power-off though access to the local System Bus accessible through <code>dbus</code>. Problem with <code>dbus</code> (or the services exposed through it, rather)? It's constantly changing. I'd recommend installing a dbus viewer tool such as <a href="https://wiki.gnome.org/action/show/Apps/DFeet?action=show&redirect=DFeet" rel="nofollow noreferrer">D-feet</a> (be advised: it's still pretty hard to visualize, but it may help)</p>
<p>Take a look to <a href="https://bbs.archlinux.org/viewtopic.php?id=127962" rel="nofollow noreferrer">these Dbus shutdown scripts</a>.</p>
<p>If you still have HAL in your distrubution (is on the way to being deprecated) try this:</p>
<pre><code>import dbus
sys_bus = dbus.SystemBus()
hal_srvc = sys_bus.get_object('org.freedesktop.Hal',
'/org/freedesktop/Hal/devices/computer')
pwr_mgmt = dbus.Interface(hal_srvc,
'org.freedesktop.Hal.Device.SystemPowerManagement')
shutdown_method = pwr_mgmt.get_dbus_method("Shutdown")
shutdown_method()
</code></pre>
<p>This works on a Ubuntu 12.04 (I just powered off my computer to make sure it worked). If you have something newer... well, it may not work. It's the downside of this method: it is very distribution specific.</p>
<p>You might have to install the <code>dbus-python</code> package for this to work (<a href="http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html" rel="nofollow noreferrer">http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html</a>)</p>
<p><strong>UPDATE 1:</strong></p>
<p>I've been doing a little bit of research and it looks like this is done in newer Ubuntu versions through <a href="http://www.freedesktop.org/software/ConsoleKit/doc/ConsoleKit.html" rel="nofollow noreferrer">ConsoleKit</a>. I've tested the code below in my Ubuntu 12.04 (which has the deprecated HAL and the newer ConsoleKit) and it did shut my computer off:</p>
<pre><code>>>> import dbus
>>> sys_bus = dbus.SystemBus()
>>> ck_srv = sys_bus.get_object('org.freedesktop.ConsoleKit',
'/org/freedesktop/ConsoleKit/Manager')
>>> ck_iface = dbus.Interface(ck_srv, 'org.freedesktop.ConsoleKit.Manager')
>>> stop_method = ck_iface.get_dbus_method("Stop")
>>> stop_method()
</code></pre>
<p><strong>UPDATE 2:</strong></p>
<p>Probably <em>why</em> can you do this without being <code>root</code> deserves a bit of a wider explanation. Let's focus on the newer <code>ConsoleKit</code> (<code>HAL</code> is way more complicated and messy, IMHO).</p>
<p>The <code>ConsoleKit</code> is a service running as <code>root</code> in your system:</p>
<pre><code>borrajax@borrajax:/tmp$ ps aux|grep console-kit
root 1590 0.0 0.0 1043056 3876 ? Sl Dec05 0:00 /usr/sbin/console-kit-daemon --no-daemon
</code></pre>
<p>Now, <code>d-bus</code> is just a message passing system. You have a service, such as <em>ConsoleKit</em> that exposes an interface to <code>d-bus</code>. One of the methods exposed is the <code>Stop</code> (shown above). <em>ConsoleKit</em>'s permissions are controlled with <em>PolKit</em>, which (despite on being based on regular Linux permissions) offers a bit of a finer grain of control for <em>"who can do what"</em>. For instance, <em>PolKit</em> can say things like <em>"If the user is logged into the computer, then allow him to do something. If it's remotely connected, then don't."</em>. If <em>PolKit</em> determines that your user is allowed to call <em>ConsoleKit</em>'s <code>Stop</code> method, that request will be passed by (or <em>through</em>) <code>d-bus</code> to <em>ConsoleKit</em> (which will subsequently shutdown your computer because it can... because it worth's it... because it's <code>root</code>)</p>
<p>Further reading:</p>
<ul>
<li><a href="https://unix.stackexchange.com/questions/5220/what-are-consolekit-and-policykit-how-do-they-work">What are ConsoleKit and PolicyKit? How do they work?</a></li>
<li><a href="https://wiki.archlinux.org/index.php/PolicyKit" rel="nofollow noreferrer">ArchWiki PolKit</a></li>
</ul>
<p>To summarize: You can't switch a computer off without being <code>root</code>. But you can tell a service that is running as <code>root</code> to shutdown the system for you.</p>
<p><strong>UPDATE 3:</strong></p>
<p>On December 2021, seven years after the original answer was written I had to do this again. This time, in a Ubuntu 18.04.</p>
<p>Unsurprisingly, things seem to have changed a bit:</p>
<ul>
<li>The PowerOff functionality seems to be handled via a new <a href="https://man.archlinux.org/man/core/systemd/org.freedesktop.login1.5.en" rel="nofollow noreferrer"><code>org.freedesktop.login1</code></a> service, which is part of the """new""" <sub>(cough! cough!)</sub> SystemD <em>machinery</em>.</li>
<li>The <code>dbus</code> Python package seems to have been <a href="https://wiki.python.org/moin/DbusExamples" rel="nofollow noreferrer">deprecated and/or considered "legacy"</a>. There is, however, a new <a href="https://pydbus.readthedocs.io/en/latest/legacydocs/tutorial.html" rel="nofollow noreferrer">PyDbus library</a> to be used instead.</li>
</ul>
<p>So we can still power off machines with an unprivileged script:</p>
<pre class="lang-py prettyprint-override"><code>#! /usr/bin/python3
from pydbus import SystemBus
bus = SystemBus()
proxy = bus.get('org.freedesktop.login1', '/org/freedesktop/login1')
if proxy.CanPowerOff() == 'yes':
proxy.PowerOff(False) # False for 'NOT interactive'
</code></pre>
<p>Update 3.1:</p>
<p>It looks like it's not <em>as new</em> as I thought <strong>X-D</strong></p>
<p>There's already <a href="https://stackoverflow.com/a/41644926/289011">an answer</a> by @Roeften in this very same thread.</p>
<p><strong>BONUS</strong>:</p>
<p>I read in one of your comments that you wanna switch the computer off after a time consuming task to prevent it from overheating... Did you know that you can <em>probably</em> power it on at a given time using RTC? (See <a href="http://www.mythtv.org/wiki/ACPI_Wakeup" rel="nofollow noreferrer">this</a> and <a href="https://www.maketecheasier.com/alarm-automatically-power-on-linux/" rel="nofollow noreferrer">this</a>) Pretty cool, uh? (I got so excited when I found out I could do this... ) <strong>:-D</strong></p> |
5,387,868 | Oracle Install for SSIS connectivity (and drivers 32 64 bit) | <p>I have an SSIS package (SQL 2008) that I need to connecto to an Oracle DB (11g) with. What do I need to install to connect to oracle? What's the terminology ? All searches I've done talk about Instant Client, but on downloading that I see no exe's? I know installing the server will give me that Oracle Net manager (UI to update TNSNames.ora) but I don't want to install the entire server. That to be is overkill. What's the smallest footprint so that I can create a connection to an oracle DB via my Connection Manager in SSIS?</p>
<p>Also what's the difference between <em>Instant Client</em> & <em>Oracle Client tools</em> etc? There's so much arcane (atleast to me) terminology that it's confusing.</p>
<p>P.s. - From reading <a href="http://www.oracle.com/technetwork/topics/dotnet/index-085163.html" rel="noreferrer">http://www.oracle.com/technetwork/topics/dotnet/index-085163.html</a> you would think this was what I wanted, but the download just has an install.bat that seems to do nothing! Typical of the "solutions" I've tried so far.</p> | 5,414,872 | 3 | 0 | null | 2011-03-22 07:06:30.01 UTC | 3 | 2013-09-05 21:59:03.82 UTC | 2011-03-24 06:13:25.28 UTC | null | 30,292 | null | 30,292 | null | 1 | 7 | oracle|ssis|driver | 48,155 | <p>Well, what I did was download <strong>Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)</strong> from <a href="http://www.oracle.com/technetwork/database/enterprise-edition/downloads/112010-win64soft-094461.html" rel="noreferrer">http://www.oracle.com/technetwork/database/enterprise-edition/downloads/112010-win64soft-094461.html</a>. It had 4 options for installing One of them being Instant Client(which did not help me). The one that works is <strong>Runtime client</strong> or something named like that. It installs Net Manager which is what I want.</p>
<p>PS-Adding on (as I traverse the Oracle 64 bit journey), I find that I cannot use SSIS with 64 bit oracle DB providers. I get the exceptions (on adding a connection in SSIS):</p>
<blockquote>
<p>Test connection failed because of an
error in initializing provider.
Attempt to load Oracle client
libraries threw
BadImageFormatException. This problem
will occur when running in 64 bit mode
with the 32 bit Oracle client
components installed.</p>
</blockquote>
<p>I'm guessing this is because SSIS process is a 32 bit one and cannot use 64 bit oracle drivers (my host machine is Win 7 64 bit). </p>
<p>After testing, I found that this is indeed the case. <strong>We need the 32 bit drivers only for the SSIS IDE</strong> but can use 64 bit when running the DTSX package using the 64 bit dtexec.exe (C:\Program Files\Microsoft SQL Server\100\DTS\Binn)</p>
<p>So in DEVELOPMENT (on a 64 bit machine) install both the 32 and 64 bit clients:
32 bit: for development in Visual Studio IDE
64 bit: To run the DTSX package using the 64 bit version of dtexec.exe on the command line (as would be the case when we run this in a production environment)</p>
<p>A similar thread <a href="https://stackoverflow.com/questions/1067727/connecting-to-oracle-from-ssis-on-vista-64-bit">here</a>.</p> |
5,127,616 | Does ESPN Cricinfo have an API? | <p>Has <a href="http://espncricinfo.com" rel="noreferrer">espncricinfo.com</a> exposed an API? I'm interested in live scores, news, and maybe photos. </p>
<p>Up until now I have only known of the rss feed..</p> | 5,127,713 | 3 | 0 | null | 2011-02-26 15:00:12.183 UTC | 21 | 2015-04-01 18:49:20.173 UTC | 2013-05-03 15:26:45.793 UTC | null | 535,822 | null | 587,532 | null | 1 | 44 | web-services|api|espn | 52,751 | <p>I do not believe an API exists - unfortunately.</p>
<p>What a number of users have done - and what is suggested by cricinfo themselves - is use Yahoo Pipes to merge a number of different feeds. You can then get the resultant pipe in JSON and other formats.</p>
<p>It's probably best demonstrated by example by looking at a 'Latest cricket scores' pipe here: <a href="http://pipes.yahoo.com/pipes/pipe.info?_id=tMcVGcqn3BGvsT__2R2EvQ" rel="noreferrer">http://pipes.yahoo.com/pipes/pipe.info?_id=tMcVGcqn3BGvsT__2R2EvQ</a></p>
<p>Of course, it would be nice to be able to search the statistics and a REST service which returns the bare data for a <a href="http://stats.espncricinfo.com/ci/engine/current/stats/index.html" rel="noreferrer">statsguru</a> search, but the only suggestion I have at present is to build statsguru queries manually with <code>wrappertype=print</code> appended and then use xpath to filter out the data you require. </p>
<p>An example statsguru query:</p>
<p><a href="http://stats.espncricinfo.com/ci/engine/player/13418.html?class=1;template=results;type=allround;wrappertype=print" rel="noreferrer">http://stats.espncricinfo.com/ci/engine/player/13418.html?class=1;template=results;type=allround;wrappertype=print</a></p> |
9,443,004 | What does the `#` operator mean in Scala? | <p>I see this code in this blog: <a href="http://apocalisp.wordpress.com/2010/06/08/type-level-programming-in-scala/" rel="noreferrer">Type-Level Programming in Scala</a>:</p>
<pre><code>// define the abstract types and bounds
trait Recurse {
type Next <: Recurse
// this is the recursive function definition
type X[R <: Recurse] <: Int
}
// implementation
trait RecurseA extends Recurse {
type Next = RecurseA
// this is the implementation
type X[R <: Recurse] = R#X[R#Next]
}
object Recurse {
// infinite loop
type C = RecurseA#X[RecurseA]
}
</code></pre>
<p>There is an operator <code>#</code> in the code <code>R#X[R#Next]</code> which I've never seen. Since it's difficult to search it(ignored by search engines), who can tell me what does it mean?</p> | 9,444,487 | 4 | 3 | null | 2012-02-25 09:57:16.07 UTC | 59 | 2018-03-26 18:22:33.543 UTC | null | null | null | null | 342,235 | null | 1 | 146 | scala|type-systems | 16,514 | <p>To explain it, we first have to explain nested classes in Scala. Consider this simple example:</p>
<pre><code>class A {
class B
def f(b: B) = println("Got my B!")
}
</code></pre>
<p>Now let's try something with it:</p>
<pre><code>scala> val a1 = new A
a1: A = A@2fa8ecf4
scala> val a2 = new A
a2: A = A@4bed4c8
scala> a2.f(new a1.B)
<console>:11: error: type mismatch;
found : a1.B
required: a2.B
a2.f(new a1.B)
^
</code></pre>
<p>When you declare a class inside another class in Scala, you are saying that <em>each instance</em> of that class has such a subclass. In other words, there's no <code>A.B</code> class, but there are <code>a1.B</code> and <code>a2.B</code> classes, and they are <em>different</em> classes, as the error message is telling us above.</p>
<p>If you did not understand that, look up path dependent types.</p>
<p>Now, <code>#</code> makes it possible for you to refer to such nested classes without restricting it to a particular instance. In other words, there's no <code>A.B</code>, but there's <code>A#B</code>, which means a <code>B</code> nested class of <em>any</em> instance of <code>A</code>.</p>
<p>We can see this in work by changing the code above:</p>
<pre><code>class A {
class B
def f(b: B) = println("Got my B!")
def g(b: A#B) = println("Got a B.")
}
</code></pre>
<p>And trying it out:</p>
<pre><code>scala> val a1 = new A
a1: A = A@1497b7b1
scala> val a2 = new A
a2: A = A@2607c28c
scala> a2.f(new a1.B)
<console>:11: error: type mismatch;
found : a1.B
required: a2.B
a2.f(new a1.B)
^
scala> a2.g(new a1.B)
Got a B.
</code></pre> |
19,992,984 | Verbs that act after backtracking and failure | <p>I was recently reading along in the <a href="http://www.pcre.org/pcre.txt" rel="noreferrer"><code>PCRE</code></a> - (Perl-compatible regular expressions) documentation and came across some interesting tricks with regular expression. As I continued to read and exhaust myself, I stopped because of some confusion in relation with using a few of the <code>(*...)</code> patterns.</p>
<p>My question and confusion relates to <code>(*PRUNE)</code> and <code>(*FAIL)</code></p>
<p>Now for reference <code>(*SKIP)</code> acts like <code>(*PRUNE)</code>, except that if the pattern is unanchored, the bumpalong advance is not to the next character, but to the <strong>position</strong> in the subject where <code>(*SKIP)</code> was encountered.</p>
<p>The documentation states that <code>(*PRUNE)</code> causes the match to fail at the current <strong>starting position</strong> in the subject if the rest of the pattern does not match. And it states <code>(*FAIL)</code> synonymous with <code>(?!)</code> negative assertion. Forces a matching failure at the <strong>given position</strong> in the pattern.</p>
<p>So basically <code>(*FAIL)</code> behaves like a failing negative assertion and is a synonym for <code>(?!)</code></p>
<p>And <code>(*PRUNE)</code> causes the match to fail at the current <strong>starting position</strong> in the subject if there is a later matching failure that causes backtracking to reach it.</p>
<blockquote>
<p>How are these different when it comes to a point of failing?</p>
<p>Can anyone provide examples of how these are implemented and used correctly?</p>
</blockquote> | 20,008,790 | 1 | 2 | null | 2013-11-15 03:29:21.933 UTC | 17 | 2021-08-26 09:26:00.52 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,206,004 | null | 1 | 26 | regex|perl|pcre | 1,619 | <p>Before reading this answer, you should be familiar with the mechanism of backtracking, atomic groups, and possessive quantifiers. You can find information about these notions and features in the Friedl book and following these links: <a href="http://www.regular-expressions.info" rel="nofollow noreferrer">www.regular-expressions.info</a>, <a href="http://www.rexegg.com" rel="nofollow noreferrer">www.rexegg.com</a></p>
<p>All the test has been made with a global search (with the <code>preg_match_all()</code> function).</p>
<h3><code>(*FAIL)</code> <sup>(or the shorthand <code>(*F)</code>)</sup></h3>
<pre><code>baabo caaco daado
caac(*FAIL)|aa.|caaco|co
[0] => aab
[1] => caaco
[2] => aad
</code></pre>
<p><code>(*FAIL)</code> causes exactly the same behavior as a "bad character" in a pattern. If you replace it with an "R", for example, you obtain exactly the same result: <code>caacR|aa.|caaco|co</code>. To be more general, you can indeed replace <code>(*FAIL)</code> with an "always failing subpattern" like: <code>(?!)</code>, <code>(?=a(?<!a))</code>,...</p>
<p><code>a (first from "baabo")</code> : Without surprise, the first result is found by the second alternative. (<code>aab</code>)</p>
<p><code>c (first)</code> : The regex engine encounters the first "c" and tries the first alternative and finds: <code>caac</code>, but the subpattern is forced to fail. Then the regex engine (always from the first "c") tries the second alternative that fails, the third alternative succeeds. (<code>caaco</code>)</p>
<p><code>a (first from "daado")</code> : the third result is found by the second alternative. (<code>aad</code>)<br><br></p>
<h3><code>(*SKIP)</code></h3>
<pre><code>baabo caaco daado
caa(*SKIP)c(*FAIL)|aa.|caaco|co
[0] => aab
[1] => co
[2] => aad
</code></pre>
<p>This verb defines a point beyond which the regex engine is not allowed to backtrack when the subpattern fails later. Consequently, <strong>all the characters found before with the subpattern are consumed, once and for all</strong>, and can not be used for another part of the pattern (alternative).</p>
<p><code>a (first from "baabo")</code> : the first result is found by the second alternative. (<code>aab</code>)</p>
<p><code>c (first)</code> : the regex engine finds <code>caac</code> as in the first case, then fails (cause of the <code>(*FAIL)</code> verb), backtracks to the second "c" but is not allowed to backtrack to characters that are previously matched ("caa") before the <code>(*SKIP)</code> verb.<br>
<code>c (second)</code> : Now, the regex engine tries always the first alternative but in this new position and fails since there is an "o" and not an "a" after, then it backtracks to this second "c". Note that in this case, these characters are not consumed as previously because the subpattern has failed before to have reached the <code>(*SKIP)</code> verb.
The second alternative is tested and fails (doesn't begin with a "c"). The third alternative fails too because the next character is an "o" and not an "a".
The fourth alternative succeeds and gives the second result. (<code>co</code>)</p>
<p><code>a (first from "daado")</code> : the third result is found by the second alternative. (<code>aad</code>)
<br><br></p>
<h3><code>(*PRUNE)</code></h3>
<pre><code>baabo caaco daado
caa(*PRUNE)c(*FAIL)|aa.|caaco|co
[0] => aab
[1] => aac
[2] => aad
</code></pre>
<p>This verb is different from <code>(*SKIP)</code> because it doesn't forbid using all the previous matched characters, but skips the first matched character by the subpattern (or forbids a subpattern to start with) if the subpattern will fail later.</p>
<p><code>a (first from "baabo")</code> : the first result is found by the second alternative. (<code>aab</code>)</p>
<p><code>c (first)</code> : the regex engine finds <code>caac</code> as in the first case, then fails, but now backtracks to the first "a" from "caaco" since the first "c" is skipped.<br>
<code>a (first from "caaco")</code> : the first alternative is tried and fails, the second succeeds and gives the second result. (<code>aac</code>)</p>
<p><code>a (first from "daado")</code> : the third result is found by the second alternative. (<code>aad</code>)</p> |
15,051,128 | Prevent form from submitting via event.preventDefault(); not working | <p>I'm using jQuery to submit my form variables, and im trying to prevent the form from submitting via the usual ways (click submit button or press enter on one of the fields)</p>
<p>i have this:</p>
<pre><code>$('#form').submit(function(){
event.preventDefault();
});
</code></pre>
<p>but it doesn't seem to work my form is still submitting, going to the process.php page.. </p> | 15,051,168 | 7 | 3 | null | 2013-02-24 11:06:03.617 UTC | 1 | 2022-05-18 13:49:35.657 UTC | 2013-10-29 14:21:42.563 UTC | null | 1,185,053 | null | 1,797,947 | null | 1 | 17 | jquery|forms|submit | 58,601 | <p>If the only thing you need to do is to prevent the default action, you can supply <code>false</code> instead of a function:</p>
<pre><code>$('#form').submit(false);
</code></pre> |
15,466,298 | Simple caret (^) at end of Windows batch file consumes all memory | <p>This simple batch file in relatively short order consumes all available memory on Windows 7 (x64). What's going on? and what precautions can be taken to ward against it?</p>
<pre><code>any-invalid-command-you-like-here ^
</code></pre>
<p>Apparently necessary preconditions to exhibit the effect: </p>
<ul>
<li>the caret <code>^</code> is the very last thing in the file, and the script is not terminated with a newline</li>
<li>the caret is preceded by at least 2 spaces or characters, e.g. if the dots in the following represent spaces the memory leak will not be triggered <code>.^</code>, while this one will <code>..^</code> (just slowly)</li>
</ul>
<p>In this <em>Process Explorer</em> screen shot, the script had been running about 30 seconds, consumed 2.9GB, and was still climbing at a steady rate:</p>
<p><a href="https://i.stack.imgur.com/lKVfN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AJwB4.png" alt="2.9GB memory consumed and still climbing"></a></p>
<p>If you're going to experiment with this, make sure you can get at the Close Window [X] control or have a Task Manager or Process Explorer fired up and ready as <kbd>Ctrl-C</kbd>, <kbd>Ctrl-Break</kbd>, <kbd>Alt-F4</kbd> <strong>have no effect</strong>.</p>
<p>It appears multiple carets will cause the memory usage to ramp up much more quickly. The first time I encountered this there wasn't enough memory available in 1 or 2 minutes to do simple things like <kbd>Alt-Tab</kbd> and even the 3 finger salute <kbd>Ctrl-Alt-Del</kbd> was ineffective. I had to hard power off the machine.</p> | 15,469,225 | 1 | 4 | null | 2013-03-17 21:12:37.557 UTC | 24 | 2019-11-18 16:30:45.71 UTC | 2015-07-17 00:40:12.803 UTC | null | 202,229 | null | 14,420 | null | 1 | 56 | windows|security|batch-file|cmd | 13,213 | <h3>Thoughts</h3>
<p>The cause of this (from my understanding) is due to the cmd interpreter looking for a character to escape since the <code>^</code> is the batch escape character. Instead of properly identifying the end of file <code>eof</code> in this scenario, cmd just keeps looping and initializing something while looking for the character to escape.</p>
<p>Reproduced on Windows 8 Pro (64) with <code>cc^^^</code> (Multiple carets used to speed up the leak).</p>
<h3>Trials</h3>
<p><code>cc^</code> infinite loop and leaks very slowly.</p>
<p><code>cc^^</code> crashes with normal invalid command error.</p>
<p><code>cc^^^</code> infinite loop and leaks faster.</p>
<p><code>cc ^</code> infinite loop and leaks very slowly.</p>
<p><code>cc ^^</code> crashes with normal invalid command error.</p>
<p><code>cc ^^^</code> infinite loop and leaks faster.</p>
<p><code>cc"^</code> crashes with normal invalid command error.</p>
<p><code>cc"^^</code> crashes with normal invalid command error.</p>
<p><code>cc"^^^</code> crashes with normal invalid command error.</p>
<h3>Notes</h3>
<ul>
<li>Only infinite loop and leaks when carets <code>^</code> are used literally (outside of quotations). When quotation added the script crashes with standard invalid command error.</li>
<li>Only infinite loop and leaks when batch file is encoded as <strong>UTF-8</strong> or <strong>ASCII</strong>. When <strong>UTF-16</strong>, the script crashes with standard invalid command error.</li>
<li>Must be an odd number of carets as to not escape the last caret.</li>
</ul>
<h3>Precautions</h3>
<ul>
<li>Make sure no batch scripts end with a caret <code>^</code> (0x5E) or at least an odd number of carets.</li>
<li>Or encode them in UTF-16.</li>
</ul> |
15,077,466 | What is a converting constructor in C++ ? What is it for? | <p>I have heard that C++ has something called "conversion constructors" or "converting constructors". What are these, and what are they for? I saw it mentioned with regards to this code:</p>
<pre><code>class MyClass
{
public:
int a, b;
MyClass( int i ) {}
}
int main()
{
MyClass M = 1 ;
}
</code></pre> | 15,077,788 | 3 | 1 | null | 2013-02-25 22:09:36.25 UTC | 33 | 2019-01-12 07:23:35.17 UTC | 2013-02-25 22:36:21.39 UTC | null | 845,092 | null | 1,141,493 | null | 1 | 59 | c++|constructor|copy-constructor | 48,507 | <p>The definition for a <em>converting constructor</em> is different between C++03 and C++11. In both cases it must be a non-<code>explicit</code> constructor (otherwise it wouldn't be involved in implicit conversions), but for C++03 it must also be callable with a single argument. That is:</p>
<pre><code>struct foo
{
foo(int x); // 1
foo(char* s, int x = 0); // 2
foo(float f, int x); // 3
explicit foo(char x); // 4
};
</code></pre>
<p>Constructors 1 and 2 are both converting constructors in C++03 and C++11. Constructor 3, which must take two arguments, is only a converting constructor in C++11. The last, constructor 4, is not a converting constructor because it is <code>explicit</code>.</p>
<ul>
<li><p><strong>C++03</strong>: §12.3.1</p>
<blockquote>
<p>A constructor declared without the <em>function-specifier</em> <code>explicit</code> that can be called with a single parameter specifies a conversion from the type of its first parameter to the type of its class. Such a constructor is called a converting constructor.</p>
</blockquote></li>
<li><p><strong>C++11</strong>: §12.3.1</p>
<blockquote>
<p>A constructor declared without the <em>function-specifier</em> <code>explicit</code> specifies a conversion from the types of its parameters to the type of its class. Such a constructor is called a converting constructor.</p>
</blockquote></li>
</ul>
<p>Why are constructors with more than a single parameter considered to be converting constructors in C++11? That is because the new standard provides us with some handy syntax for passing arguments and returning values using <em>braced-init-lists</em>. Consider the following example:</p>
<pre><code>foo bar(foo f)
{
return {1.0f, 5};
}
</code></pre>
<p>The ability to specify the return value as a <em>braced-init-list</em> is considered to be a conversion. This uses the converting constructor for <code>foo</code> that takes a <code>float</code> and an <code>int</code>. In addition, we can call this function by doing <code>bar({2.5f, 10})</code>. This is also a conversion. Since they are conversions, it makes sense for the constructors they use to be <em>converting constructors</em>.</p>
<p>It is important to note, therefore, that making the constructor of <code>foo</code> which takes a <code>float</code> and an <code>int</code> have the <code>explicit</code> function specifier would stop the above code from compiling. The above new syntax can only be used if there is a converting constructor available to do the job.</p>
<ul>
<li><p><strong>C++11</strong>: §6.6.3:</p>
<blockquote>
<p>A <code>return</code> statement with a <em>braced-init-list</em> initializes the object or reference to be returned from the function by copy-list-initialization (8.5.4) from the specified initializer list.</p>
</blockquote>
<p>§8.5:</p>
<blockquote>
<p>The initialization that occurs [...] in argument passing [...] is called copy-initialization.</p>
</blockquote>
<p>§12.3.1:</p>
<blockquote>
<p>An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used.</p>
</blockquote></li>
</ul> |
15,009,194 | Assign only if condition is true in ternary operator in JavaScript | <p>Is it possible to do something like this in JavaScript?</p>
<pre><code>max = (max < b) ? b;
</code></pre>
<p>In other words, assign value only if the condition is true. If the condition is false, do nothing (no assignment). Is this possible?</p> | 15,009,278 | 11 | 3 | null | 2013-02-21 18:02:03.507 UTC | 10 | 2022-01-12 05:39:57.58 UTC | null | null | null | null | 1,958,032 | null | 1 | 67 | javascript|ternary-operator | 109,614 | <p>Don't use the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator" rel="noreferrer">ternary operator</a> then, it requires a third argument. You would need to reassign <code>max</code> to <code>max</code> if you don't want it to change (<code>max = (max < b) ? b : max</code>).</p>
<p>An <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/if...else" rel="noreferrer">if-statement</a> is much more clear:</p>
<pre><code>if (max < b) max = b;
</code></pre>
<p>And if you need it to be an expression, you can (ab)use the short-circuit-evaluation of <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators" rel="noreferrer">AND</a>:</p>
<pre><code>(max < b) && (max = b)
</code></pre>
<p>Btw, if you want to avoid repeating variable names (or expressions?), you could use the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/max" rel="noreferrer">maximum function</a>:</p>
<pre><code>max = Math.max(max, b);
</code></pre> |
15,458,650 | Make an image responsive - the simplest way | <p>I notice that my code is responsive, in the fact that if I scale it down to the size of a phone or tablet - all of the text, links, and social icons scale accordingly.</p>
<p>However, the ONLY thing that doesn't is my image in the body; which is wrapped in paragraph tags... with that being said, is there a simple way to make the image responsive as well?</p>
<p>Here's the code that I used to have my image show in the body:</p>
<pre><code><body>
<center>
<p><a href="MY WEBSITE LINK" target="_blank"><img src="IMAGE LINK" border="0" alt="Null"></a></p>
</center>
</body>
</code></pre> | 15,458,733 | 12 | 5 | null | 2013-03-17 07:51:25.923 UTC | 37 | 2021-06-05 11:50:30.993 UTC | 2021-06-05 11:50:30.993 UTC | null | 4,356,300 | null | 2,176,358 | null | 1 | 89 | html|css|image|mobile | 510,031 | <p>You can try doing</p>
<pre><code><p>
<a href="MY WEBSITE LINK" target="_blank">
<img src="IMAGE LINK" style='width:100%;' border="0" alt="Null">
</a>
</p>
</code></pre>
<p>This should scale your image if in a fluid layout.</p>
<p>For responsive (meaning your layout reacts to the size of the window) you can add a class to the image and use <code>@media</code> queries in CSS to change the width of the image.</p>
<p>Note that changing the height of the image will mess with the ratio.</p> |
28,360,978 | CSS: How to get browser scrollbar width? (for :hover {overflow: auto} nice margins) | <p>I'm not sure if title is clear, so few words of explanation. I've got few little elements, let say <code>div</code>'s (<code>200px</code> x <code>400px</code> CONSTANT). Inside each of them, there is a paragraph with about 20 lines of text. <strong>Of course, this it to much for a poor little div</strong>. What I want to do is: </p>
<ol>
<li>Normally <code>div</code> has <code>overflow: hidden</code> property.</li>
<li>On mouse over (<code>:hover</code>) this property is changed to <code>overflow: auto;</code>, and the scrollbar appears.</li>
</ol>
<p>What is the problem? I want a little space (padding or margin) between the paragraph text and the scrollbar. Let's say that paragraph has a symetrical <code>margin: 20px;</code>. But after <code>:hover</code> triggers on, the scrollbar appears, and the whole right side of the paragraph is moved <code>"scrollbar-width" px</code> to the left. Sentences are broken in other lines, and the whole paragraph look different, which is quite annoying and not user friendly. How can I set my CSS, so the only change after hover will be the appearance of scroolbar?</p>
<p>In other words:</p>
<pre><code>/* Normally no scrollbar */
div {display: block; width: 400px; height: 200px; overflow: hidden;}
/* On hover scrollbar appears */
div:hover {overflow: auto;}
/* Paragraph margin predicted for future scrollbar on div */
div p {margin: 20px (20px + scrollbarwidth px) 20px 50px;}
/* With scrollbar margin is symmetrical */
div:hover p {margin: 20px;} /* With scrollbar */
</code></pre>
<p><strong>I have done a little snippet for it, with exaplanation of my problem in <code>strong</code>. I hope everything is clear :).</strong> I'm searching for a solution for almost two hours now, so I think my question is quite unique and interesting.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.demo1 {
width: 400px;
height: 200px;
overflow: hidden;
background: #ddd;
}
div.demo1:hover {
overflow: auto;
}
div.demo1 p {
background: #eee;
margin: 20px;
}
div.demo2 {
width: 400px;
height: 200px;
overflow: hidden;
background: #ddd;
}
div.demo2:hover {
overflow: auto;
}
div.demo2 p {
background: #eee;
margin: 20px 40px 20px 20px;
}
div.demo2:hover p {
margin: 20px 20px 20px 20px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="demo1">
<p>
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
</p>
</div>
<br>
<br>
<strong>As you can see, on hover right side of the paragraph "moves" left. But I want something like:</strong>
<br>
<br>
<div class="demo2">
<p>
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.
</p>
</div>
<strong>But with a "perfect" scrollbar width (in this example I used 20px)</strong></code></pre>
</div>
</div>
</p> | 28,361,560 | 11 | 2 | null | 2015-02-06 07:52:30.257 UTC | 7 | 2022-08-04 14:15:39.34 UTC | null | null | null | null | 1,125,465 | null | 1 | 29 | html|css|width|scrollbar | 58,280 | <p>Scrollbar widths can vary between browsers and operating systems, and unfortunately CSS does not provide a way to detect those widths: we need to use JavaScript.</p>
<p>Other people have solved this problem by measuring the width of the scrollbar on an element:</p>
<ul>
<li><a href="http://davidwalsh.name/detect-scrollbar-width" rel="nofollow noreferrer">http://davidwalsh.name/detect-scrollbar-width</a> (original post)</li>
<li><a href="http://jsfiddle.net/a1m6an3u/" rel="nofollow noreferrer">http://jsfiddle.net/a1m6an3u/</a> (live example)</li>
</ul>
<p>We create a div <code>.scrollbar-measure</code>, add a scrollbar, and return its size.</p>
<pre class="lang-js prettyprint-override"><code>// Create the div
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);
// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.warn(scrollbarWidth);
// Delete the div
document.body.removeChild(scrollDiv);
</code></pre>
<p>This is fairly straightforward, but it is (obviously) not pure CSS.</p> |
28,100,809 | NoSuchBeanDefinitionException expected at least 1 bean which qualifies as autowire candidate for this dependency | <p>I know this question has been asked so many times but I'm really having trouble to get over it. I have tried so many combinations by seeing those question but no one seems to fit my case.</p>
<p>The full log error is the following:</p>
<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'professorController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.personal.online.dao.ProfessorDao com.personal.online.controller.ProfessorController.professorDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.personal.online.dao.ProfessorDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:643)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:606)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:657)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:525)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:466)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:865)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.personal.online.dao.ProfessorDao com.personal.online.controller.ProfessorController.professorDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.personal.online.dao.ProfessorDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 34 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.personal.online.dao.ProfessorDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 36 more
jan 22, 2015 9:51:21 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Allocate exception for servlet appServlet
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.personal.online.dao.ProfessorDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:643)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:606)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:657)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:525)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:466)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:865)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p>Here's my current implementation:</p>
<p>Controller:</p>
<pre><code>package com.personal.online.controller;
// imports
@Transactional
@Controller
public class ProfessorController {
@Autowired
private ProfessorDao professorDao;
@RequestMapping("cadastrarProfessor")
public String cadastrar() {
professorDao.persist(new Professor("some name"));
return "professor/formulario";
}
}
</code></pre>
<p>Interface:</p>
<pre><code>package com.personal.online.dao;
public interface ProfessorDao {
void persist(Professor professor);
}
</code></pre>
<p>Repository:</p>
<pre><code>package com.personal.online.dao;
@Repository
public class JpaProfessorDao implements ProfessorDao {
@PersistenceContext
EntityManager em;
@Transactional
public void persist(Professor professor) {
em.persist(professor);
}
}
</code></pre>
<p>Model:</p>
<pre><code>package com.personal.online.model;
@Entity
@Table(name = "Professor")
public class Professor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
private String nome;
public Professor() {
}
public Professor(String nome) {
this.nome = nome;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
</code></pre>
<p>Spring configuration:</p>
<pre><code><annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter" />
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
<beans:bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/PersonalOnline" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<beans:bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="mysqlDataSource" />
<beans:property name="jpaVendorAdapter">
<beans:bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</beans:property>
</beans:bean>
<beans:bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="entityManagerFactory" />
</beans:bean>
<tx:annotation-driven />
<context:component-scan base-package="com.personal.online.controller" />
</code></pre>
<p>persistence.xml:</p>
<p></p>
<pre><code> <provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.personal.online.model.Professor</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/personal_online" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</code></pre> | 28,100,948 | 5 | 3 | null | 2015-01-22 23:54:19.563 UTC | 0 | 2018-09-17 13:39:34.807 UTC | 2015-01-26 10:00:32.96 UTC | null | 115,835 | null | 2,026,010 | null | 1 | 9 | java|hibernate|spring-mvc|jpa | 59,038 | <p>Add the package of <code>JpaProfessorDao</code> to the list of packages to be scanned</p>
<pre><code><context:component-scan base-package="com.personal.online.controller, com.personal.online.dao" />
</code></pre> |
7,705,929 | how to select the most frequently appearing values? | <p>I've seen examples where the query orders by count and takes the top row, but in this case there can be multiple "most frequent" values, so I might want to return more than just a single result.</p>
<p>In this case I want to find the most frequently appearing last names in a users table, here's what I have so far:</p>
<pre><code>select last_name from users group by last_name having max(count(*));
</code></pre>
<p>Unfortunately with this query I get an error that my max function is nested too deeply.</p> | 7,705,993 | 2 | 0 | null | 2011-10-09 19:20:44.443 UTC | 8 | 2017-01-25 20:04:29.087 UTC | null | null | null | null | 964,195 | null | 1 | 11 | sql|oracle | 42,293 | <pre><code>select
x.last_name,
x.name_count
from
(select
u.last_name,
count(*) as name_count,
rank() over (order by count(*) desc) as rank
from
users u
group by
u.last_name) x
where
x.rank = 1
</code></pre>
<p>Use the analytical function <code>rank</code>. It will assign a numbering based on the order of <code>count(*) desc</code>. If two names got the same count, they get the same rank, and the next number is skipped (so you might get rows having ranks 1, 1 and 3). <code>dense_rank</code> is an alternative which doesn't skip the next number if two rows got the same rank, (so you'd get 1, 1, 2), but if you want only the rows with rank 1, there is not much of a difference. </p>
<p>If you want only one row, you'd want each row to have a different number. In that case, use <code>row_number</code>. Apart from this small-but-important difference, these functions are similar and can be used in the same way.</p> |
8,828,451 | How to right align this submit button? | <p>I have a large number for forms with submit buttons and I need to right align the buttons. The problem is that when I use <code>float: right</code>, the submit element is taken out of the normal document flow. This means the form's height is reduced and it's bottom border then interferes with the button.</p>
<p>Here's the code:</p>
<pre><code><html>
<head>
<style type="text/css">
#left-col {
width: 290px;
}
#loginForm {
border: 1px solid black;
}
#submit {
/* float: right; */
}
</style>
</head>
<body>
<div id="left-col">
<div id="loginForm">
<form id="user-login-form" enctype="application/x-www-form-urlencoded" method="post" action="">
<label for="email" class="required">Email</label>
<input type="text" name="email" id="email" value="">
<label for="password" class="required">Password</label>
<input type="password" name="password" id="password" value="">
<input type="submit" name="submit" id="submit" value="Login" class="submit">
</form>
</div>
</div>
</body>
</html>
</code></pre>
<p>The forms are generated programatically (using Zend_Form) so I am hoping to avoid hacks that require additional elements (such as paragraphs with clear: both).</p>
<p>Hopefully this will be a simple question for a CSS guru!</p>
<p>Thanks...</p> | 8,828,484 | 5 | 5 | null | 2012-01-11 23:56:52.907 UTC | 0 | 2015-04-23 12:58:09.803 UTC | null | null | null | null | 356,282 | null | 1 | 3 | css | 48,171 | <p>You can use the CSS <code>:after</code> pseudoelement to clear the container, without adding any extra HTML markup.</p>
<p>You would add something like this to your CSS:</p>
<pre><code>#loginForm:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
</code></pre>
<p>Or to the <code>form</code> element, whichever you deem more appropriate.</p> |
5,315,659 | jQuery change hash (fragment identifier) while scrolling down page | <p>I'm building a one pager website. Eg. every page (5 in total) is on one big page with the main menu fixed at the top. When you click on a menu link it slides you down to that pages anchor tag and the clicked menu item get a "active" CSS class. </p>
<p>What I'd like to do now is allow the user to scroll themself but still have the menu "active" item and URL hash change as they do.</p>
<p>So my question basically is how do I know when the user has scrolled down to a different page so I can update the menu and URL hash (fragment identifier).</p>
<p>Thanks</p> | 5,315,993 | 4 | 1 | null | 2011-03-15 17:33:58.62 UTC | 10 | 2016-05-24 08:24:32.837 UTC | 2016-05-24 08:24:32.837 UTC | null | 1,010,918 | null | 498,187 | null | 1 | 13 | javascript|jquery|url | 19,756 | <p>its possible but there are a requirement to your page (for my solution to work): </p>
<p>your page have to be separated in divs(or sections whatever) with unique ids (i hope you dont use anchor <code><a></code>'s)</p>
<p>than you can use code like this:</p>
<pre><code>$(document).bind('scroll',function(e){
$('section').each(function(){
if (
$(this).offset().top < window.pageYOffset + 10
//begins before top
&& $(this).offset().top + $(this).height() > window.pageYOffset + 10
//but ends in visible area
//+ 10 allows you to change hash before it hits the top border
) {
window.location.hash = $(this).attr('id');
}
});
});
</code></pre>
<p>with html like this</p>
<pre><code><section id="home">
Home
</section>
<section id="works">
Works
</section>
<section id="about">
About
</section>
</code></pre> |
5,083,954 | Send Message in C# | <p>I'm creating an application that uses a main project that is connected to several different DLLs. From one DLL window I need to be able to open a window in another but the DLL's can't reference each other. </p>
<p>It was suggested to me to use the sendmessage function in the first DLL and have a listener in the main program that directs that message to the appropriate DLL to open it's window. </p>
<p>However I'm not familiar at all with the sendmessage function and am having a lot of diffculty piecing things together from information I'm finding online. </p>
<p>If someone could please show me the correct way (if there is any) to use the sendmessage function and maybe how a listener captures that message that would be amazing. Here is some of the code I've got so far I'm not sure if I'm heading in the right direction.</p>
<pre><code> [DllImport("user32.dll")]
public static extern int FindWindow(string lpClassName, String lpWindowName);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
public void button1_Click(object sender, EventArgs e)
{
int WindowToFind = FindWindow(null, "Form1");
}
</code></pre> | 5,084,002 | 6 | 2 | null | 2011-02-22 21:05:28.033 UTC | 8 | 2019-11-19 15:54:17.643 UTC | null | null | null | null | 629,099 | null | 1 | 16 | c#|sendmessage | 122,719 | <p>You don't need to send messages.</p>
<p>Add an <a href="http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx" rel="noreferrer">event</a> to the one form and an event handler to the other. Then you can use a third project which references the other two to attach the event handler to the event. The two DLLs don't need to reference each other for this to work.</p> |
5,587,207 | Why put void in params? | <p>What's the reason for putting void inside of the params? </p>
<p>Why not just leave it blank? </p>
<pre><code>void createLevel(void);
void createLevel();
</code></pre> | 5,587,262 | 6 | 5 | null | 2011-04-07 20:28:38.023 UTC | 7 | 2016-01-13 16:30:54.493 UTC | 2016-01-13 16:30:54.493 UTC | null | 2,504,659 | null | 438,339 | null | 1 | 36 | c++ | 11,383 | <p>The <code>void</code> in the parenthesis are from C. In C a function with empty parentheses could have any number of parameters. In C++ it doesn't make any difference.</p> |
4,981,440 | Scrapy - how to manage cookies/sessions | <p>I'm a bit confused as to how cookies work with Scrapy, and how you manage those cookies.</p>
<p>This is basically a simplified version of what I'm trying to do:
<img src="https://i.stack.imgur.com/nn517.png" alt="enter image description here"></p>
<hr>
<h2>The way the website works:</h2>
<p>When you visit the website you get a session cookie.</p>
<p>When you make a search, the website remembers what you searched for, so when you do something like going to the next page of results, it knows the search it is dealing with.</p>
<hr>
<h2>My script:</h2>
<p>My spider has a start url of searchpage_url</p>
<p>The searchpage is requested by <code>parse()</code> and the search form response gets passed to <code>search_generator()</code></p>
<p><code>search_generator()</code> then <code>yield</code>s lots of search requests using <code>FormRequest</code> and the search form response.</p>
<p>Each of those FormRequests, and subsequent child requests need to have it's own session, so needs to have it's own individual cookiejar and it's own session cookie.</p>
<hr>
<p>I've seen the section of the docs that talks about a meta option that stops cookies from being merged. What does that actually mean? Does it mean the spider that makes the request will have its own cookiejar for the rest of its life?</p>
<p>If the cookies are then on a per Spider level, then how does it work when multiple spiders are spawned? Is it possible to make only the first request generator spawn new spiders and make sure that from then on only that spider deals with future requests?</p>
<p>I assume I have to disable multiple concurrent requests.. otherwise one spider would be making multiple searches under the same session cookie, and future requests will only relate to the most recent search made?</p>
<p>I'm confused, any clarification would be greatly received!</p>
<hr>
<h2>EDIT:</h2>
<p>Another options I've just thought of is managing the session cookie completely manually, and passing it from one request to the other.</p>
<p>I suppose that would mean disabling cookies.. and then grabbing the session cookie from the search response, and passing it along to each subsequent request.</p>
<p>Is this what you should do in this situation?</p> | 25,516,223 | 6 | 2 | null | 2011-02-12 23:51:01.863 UTC | 37 | 2022-07-26 12:51:15.407 UTC | 2011-02-13 00:28:25.95 UTC | null | 311,220 | null | 311,220 | null | 1 | 62 | python|session|cookies|session-cookies|scrapy | 53,914 | <p>Three years later, I think this is exactly what you were looking for:
<a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#std:reqmeta-cookiejar" rel="noreferrer">http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#std:reqmeta-cookiejar</a></p>
<p>Just use something like this in your spider's start_requests method:</p>
<pre><code>for i, url in enumerate(urls):
yield scrapy.Request("http://www.example.com", meta={'cookiejar': i},
callback=self.parse_page)
</code></pre>
<p>And remember that for subsequent requests, you need to explicitly reattach the cookiejar each time:</p>
<pre><code>def parse_page(self, response):
# do some processing
return scrapy.Request("http://www.example.com/otherpage",
meta={'cookiejar': response.meta['cookiejar']},
callback=self.parse_other_page)
</code></pre> |
4,986,844 | What does "cdecl" stand for? | <p>Yes, I know that "cdecl" is the name of a prominent calling convention, so please don't explain calling conventions to me. What I'm asking is what the abbreviation (?) "cdecl" actually stands for. I think it's a poor naming choice, because at first sight it reminds one of "C declarator" (a rather unique syntactic aspect of C). In fact, there is a program called <a href="http://www.cdecl.org/" rel="noreferrer">cdecl</a> whose sole purpose is to decipher C declarators. But the C declarator syntax has absolutely nothing to do with calling conventions as far as I can tell.</p>
<p>Simplified version: "stdcall" stands for "standard calling convention". What does "cdecl" stand for?</p> | 69,833,093 | 8 | 8 | null | 2011-02-13 21:00:13.817 UTC | 10 | 2021-11-04 02:01:07.71 UTC | 2011-02-13 21:28:56.587 UTC | null | 505,088 | null | 252,000 | null | 1 | 38 | c++|c|calling-convention|nomenclature|cdecl | 16,640 | <p>The term CDECL originates from Microsoft's BASIC and their Mixed Language Programming ecosystem. The ecosystem permitted any of the Microsoft's four major languages (BASIC, FORTRAN, Pascal and C) to make calls to any other. Each language had a slightly different calling convention, and each had a way to declare an external function or procedure to be using a specific convention.</p>
<p>In BASIC, the <code>DECLARE</code> statement had to be used before you could call an external function with the <code>CALL</code> statement. To denote an external FORTRAN or Pascal procedure or function, you would write one of</p>
<pre><code>DECLARE SUB Foo ()
DECLARE FUNCTION Foo ()
</code></pre>
<p>C calling conventions differed from the other languages in part because the arguments were pushed on the stack in reverse order. You would inform BASIC of this by adding the CDECL modifier:</p>
<pre><code>DECLARE SUB Foo CDECL ()
DECLARE FUNCTION Foo CDECL ()
</code></pre>
<p>By contrast, when writing in FORTRAN or Pascal, the modifier is [C]. This is an indication CDECL was specific to BASIC's DECLARE statement and not
a previously established term. At the time, there was no specific term for "C calling conventions". Only with the advent of new calling conventions in WIN32 (stdcall, fastcall, etc) did "cdecl" get co-opted and become the de-facto name to refer to the legacy conventions in the absence of another term.</p>
<p>In summary, CDECL means "C declaration". It had its origins in BASIC compilers, not C compilers, and it was an arbitrarily-chosen BASIC keyword, and somewhat redundant because plain "C" could not be a keyword.</p>
<p>Details about CDECL can be found in this 1987 document:</p>
<p><a href="https://archive.org/details/Microsoft_Macro_Assembler_5.1_Mixed_Language_Programming_Guide/page/n1/mode/2up?q=cdecl" rel="nofollow noreferrer">https://archive.org/details/Microsoft_Macro_Assembler_5.1_Mixed_Language_Programming_Guide/page/n1/mode/2up?q=cdecl</a></p> |
5,472,362 | Android automatic horizontally scrolling TextView | <p>I am trying to implement a single-line text view that will scroll automatically. But I unfortunatly cannot get it to work. The AutoScrollTextView is declared inside a LinearLayout (width and height = fill_parent). The class basically uses a Handler that calls itself to scroll by a given amount. I have simplified the code to only show a text view that should be scrolling by 5 pixels every second.</p>
<p>The log output is correct, the getScrollX() method returns the appropriate scrollX position. </p>
<p>If I don't call <code>requestLayout()</code>, nothing gets drawn. <code>invalidate()</code> has no effect.</p>
<p>Would anybody have a clue?</p>
<pre><code>public class AutoScrollTextView extends TextView {
public AutoScrollTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setSingleLine();
setEllipsize(null);
setText("Single-line text view that scrolls automatically if the text is too long to fit in the widget");
}
// begin to scroll the text from the original position
public void startScrolling() {
scrollHandler.sendEmptyMessage(0);
}
private Handler scrollHandler = new Handler() {
private static final int REFRESH_INTERVAL = 1000;
public void handleMessage(Message msg) {
scrollBy(5, 0);
requestLayout();
Log.debug("Scrolled to " + getScrollX() + " px");
sendEmptyMessageDelayed(0, REFRESH_INTERVAL);
}
};
}
</code></pre> | 5,472,637 | 9 | 2 | null | 2011-03-29 12:18:04.667 UTC | 45 | 2022-08-11 14:00:27.34 UTC | null | null | null | null | 490,961 | null | 1 | 70 | android|scroll|textview | 106,458 | <p>If you don't need to sub-class the <code>TextView</code>, you can try this in your layout file:</p>
<pre><code> <TextView
android:text="Single-line text view that scrolls automatically if the text is too long to fit in the widget"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit ="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</code></pre>
<p>Also, in your code use the following:</p>
<pre><code>findViewById(R.id.serviceColorCode).setSelected(true);
</code></pre>
<p>[Answer edited based on comments]</p> |
17,018,685 | Display image in its actual size in angular.js | <p>I need to display an image in its actual size, even if it is bigger than its container. I tried the trick of using Image variable and <a href="https://stackoverflow.com/a/7686392/196451">capturing the size on load</a> with something like this:</p>
<p>HTML:</p>
<pre><code><div ng-controller="MyCtrl">
<input ng-model="imageurl" type="url" />
<button ng-click="loadimage()" type="button">Load Image</button>
<img ng-src="{{image.path}}"
style="width: {{image.width}}px; height: {{image.height}}px" />
</div>
</code></pre>
<p>Javascript:</p>
<pre><code>.controller("MyCtrl", ["$scope", function ($scope) {
$scope.image = {
path: "",
width: 0,
height: 0
}
$scope.loadimage = function () {
var img = new Image();
img.onload = function () {
$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
}
img.src = $scope.imageurl;
}
}]);
</code></pre>
<p>This script works, but only after the button is clicked several times if the image is big.</p>
<p>What should I do to make it work in one click?</p>
<p>Is there a better way to discover the image size than this?</p> | 17,018,779 | 3 | 2 | null | 2013-06-10 07:19:46.573 UTC | 2 | 2014-10-29 21:13:53.847 UTC | 2017-05-23 12:31:55.807 UTC | null | -1 | null | 196,451 | null | 1 | 5 | angularjs | 40,020 | <p>You need to use <a href="http://docs.angularjs.org/api/ng.%24rootScope.Scope#%24apply" rel="noreferrer"><code>$scope.$apply</code></a>, otherwise any changes to <code>$scope</code> made in non-Angular event handlers won't be processed properly:</p>
<pre><code>img.onload = function () {
$scope.$apply(function() {
$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
});
}
</code></pre> |
12,575,022 | Generating an Instagram- or Youtube-like unguessable string ID in ruby/ActiveRecord | <p>Upon creating an instance of a given ActiveRecord model object, I need to generate a shortish (6-8 characters) unique string to use as an identifier in URLs, in the style of Instagram's photo URLs (like <a href="http://instagram.com/p/P541i4ErdL/" rel="nofollow noreferrer">http://instagram.com/p/P541i4ErdL/</a>, which I just scrambled to be a 404) or Youtube's video URLs (like <a href="http://www.youtube.com/watch?v=oHg5SJYRHA0" rel="nofollow noreferrer">http://www.youtube.com/watch?v=oHg5SJYRHA0</a>).</p>
<p>What's the best way to go about doing this? Is it easiest to just <a href="https://stackoverflow.com/questions/88311/how-best-to-generate-a-random-string-in-ruby">create a random string</a> repeatedly until it's unique? Is there a way to hash/shuffle the integer id in such a way that users can't hack the URL by changing one character (like I did with the 404'd Instagram link above) and end up at a new record?</p> | 12,587,277 | 3 | 7 | null | 2012-09-25 01:19:57.28 UTC | 8 | 2017-11-22 10:13:33.837 UTC | 2017-05-23 12:16:51.223 UTC | null | -1 | null | 463,892 | null | 1 | 13 | ruby|postgresql|activerecord|sinatra | 6,448 | <p>You could do something like this:</p>
<p><em>random_attribute.rb</em></p>
<pre><code>module RandomAttribute
def generate_unique_random_base64(attribute, n)
until random_is_unique?(attribute)
self.send(:"#{attribute}=", random_base64(n))
end
end
def generate_unique_random_hex(attribute, n)
until random_is_unique?(attribute)
self.send(:"#{attribute}=", SecureRandom.hex(n/2))
end
end
private
def random_is_unique?(attribute)
val = self.send(:"#{attribute}")
val && !self.class.send(:"find_by_#{attribute}", val)
end
def random_base64(n)
val = base64_url
val += base64_url while val.length < n
val.slice(0..(n-1))
end
def base64_url
SecureRandom.base64(60).downcase.gsub(/\W/, '')
end
end
Raw
</code></pre>
<p><em>user.rb</em></p>
<pre><code>class Post < ActiveRecord::Base
include RandomAttribute
before_validation :generate_key, on: :create
private
def generate_key
generate_unique_random_hex(:key, 32)
end
end
</code></pre> |
12,279,236 | backbone.js collection events | <p>I develop a jquery & backbone.js web app.<br>
One component has an html table and behind this table is a backbone.js collection.<br>
Any change in this collection should lead to an update of the html table, so I write </p>
<pre><code>this.collection.bind("reset add remove", this.renderRows, this);
</code></pre>
<p>So I update the html table, when the whole collection gets new, when a new model gets added and when a model gets removed. </p>
<p>There's also a detail view component that gets called when the user hovers and clicks over a certain row of the html table. At the beginning of this component I get the right model out of the collection</p>
<pre><code>changeModel = this.collection.get(id);
</code></pre>
<p>After the user has changed some attributes, I do</p>
<pre><code>changeModel.set(attrs);
</code></pre>
<p>and return to the html table. The model in the collection has the correct changed values.</p>
<p>But the html table is not updated as none of the 3 events (reset, add, remove) was triggered. </p>
<p>So I added "replace" to the collection binding</p>
<pre><code>this.collection.bind("replace reset add remove", this.renderRows, this);
</code></pre>
<p>and before returning from the detail view I called </p>
<pre><code>this.collection.trigger("replace");
</code></pre>
<p>My solution works, but my question is:</p>
<p>Is there any "native" backbone.js solution that is already there and that I have missed and where I do not have to trigger something by myself?</p> | 12,279,458 | 1 | 0 | null | 2012-09-05 10:19:02.507 UTC | 12 | 2021-11-30 14:56:12.69 UTC | 2013-11-06 16:09:40.667 UTC | null | 229,044 | null | 780,522 | null | 1 | 16 | backbone.js | 44,892 | <p>The <code>change</code> events from models bubble up to the collection. (Collection's <code>_onModelEvent</code> -function in the <a href="http://backbonejs.org/docs/backbone.html#section-105" rel="nofollow noreferrer">annotated source</a>. The method just basically takes all events from models and triggers them on the collection.</p>
<p>This leads to</p>
<ol>
<li>Model attribute is set</li>
<li>Model triggers <code>change</code></li>
<li>Collection catches <code>change</code></li>
<li>Collection triggers <code>change</code></li>
</ol>
<p>So</p>
<pre><code>this.collection.bind("replace reset add remove", this.renderRows, this);
</code></pre>
<p>has to be replaced with this</p>
<pre><code>this.collection.bind("change reset add remove", this.renderRows, this);
</code></pre>
<p>P.S.</p>
<p>My personal opinion is that you shouldn't redraw the whole table if just one model is changed. Instead make each table row a view in itself that has the corresponding model as its model and then react to attribute changes there. There is no point in redrawing 500 table cells if you're targeting just one.</p>
<p><strong>UPDATE</strong></p>
<p>And nowadays you should use the <code>on</code> -method for binding to events.</p>
<pre><code>collection.on("change reset add remove", this.renderRows, this);
</code></pre>
<p>If you're using BB 1.0, and this event is being listened to within a <code>View</code>, I suggest moving to use the new <a href="http://backbonejs.org/#Events-listenTo" rel="nofollow noreferrer"><code>listenTo</code></a> to bind into events, which also allows for easy unbinding when calling <code>view.remove()</code>. In that case you should do:</p>
<pre><code>// assuming this is the view
this.listenTo(collection, "change reset add remove", this.renderRows);
</code></pre> |
12,562,624 | Terminal window inside Sublime Text 2 | <p>I saw <a href="http://wbond.net/sublime_packages/terminal">this project</a> that basically opens a new terminal window from sublime text-2.<br>
What I'm looking for is a way to open the terminal <strong>inside</strong> sublime text 2 via console.<br>
Does anyone knows how can I do that?</p> | 12,563,619 | 6 | 0 | null | 2012-09-24 09:54:15.153 UTC | 10 | 2019-05-24 01:58:30.963 UTC | 2013-10-18 12:49:26.657 UTC | null | 771,578 | null | 543,601 | null | 1 | 51 | terminal|sublimetext2 | 91,660 | <p>SublimeREPL does what you want</p>
<p><a href="https://github.com/wuub/SublimeREPL/">https://github.com/wuub/SublimeREPL/</a></p>
<p>Of course, there are some limitations because the window of Sublime Text 2 is not originally designed for continuous running buffer of stdin input.</p> |
19,122,942 | AngularJS sorting rows by table header | <p>I have four table headers:</p>
<pre><code>$scope.headers = ["Header1", "Header2", "Header3", "Header4"];
</code></pre>
<p>And I want to be able to sort my table by clicking on the header.</p>
<p>So if my table looks like this</p>
<pre><code>H1 | H2 | H3 | H4
A H D etc....
B G C
C F B
D E A
</code></pre>
<p>and I click on</p>
<pre><code>H2
</code></pre>
<p>my table now looks like this:</p>
<pre><code>H1 | H2 | H3 | H4
D E A etc....
C F B
B G C
A H D
</code></pre>
<p>That is, the content of each column never changes, but by clicking on the header I want to order the columns by, the rows will reorder themselves.</p>
<p>The content of my table is created by a database call done with <a href="https://en.wikipedia.org/wiki/Mojolicious" rel="noreferrer">Mojolicious</a> and is returned to the browser with</p>
<pre><code>$scope.results = angular.fromJson(data); // This works for me so far
</code></pre>
<p>The rest of the code I have cobbled together looks something like this:</p>
<pre><code><table class= "table table-striped table-hover">
<th ng-repeat= "header in headers">
<a> {{headers[$index]}} </a>
</th>
<tr ng-repeat "result in results">
<td> {{results.h1}} </td>
<td> {{results.h2}} </td>
<td> {{results.h3}} </td>
<td> {{results.h4}} </td>
</tr>
</table>
</code></pre>
<p>How do I order the columns from this point, just by clicking on the header at the top of the table?</p> | 19,123,525 | 9 | 4 | null | 2013-10-01 18:06:18.623 UTC | 32 | 2020-03-25 01:19:22.947 UTC | 2016-11-28 23:56:26.74 UTC | null | 4,370,109 | null | 1,108,761 | null | 1 | 68 | angularjs|angularjs-ng-repeat|html-table | 141,623 | <p>I think this <a href="http://codepen.io/anon/pen/fjkcg">working CodePen example</a> that I created will show you exactly how to do what you want.</p>
<p>The template:</p>
<pre><code><section ng-app="app" ng-controller="MainCtrl">
<span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
<table class="table table-bordered">
<thead>
<tr>
<th>
<a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">
<td>{{emp.firstName}}</td>
<td>{{emp.lastName}}</td>
<td>{{emp.age}}</td>
</tr>
</tbody>
</table>
</section>
</code></pre>
<p>The JavaScript code:</p>
<pre><code>var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.orderByField = 'firstName';
$scope.reverseSort = false;
$scope.data = {
employees: [{
firstName: 'John',
lastName: 'Doe',
age: 30
},{
firstName: 'Frank',
lastName: 'Burns',
age: 54
},{
firstName: 'Sue',
lastName: 'Banter',
age: 21
}]
};
});
</code></pre> |
24,208,842 | Visual Studio 2013, TFS is very slow | <p>When I originally installed VS Ultimate 2013 everything was fine but for the last month or so it's been a dog.
The source control explore in my Visual Studio 2013 install is very slow. Just clicking on a node and the act of displaying the node contents takes 20+ seconds.</p>
<p>Everyone else on the team is ok so it's not the TFS server it's just my install.
I assumed it was some addin I'd installed into VS so disabled them but no luck.</p>
<p>Any ideas?</p> | 24,264,059 | 13 | 5 | null | 2014-06-13 15:22:05.897 UTC | 8 | 2021-04-19 07:27:44.537 UTC | null | null | null | null | 17,579 | null | 1 | 35 | tfs|visual-studio-2013 | 28,267 | <p>Having tried all suggestions, unloaded all add ons, tried to reinstall VS, removed all extra workspaces etc. the answer to my problem was to unmap my workspace and then remap it.
Problem solved. Not got a clue what the underlying fault was.</p> |
3,583,757 | How to make sure that Tomcat6 reads CATALINA_OPTS on Windows? | <p>I have a Tomcat6 running on a Windows2003 machine.
I deployed 2 Grails apps on this server and I soon noticed that everything was crashing sometime after the deploy with a classic PermGen error.</p>
<pre><code>java.lang.OutOfMemoryError: PermGen space
java.lang.ClassLoader.defineClass1(Native Method)
java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
java.lang.ClassLoader.defineClass(ClassLoader.java:616)
org.codehaus.groovy.reflection.ClassLoaderForClassArtifacts.de
...
</code></pre>
<p>So I found a common fix for this problem: increasing heap and permgen space with:</p>
<pre><code>set CATALINA_OPTS="-Xms1024m -Xmx1024m -XX:PermSize=128m -XX:MaxPermSize=512m"
</code></pre>
<p>Added into C:\apache-tomcat-6.0.26\bin\catalina.bat.
Unfortunately this didn't work, but the problem is that I'm not sure that Tomcat is picking it up. I checked various logs but these options are never printed out.
Is there a way to log them and make sure that Tomcat has read them?</p>
<p>EDIT: I tried to add the following JVM options with tomcat6w.exe:</p>
<pre><code>-XX:+CMSClassUnloadingEnabled
-XX:+CMSPermGenSweepingEnabled
-XX:+UseConcMarkSweepGC
</code></pre>
<p>And nothing changed. I get a permGen after 2-3 minutes of uptime.
Any other idea?</p>
<p>Cheers!
Mulone</p> | 3,600,542 | 4 | 3 | null | 2010-08-27 11:41:24.85 UTC | 7 | 2015-02-16 00:58:50.943 UTC | 2010-08-27 12:05:02.39 UTC | null | 338,365 | null | 338,365 | null | 1 | 6 | tomcat|logging|grails|permgen | 38,000 | <p>Thank you all!
I finally solved the issue by adding:</p>
<pre><code>-XX:+CMSClassUnloadingEnabled
-XX:+CMSPermGenSweepingEnabled
-XX:+UseConcMarkSweepGC
-XX:PermSize=128m
-XX:MaxPermSize=512m
</code></pre>
<p>To the java options on tomcat6w.exe.</p>
<p>Thanks!</p> |
22,520,413 | C strlen() implementation in one line of code | <p>Yesterday I was at interview and was asked to implement strlen() in C without using any standard functions, all by hands. As an absolute amateur, I implemented primitive version with while loop. Looking at this my interviewer said that it can be implemented at just one line of code. I wasn't be able to produce this code using that term at that moment. After interview I asked my colleagues, and the most experienced from them gave me this piece which really worked fine:</p>
<pre><code>size_t str_len (const char *str)
{
return (*str) ? str_len(++str) + 1 : 0;
}
</code></pre>
<p>So there is a question, is it possible without using recursion, and if yes, how?
Terms:</p>
<ul>
<li>without any assembler</li>
<li>without any C functions existed in libraries</li>
<li>without just spelling few strings of code in one</li>
</ul>
<p>Please, take note that this is not the question of optimization or real using, just the possibility of make task done.</p> | 22,520,702 | 9 | 6 | null | 2014-03-19 23:30:27.753 UTC | 8 | 2017-08-24 16:44:21.487 UTC | null | null | null | null | 1,236,726 | null | 1 | 12 | c|algorithm|strlen | 15,651 | <p>Similar to @DanielKamilKozar's answer, but with a for-loop, you can do this with no for-loop body, and <code>len</code> gets initialized properly in the function:</p>
<pre><code>void my_strlen(const char *str, size_t *len)
{
for (*len = 0; str[*len]; (*len)++);
}
</code></pre> |
19,145,787 | FieldError: Cannot resolve keyword 'XXXX' into field | <p>This is a very strange error. I only receive it on my heroku server. </p>
<p>Here is how my model is: </p>
<pre><code># Abstract Model
class CommonInfo(models.Model):
active = models.BooleanField('Enabled?', default=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Country(CommonInfo):
name = models.CharField('Country Name', db_index=True, max_length=200, help_text='e.g. France')
official_name = models.CharField('Official Name', max_length=400, blank=True, help_text='e.g. French Republic')
population = models.IntegerField('Population', help_text='Population must be entered as numbers with no commas or separators, e.g. 39456123', null=True, blank=True)
alpha2 = models.CharField('ISO ALPHA-2 Code', max_length=2, blank=True)
class News(CommonInfo):
title = models.CharField('Title', max_length=250)
slug = models.CharField('slug', max_length=255, unique=True)
body = models.TextField('Body', null=True, blank=True)
excerpt = models.TextField('Excerpt', null=True, blank=True)
author = models.ForeignKey(Author)
country = models.ManyToManyField(Country, null=True, blank=True)
def __unicode__(self):
return self.title
</code></pre>
<p>When I try to access News items from Admin site on my production server, I get this error (everything works fine on my dev server):</p>
<pre><code>FieldError: Cannot resolve keyword 'news' into field. Choices are: active, alpha2, date_created, date_updated, id, name, official_name, population
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py", line 687, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1271, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1139, in add_filter
process_extras=process_extras)
File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1337, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
</code></pre>
<p>I run the same django (1.5.4) and python (2.7.2) versions on my production and development environments. </p>
<p>My production server is Heroku</p>
<p>Any ideas what could triggers the error?</p>
<p><strong>UPDATE</strong>:</p>
<p>admin.py config is as follow:</p>
<pre><code>from django.contrib import admin
from APP.models import Country, News
class NewsForm(ModelForm):
class Meta:
model = News
class NewsAdmin(ModelAdmin):
form = NewsForm
search_fields = ['title',
'country__name']
list_filter = ('country',
'active'
)
list_per_page = 30
list_editable = ('active', )
list_display = ('title',
'active'
)
list_select_related = True
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Country)
admin.site.register(News, NewsAdmin)
</code></pre> | 19,418,412 | 6 | 12 | null | 2013-10-02 20:00:29.503 UTC | 4 | 2020-04-16 16:28:00.873 UTC | 2013-10-02 21:04:10.493 UTC | null | 1,197,939 | null | 1,197,939 | null | 1 | 18 | python|django | 57,050 | <p>Finally, I was able to resolve the issue.</p>
<p>First, I managed to replicate the error in my local environment. At first, I was testing the application using built-in Django runserver. However, my production environment is Heroku that uses Gunicorn as webserver. When I switched to Gunicorn and foreman on my local server, I was able to replicate the error. </p>
<p>Second, I tried to pin point the issue by going through the models and add/remove different components, fields. To explain the process better, I have to add a missing piece to the original question. </p>
<p>The description I had posted above is kind of incomplete. I have another model in my models.py that I did not include in my original question, because I thought it was not relevant. Here is the complete model:</p>
<pre><code># Abstract Model
class CommonInfo(models.Model):
active = models.BooleanField('Enabled?', default=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Country(CommonInfo):
name = models.CharField('Country Name', db_index=True, max_length=200, help_text='e.g. France')
official_name = models.CharField('Official Name', max_length=400, blank=True, help_text='e.g. French Republic')
population = models.IntegerField('Population', help_text='Population must be entered as numbers with no commas or separators, e.g. 39456123', null=True, blank=True)
alpha2 = models.CharField('ISO ALPHA-2 Code', max_length=2, blank=True)
def get_country_names():
names = Country.objects.only('name').filter(active=1)
names = [(str(item), item) for item in names]
return names
class Person(CommonInfo):
name = models.CharField(max_length=200)
lastname = models.CharField(max_length=300)
country = models.CharField(max_length=250, choices=choices=get_country_names())
class News(CommonInfo):
title = models.CharField('Title', max_length=250)
slug = models.CharField('slug', max_length=255, unique=True)
body = models.TextField('Body', null=True, blank=True)
excerpt = models.TextField('Excerpt', null=True, blank=True)
author = models.ForeignKey(Author)
country = models.ManyToManyField(Country, null=True, blank=True)
def __unicode__(self):
return self.title
</code></pre>
<p>My model design didn't require a ForeignKey for Person's table, so I had decided to go with a simple CharField and instead, use a regular drop down menu. However, for some reason, Gunicorn raises the above mentioned error when, as part of the get_country_names(), the Country table is called before News. As soon as I deleted the get_country_names() and turned the country field on Person table into a regular CharField the issue was resolved. </p>
<p>Reading through the comments in <a href="https://code.djangoproject.com/ticket/1796" rel="noreferrer">this old Django bug</a> and <a href="http://chase-seibert.github.io/blog/2010/04/30/django-manytomany-error-cannot-resolve-keyword-xxx-into-a-field.html" rel="noreferrer">this post</a> by Chase Seibert considerably helped me in this process. </p>
<p>Although ticket#1796 appears to be fixed more than 6 years ago, it seems that some tiny issues still remain deep buried there.</p>
<p>Thats it! Thanks everyone. </p> |
11,020,575 | PHP: return value from function and echo it directly? | <p>this might be a stupid question but …</p>
<p><strong>php</strong></p>
<pre><code>function get_info() {
$something = "test";
return $something;
}
</code></pre>
<p><strong>html</strong></p>
<pre><code><div class="test"><?php echo get_info(); ?></div>
</code></pre>
<p>Is there a way to make the function automatically "echo" or "print" the returned statement?
Like I wanna do this … </p>
<pre><code><div class="test"><?php get_info(); ?></div>
</code></pre>
<p>… without the "echo" in it?</p>
<p>Any ideas on that? Thank you in advance!</p> | 11,020,600 | 7 | 0 | null | 2012-06-13 17:53:58.697 UTC | 4 | 2020-08-22 09:49:03.493 UTC | 2012-06-13 18:54:11.653 UTC | null | 83,805 | null | 1,444,475 | null | 1 | 16 | php|function|echo | 98,476 | <p>You can use the special tags:</p>
<pre><code><?= get_info(); ?>
</code></pre>
<p>Or, of course, you can have your function echo the value:</p>
<pre><code>function get_info() {
$something = "test";
echo $something;
}
</code></pre> |
11,233,633 | Understanding Asynchronous Code in Layman's terms | <p>I understand the basic thing about asynchronous-ness: things don't execute sequentially. And I understand there is something very powerful about that... allegedly. But for the life of me I can't wrap my head around the code. Let's take a look at async Node.JS code that I HAVE WRITTEN...but don't truly get.</p>
<pre><code>function newuser(response, postData) {
console.log("Request handler 'newuser' was called.");
var body = '<html>' +
'<head>' +
'<meta http-equiv="Content-Type" content="text/html; ' +
'charset=UTF-8" />' +
'</head>' +
'<body>' +
'<form action=" /thanks" method="post">' +
'<h1> First Name </h1>' +
'<textarea name="text" rows="1" cols="20"></textarea>' +
'<h1> Last Name </h1>' +
'<textarea name="text" rows="1" cols="20"></textarea>' +
'<h1> Email </h1>' +
'<textarea name="text" rows="1" cols="20"></textarea>' +
'<input type="submit" value="Submit text" />' +
'</body>' +
'</html>';
response.writeHead(200, { "Content-Type": "text/html" });
response.write(body);
response.end();
}
</code></pre>
<p>Where did response come from again? postData? Why can't I define a variable in this "callback" and then use it outside of the callback? Is there a way to have a few things be sequential then the rest of the program async?</p> | 11,233,849 | 3 | 0 | null | 2012-06-27 19:32:04.403 UTC | 16 | 2013-08-10 21:10:55.537 UTC | 2012-06-27 19:46:48.087 UTC | null | 361,684 | null | 1,222,564 | null | 1 | 21 | javascript|node.js|asynchronous | 16,709 | <p>I'm not sure where this function is being used, but the point of callbacks is that you pass them into some function that runs asynchronously; it stores your callback away, and when that function is done with whatever it needs to do, it will <em>call</em> your callback with the necessary parameters. An example from front-to-back is probably best.</p>
<p>Imagine we have a framework, and in it there is an operation that runs for a long time, fetching some data from the database.</p>
<pre><code>function getStuffFromDatabase() {
// this takes a long time
};
</code></pre>
<p>Since we don't want it to run synchronously, we'll allow the user to pass in a callback.</p>
<pre><code>function getStuffFromDatabase(callback) {
// this takes a long time
};
</code></pre>
<p>We'll simulate taking a long time with a call to <code>setTimeout</code>; we'll also pretend we got some data from the database, but we'll just hardcode a string value.</p>
<pre><code>function getStuffFromDatabase(callback) {
setTimeout(function() {
var results = "database data";
}, 5000);
};
</code></pre>
<p>Finally, once we have the data, we'll <em>call</em> the callback given to us by the user of the framework's function.</p>
<pre><code>function getStuffFromDatabase(callback) {
setTimeout(function() {
var results = "database data";
callback(results);
}, 5000);
};
</code></pre>
<p>As a user of the framework, you'd do something like this to use the function:</p>
<pre><code>getStuffFromDatabase(function(data) {
console.log("The database data is " + data);
});
</code></pre>
<p>So, as you can see <code>data</code> (same as <code>response</code> and <code>postData</code> in your example) came from the function that you pass your callback <em>into</em>; it gives that data to you when it knows what that data should be.</p>
<p>The reason you can't set a value in your callback and use it outside the callback is because the callback itself doesn't happen until later in time.</p>
<pre><code>// executed immediately executed sometime in the future
// | | by getStuffFromDatabase
// v v
getStuffFromDatabase(function(data) {
var results = data; // <- this isn't available until sometime in the future!
});
console.log(results); // <- executed immediately
</code></pre>
<p>When the <code>console.log</code> runs, the assignment of <code>var results</code> hasn't happened yet!</p> |
11,453,530 | applicationContext not finding Controllers for Servlet context | <p>I have a Spring web app with an applicationContext.xml and a dispatcher-servlet.xml configuration. I've defined the <code><context:component-scan /></code> in applicationContext.xml, but when I run my app the Controllers are not found unless I also add <code><context:component-scan /></code> to the dispatcher-servlet.xml. I'm using the same base-package in both, so that's not the issue.</p>
<p>I am confused, because I <em>thought</em> that the applicationContext.xml was a parent of dispatcher-servlet.xml. Wouldn't putting <code><context:component-scan /></code> in applicationContext.xml suffice?</p>
<p>web.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
<p>EDIT: I am also using mvc:annotation-driven in the dispatcher-servlet.xml, which is supposed to pick up Controllers (I thought?).</p>
<p>EDIT 2: Here are the config files. I removed a bunch of Spring Security and OAuth settings from applicationContext.xml (for security reasons and being they probably aren't relevant anyway).</p>
<p>applicationContext.xml</p>
<pre><code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="bar.foo"/>
<context:property-placeholder location="classpath:my.properties" />
<bean class="bar.foo.ServicesConfig" />
</beans>
</code></pre>
<p>dispatcher-servlet.xml</p>
<pre><code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="bar.foo.controller" />
<mvc:annotation-driven/>
<mvc:default-servlet-handler />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="order" value="2" />
</bean>
<bean id="contentViewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
</map>
</property>
<property name="defaultViews">
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</property>
<property name="order" value="1" />
</bean>
</beans>
</code></pre>
<p>EDIT 3: Okay, this is interesting. My services and dao classes are in a different project (JAR) that I reference from the web project. I am using java-based config and referencing it from the applicationContext.xml:</p>
<pre><code><bean class="bar.foo.config.ServicesConfig" />
</code></pre>
<p>So, this means there are only Controller annotations in my web project (where applicationContext.xml is located). In retrospect, removing context:component-scan from my applicationContext.xml should not have any affect, since there are no annotations except for @Controller ones (FIX to EDIT: there are some @Autowired annotations). But, when I remove the context:component-scan from applicationContext.xml, it says that the Controllers (found from dispatcher servlet scan) cannot find my Service classes. Shouldn't the reference to the ServicesConfig be enough? Here is the ServicesConfig class for references - it has its own component scan for the Services, which are a different package from what the applicationContext.xml was scanning.</p>
<pre><code>@Configuration
@ComponentScan({ "some.other.package", "another.package" })
@ImportResource({ "classpath:commonBeans.xml" })
@PropertySource({ "classpath:services.properties",
"classpath:misc.properties" })
public class ServicesConfig {
// Bean definitions //
}
</code></pre>
<p>SOLUTION:</p>
<p>When I removed context:component-scan from my root context, the Controllers were not picking up the autowired services beans. This was because the root context references my services java-based config Bean, but I did not have the root context setup to scan for Components. Hence, when I add component scanning to the root context (applicationContext.xml) everything works. Here is what I have now:</p>
<p>applicationContext.xml:</p>
<pre><code><bean class="bar.foo.config.ServicesConfig" />
<context:component-scan base-package="bar.foo.config" />
</code></pre>
<p>dispatcher-servlet.xml:</p>
<pre><code><context:component-scan base-package="bar.foo.controller" />
</code></pre>
<p>I have the web context setup to pickup Controller, Autowired, and any other annotations in the controller package - I'm not sure if this is best practice or not.</p> | 11,471,568 | 3 | 3 | null | 2012-07-12 14:01:32.977 UTC | 13 | 2015-10-30 05:55:51.46 UTC | 2012-07-13 15:41:14.61 UTC | null | 971,813 | null | 971,813 | null | 1 | 22 | spring|spring-mvc|spring-annotations | 35,335 | <p>You are right - there are two different application contexts, the root application context loaded up by ContextLoaderListener (at the point the ServletContext gets initialized), and the Web Context (loaded up by DispatcherServlet), the root application context is the parent of the Web context.</p>
<p>Now, since these are two different application contexts, they get acted on differently - if you define <code>component-scan</code> for your services in application context, then all the beans for the services get created here.</p>
<p>When your Dispatcher servlet loads up it will start creating the Web Context, at some point(driven by <code><mvc:annotation-driven/></code> it will create a mapping for your uri's to handler methods, it will get the list of beans in the application context(which will be the web application context, not the Root application Context) and since you have not defined a <code>component-scan</code> here the controller related beans will not be found and the mappings will not get created, that is the reason why you have to define a component-scan in the dispatcher servlets context also.</p>
<p>A good practice is to exclude the Controller related beans in the Root Application Context:</p>
<pre><code><context:component-scan base-package="package">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
</code></pre>
<p>and only controller related one's in Web Application Context:</p>
<pre><code><context:component-scan base-package="package" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation" />
</context:component-scan>
</code></pre> |
11,112,216 | How to Convert a byte array into an int array? | <p>How to Convert a byte array into an int array? I have a byte array holding 144 items and the ways I have tried are quite inefficient due to my inexperience. I am sorry if this has been answered before, but I couldn't find a good answer anywhere.</p> | 11,112,236 | 4 | 2 | null | 2012-06-20 02:54:48.06 UTC | 3 | 2020-07-05 16:03:18.81 UTC | null | null | null | null | 1,166,981 | null | 1 | 24 | c#|arrays | 39,629 | <p>Simple:</p>
<pre><code>//Where yourBytes is an initialized byte array.
int[] bytesAsInts = yourBytes.Select(x => (int)x).ToArray();
</code></pre>
<p>Make sure you include <code>System.Linq</code> with a using declaration:</p>
<pre><code>using System.Linq;
</code></pre>
<p>And if LINQ isn't your thing, you can use this instead:</p>
<pre><code>int[] bytesAsInts = Array.ConvertAll(yourBytes, c => (int)c);
</code></pre> |
11,021,304 | JDBC connection default autoCommit behavior | <p>I'm working with JDBC to connect to Oracle. I tested <code>connection.setAutoCommit(false)</code> vs <code>connection.setAutoCommit(true)</code> and the results were as expected. </p>
<p>While by default connection is supposed to work as if <code>autoCommit(true)</code> [correct me if I'm wrong], but none of the records are being inserted till <code>connection.commit()</code> was called. Any advice regarding default behaviour?</p>
<pre><code>String insert = "INSERT INTO MONITOR (number, name,value) VALUES (?,?,?)";
conn = connection; //connection details avoided
preparedStmtInsert = conn.prepareStatement(insert);
preparedStmtInsert.execute();
conn.commit();
</code></pre> | 11,022,406 | 1 | 4 | null | 2012-06-13 18:42:19.85 UTC | 3 | 2016-11-07 11:15:06.787 UTC | 2016-11-07 11:15:06.787 UTC | null | 814,702 | null | 1,454,452 | null | 1 | 27 | oracle|jdbc|autocommit | 39,774 | <p>From <a href="http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html">Oracle JDBC documentation</a>:</p>
<blockquote>
<p>When a connection is created, it is in auto-commit mode. This means
that each individual SQL statement is treated as a transaction and is
automatically committed right after it is executed. (To be more
precise, <strong>the default is for a SQL statement to be committed when it is
completed, not when it is executed. A statement is completed when all
of its result sets and update counts have been retrieved</strong>. In almost
all cases, however, a statement is completed, and therefore committed,
right after it is executed.)</p>
</blockquote>
<p>The other thing is - you ommitted connection creation details, so I'm just guessing - if you are using some frameworks, or acquiring a connection from a datasource or connection pool, the <code>autocommit</code> may be turned <code>off</code> by those frameworks/pools/datasources - the solution is to never trust in default settings ;-)</p> |
11,053,516 | CSS Styling for a Button: Using <input type="button> instead of <button> | <p>I'm trying to style a button using <code><input type="button"></code> instead of just <code><button></code>. With the code I have, the button extends all the way across the screen. I just want to be able to fit it to the text that it's in the button. Any ideas?</p>
<p>See the <a href="http://jsfiddle.net/8bDux/">jsFiddle Example</a> or continue on to the HTML:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>WTF</title>
</head>
<style type="text/css">
.button {
color:#08233e;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
padding:14px;
background:url(overlay.png) repeat-x center #ffcc00;
background-color:rgba(255,204,0,1);
border:1px solid #ffcc00;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
border-bottom:1px solid #9f9f9f;
-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
cursor:pointer;
}
.button:hover {
background-color:rgba(255,204,0,0.8);
}
</style>
<body>
<div class="button">
<input type="button" value="TELL ME MORE" onClick="document.location.reload(true)">
</div>
</body>
</code></pre>
<p></p> | 11,053,651 | 6 | 1 | null | 2012-06-15 15:16:28.553 UTC | 4 | 2018-01-06 09:38:29.023 UTC | 2012-06-15 15:19:25.753 UTC | null | 526,741 | null | 1,306,994 | null | 1 | 28 | css|button | 301,356 | <p>In your <code>.button</code> CSS, try <code>display:inline-block</code>. See this <a href="http://jsfiddle.net/w29DC/" rel="noreferrer">JSFiddle</a></p> |
11,185,873 | Variable scope and Try Catch in python | <pre><code>import Image
import os
for dirname, dirs, files in os.walk("."):
for filename in files:
try:
im = Image.open(os.path.join(dirname,filename))
except IOError:
print "error opening file :: " + os.path.join(dirname,filename)
print im.size
</code></pre>
<p>Here I'm trying to print the size of all the files in a directory (and sub). But I know <code>im</code> is outside the scope when in the line <code>im.size</code>. But how else do I do it without using <code>else</code> or <code>finally</code> blocks.</p>
<p>The following error is shown:</p>
<pre><code>Traceback (most recent call last):
File "batch.py", line 13, in <module>
print im.size
NameError: name 'im' is not defined
</code></pre> | 11,185,984 | 3 | 6 | null | 2012-06-25 08:33:55.413 UTC | 5 | 2017-04-18 15:58:26.687 UTC | 2017-04-18 15:58:26.687 UTC | null | 1,516,116 | null | 835,415 | null | 1 | 31 | python|variables|try-catch|scope|python-imaging-library | 34,965 | <p>What's wrong with the "else" clause ?</p>
<pre><code>for filename in files:
try:
im = Image.open(os.path.join(dirname,filename))
except IOError, e:
print "error opening file :: %s : %s" % (os.path.join(dirname,filename), e)
else:
print im.size
</code></pre>
<p>Now since you're in a loop, you can also use a "continue" statement:</p>
<pre><code>for filename in files:
try:
im = Image.open(os.path.join(dirname,filename))
except IOError, e:
print "error opening file :: %s : %s" % (os.path.join(dirname,filename), e)
continue
print im.size
</code></pre> |
11,268,437 | How to convert string to integer in UNIX shelll | <p>I have <code>d1="11"</code> and <code>d2="07"</code>. I want to convert <code>d1</code> and <code>d2</code> to integers and perform <code>d1-d2</code>. How do I do this in UNIX?</p>
<p><code>d1 - d2</code> currently returns <code>"11-07"</code> as result for me.</p> | 11,269,389 | 5 | 1 | null | 2012-06-29 20:18:46.37 UTC | 12 | 2022-07-15 12:22:16.257 UTC | 2022-07-15 12:22:16.257 UTC | null | 4,374,258 | null | 1,484,056 | null | 1 | 57 | linux|shell|unix|interactive | 300,422 | <p>The standard solution:</p>
<pre><code> expr $d1 - $d2
</code></pre>
<p>You can also do:</p>
<pre><code>echo $(( d1 - d2 ))
</code></pre>
<p>but beware that this will treat <code>07</code> as an octal number! (so <code>07</code> is the same as <code>7</code>, but <code>010</code> is different than <code>10</code>).</p> |
11,397,757 | SQL COUNT* GROUP BY bigger than, | <p>I want to select the distinct keys with the occurence number, this query seems functionate:</p>
<pre><code>SELECT ItemMetaData.KEY, ItemMetaData.VALUE, count(*)
FROM ItemMetaData
GROUP BY ItemMetaData.KEY
ORDER BY count(*) desc;
</code></pre>
<p>But I also want to filter these result, meaning I want only where count(*) is greater than 2500 so only bigger than 2500 occurence will shown, but:</p>
<pre><code>SELECT *
FROM
(
SELECT ItemMetaData.KEY, ItemMetaData.VALUE, count(*)
FROM ItemMetaData
GROUP BY ItemMetaData.KEY
ORDER BY count(*) desc
) as result WHERE count(*)>2500;
</code></pre>
<p>Unfortunately this query results in a syntax error. Can you help me achieve my requirement?</p> | 11,397,793 | 4 | 1 | null | 2012-07-09 15:01:54.297 UTC | 6 | 2017-08-23 10:24:41.233 UTC | 2016-02-11 21:30:16.46 UTC | null | 179,386 | null | 1,087,718 | null | 1 | 63 | sql|count|group-by | 96,869 | <p>HAVING clause for aggregates</p>
<pre><code>SELECT ItemMetaData.KEY, ItemMetaData.VALUE, count(*)
FROM ItemMetaData
Group By ItemMetaData.KEY, ItemMetaData.VALUE
HAVING count(*) > 2500
ORDER BY count(*) desc;
</code></pre> |
11,089,540 | Textarea height: 100% | <p>Here's my fiddle: <a href="http://jsfiddle.net/e6kCH/15/" rel="noreferrer">http://jsfiddle.net/e6kCH/15/</a></p>
<p>It may sound stupid, but I can't find a way to make the text area height equal to 100%. It works for the width, but not for height.</p>
<p>I want the text area to resize depending of the window size...like it works in my fiddle for the width...</p>
<p>Any ideas?</p> | 11,089,591 | 1 | 0 | null | 2012-06-18 19:16:47.59 UTC | 2 | 2016-02-17 18:44:14.487 UTC | 2012-07-20 20:14:16.307 UTC | null | 830,691 | null | 1,290,453 | null | 1 | 73 | html|css | 84,233 | <p><strong>Height of an element is relative to its parent.</strong> Thus, if you want to make expand your element into the whole height of the viewport, you need to apply your CSS to <code>html</code> and <code>body</code> as well (the parent elements):</p>
<pre><code>html, body {
height: 100%;
}
#textbox {
width: 100%;
height: 100%;
}
</code></pre>
<p><strong>Alternative solution with CSS3</strong>: If you can use CSS3, you can use <a href="http://dev.w3.org/csswg/css-values/#viewport-relative-lengths" rel="noreferrer">Viewport percentage units</a> and directly scale your textbox to 100 % height (and 100% width) of the viewport <a href="http://jsfiddle.net/A22SF/" rel="noreferrer">(jsfiddle here)</a></p>
<pre><code>body {
margin: 0;
}
#textbox {
width: 100vw;
height: 100vh;
}
</code></pre> |
11,207,638 | Advantages of bundledDependencies over normal dependencies in npm | <p>npm allows us to specify <a href="https://docs.npmjs.com/files/package.json#bundleddependencies" rel="noreferrer"><code>bundledDependencies</code></a>, but what are the advantages of doing so? I guess if we want to make absolutely sure we get the right version even if the module we reference gets deleted, or perhaps there is a speed benefit with bundling?</p>
<p>Anyone know the advantages of <code>bundledDependencies</code> over normal dependencies?</p> | 11,292,519 | 5 | 4 | null | 2012-06-26 12:45:48.98 UTC | 23 | 2019-11-21 09:55:40.76 UTC | 2019-03-19 23:56:21.16 UTC | null | 2,688,027 | null | 130,638 | null | 1 | 92 | node.js|npm|dependencies | 53,045 | <p>One of the biggest problems right now with Node is how fast it is changing. This means that production systems can be very fragile and an <code>npm update</code> can easily break things.</p>
<p>Using bundledDependencies is a way to get round this issue by ensuring, as you correctly surmise, that you will always deliver the correct dependencies no matter what else may be changing.</p>
<p>You can also use this to bundle up your own, private bundles and deliver them with the install.</p> |
13,190,337 | Avoid Memory Leak / Usage Javascript | <p>I am newbie to jQuery. I am bit confused whether is it fine or may cause memory leak ?</p>
<p>Here is the code: This method is called on certain date filters for each new values </p>
<pre><code>function preapreTooltip(chart) {
var tickLength = chart.xAxis[0].tickPositions.length,
ticks = chart.xAxis[0].ticks,
tickPositions = chart.xAxis[0].tickPositions;
for ( var iCntr = 0; iCntr < tickLength; iCntr++) {
var tickVal = tickPositions[iCntr];
//.label or .mark or both
(function(tickVal) { // Is this good practice to call function like this?
ticks[tickVal].label
.on('mouseover', function(event) { // Is this good practice to call function like this?
var label = '', labelCnt=0;
$(chart.series).each(function(nCntr, series) {
//business logic for each series
});
// calling method to show values in a popup
});
ticks[tickVal].label.on('mouseout', function(event) { // Is this good practice to call function like this?
try {
hideWrapper(); // hides popup
} catch (e) {
// do nothing
}
});
})(tickVal);
}
}
</code></pre> | 13,191,289 | 2 | 7 | null | 2012-11-02 06:21:47.573 UTC | 11 | 2016-05-26 10:54:07.187 UTC | 2012-11-02 06:50:44.767 UTC | null | 559,026 | null | 559,026 | null | 1 | 13 | javascript|jquery|memory-leaks | 7,552 | <p>Whilst there are browser specific issues that need to be avoided when writing large pure JavaScript projects, when using a library such as jQuery it should be assumed that the library's design helps you avoid these problems. However, considering memory leaks are rather hard to track down, and each different version of a particular browser could behave differently - it is far better to know how to generally avoid memory leaks than being specific:</p>
<ol>
<li>If your code is being iterated many times, make sure the variables you are using can be discarded by <em>garbage collection</em>, and are not tied up in closure references.</li>
<li>If your code is dealing with large data structures, make sure you have a way of removing or nullifying the data.</li>
<li>If your code constructs many objects, functions and event listeners - it is always best to include some deconstructive code too.</li>
<li>Try to avoid attaching javascript objects or functions to elements directly as an attribute - i.e. <code>element.onclick = function(){}</code>.</li>
<li>If in doubt, always tidy up when your code is finished.</li>
</ol>
<p>You seem to believe that it is the way of calling a function that will have an effect on leaking, however it is always much more likely to be the content of those functions that could cause a problem.</p>
<h3>With your code above, my only suggestions would be:</h3>
<ol>
<li><p>Whenever using event listeners try and find a way to reuse functions rather than creating one per element. This can be achieved by using <a href="http://icant.co.uk/sandbox/eventdelegation/" rel="nofollow" title="event delegation">event delegation</a> <em>(trapping the event on an ancestor/parent and delegating the reaction to the <code>event.target</code>)</em>, or coding a singular general function to deal with your elements in a relative way, most often relative to <code>this</code> or <code>$(this)</code>.</p></li>
<li><p>When needing to create many event handlers, it is usually best to store those event listeners as named functions so you can remove them again when you are finished. This would mean avoiding using anonymous functions as you are doing. However, if you know that it is only your code dealing with the DOM, you can fallback to using <code>$(elements).unbind('click')</code> to remove all click handlers <em>(anonymous or not)</em> applied using jQuery to the selected elements. If you do use this latter method however, it is definitely better to use jQuery's event namespacing ability - so that you know you are only removing your events. i.e. <code>$(elements).unbind('click.my_app');</code>. This obviously means you do have to bind the events using <code>$(elements).bind('click.my_app', function(){...});</code></p></li>
</ol>
<h3>being more specific:</h3>
<p>auto calling an anonymous function</p>
<pre><code>(function(){
/*
running an anonymous function this way will never cause a memory
leak because memory leaks (at least the ones we have control over)
require a variable reference getting caught in memory with the
JavaScript runtime still believing that the variable is in use,
when it isn't - meaning that it never gets garbage collected.
This construction has nothing to reference it, and so will be
forgotten the second it has been evaluated.
*/
})();
</code></pre>
<p>adding an anonymous event listener with jQuery:</p>
<pre><code>var really_large_variable = {/*Imagine lots of data here*/};
$(element).click(function(){
/*
Whilst I will admit not having investigated to see how jQuery
handles its event listeners onunload, I doubt if it is auto-
matically unbinding them. This is because for most code they
wont cause a problem, especially if only a few are in use. For
larger projects though it is a good idea to create some beforeunload
or unload handlers that delete data and unbind any event handling.
The reason for this is not to protect against the reference of the
function itself, but to make sure the references the function keeps
alive are removed. This is all down to how JS scope works, if you
have never read up on JavaScript scope... I suggest you do so.
As an example however, this anonymous function has access to the
`really_large_variable` above - and will prevent any garbage collection
system from deleting the data contained in `really_large_variable`
even if this function or any other code never makes use of it.
When the page unloads you would hope that the browser would be able
to know to clear the memory involved, but you can't be 100% certain
it will *(especially the likes of IE6/7)* - so it is always best
to either make sure you set the contents of `really_large_variable` to null
or make sure you remove your references to your closures/event listeners.
*/
});
</code></pre>
<h3>tearDowns and deconstruction</h3>
<p>I've focused - with regard to my explanations - on when the page is no longer required and the user is navigating away. However the above becomes even more relevant in today's world of ajaxed content and highly dynamic interfaces; GUIs that are constantly creating and trashing elements.</p>
<p>If you are creating a dynamic javascript app, I cannot stress how important it is to have constructors with <code>.tearDown</code> or <code>.deconstruct</code> methods that are executed when the code is no longer required. These should step through large custom object constructs and nullify their content, as well as removing event listeners and elements that have been dynamically created and are no longer of use. You should also use jQuery's <code>empty</code> method before replacing an element's content - this can be better explained in their words:</p>
<p><a href="http://api.jquery.com/empty/" rel="nofollow">http://api.jquery.com/empty/</a></p>
<blockquote>
<p>To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.</p>
<p>If you want to remove elements without destroying their data or event handlers (so they can be re-added later), use .detach() instead.</p>
</blockquote>
<p>Not only does coding with tearDown methods force you to do so more tidily <em>(i.e. making sure you to keep related code, events and elements namespaced together)</em>, it generally means you build code in a more modular fashion; which is obviously far better for future-proofing your app, for read-ability, and for anyone else who may take over your project at a later date.</p> |
13,180,293 | AngularJS multiple uses of Controller and rootScope | <p>I want to use a controller on 2 seperated HTML elements, and use the $rootScope to keep the 2 lists in sync when one is edited:</p>
<p><strong>HTML</strong></p>
<pre><code><ul class="nav" ng-controller="Menu">
<li ng-repeat="item in menu">
<a href="{{item.href}}">{{item.title}}</a>
</li>
</ul>
<div ng-controller="Menu">
<input type="text" id="newItem" value="" />
<input type="submit" ng-click="addItem()" />
<ul class="nav" ng-controller="Menu">
<li ng-repeat="item in menu">
<a href="{{item.href}}">{{item.title}}</a>
</li>
</ul>
</div>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>angular.module('menuApp', ['menuServices']).
run(function($rootScope){
$rootScope.menu = [];
});
angular.module('menuServices', ['ngResource']).
factory('MenuData', function ($resource) {
return $resource(
'/tool/menu.cfc',
{
returnFormat: 'json'
},
{
getMenu: {
method: 'GET',
params: {method: 'getMenu'}
},
addItem: {
method: 'GET',
params: {method: 'addItem'}
}
}
);
});
function Menu($scope, MenuData) {
// attempt to add new item
$scope.addNewItem = function(){
var thisItem = $('#newItem').val();
MenuData.addItem({item: thisItem},function(data){
$scope.updateMenu();
});
}
$scope.updateMenu = function() {
MenuData.getMenu({},function(data){
$scope.menu = data.MENU;
});
}
// get menu data
$scope.updateMenu();
}
</code></pre>
<p>When the page loads, both the <code>UL</code> and the <code>DIV</code> display the correct contents from the database, but when i use the <code>addNewItem()</code> method only the <code>DIV</code> gets updated.</p>
<p>Is there a better way to structure my logic, or can I do something to make sure the <code>$scope.menu</code> in the <code>UL</code> gets updated at the same time?</p>
<p>Here's an example of something similar: <a href="http://plnkr.co/edit/2a55gq">http://plnkr.co/edit/2a55gq</a></p> | 13,181,133 | 3 | 3 | null | 2012-11-01 15:28:47.597 UTC | 23 | 2014-04-15 06:34:42.44 UTC | 2013-05-10 08:57:37.283 UTC | null | 629,685 | null | 884,842 | null | 1 | 19 | javascript|data-binding|controller|angularjs | 45,309 | <p>I would suggest to use a service that holds the menu and its methods. The service will update the menu which is referenced by the controller(s).</p>
<p>See a working plunker here: <a href="http://plnkr.co/edit/Bzjruq" rel="noreferrer">http://plnkr.co/edit/Bzjruq</a></p>
<p>This is the sample JavaScript code:</p>
<pre><code>angular
.module( 'sampleApp', [] )
.service( 'MenuService', [ '$rootScope', function( $rootScope ) {
return {
menu: [ 'item 1' ],
add: function( item ) {
this.menu.push( item );
}
};
}])
.controller( 'ControllerA', [ 'MenuService', '$scope', function( MenuService, $scope ) {
$scope.menu = MenuService.menu;
$scope.addItem = function() {
MenuService.add( $scope.newItem );
};
}]);
</code></pre>
<p>And the sample Html page:</p>
<pre><code><!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="sampleApp">
<div ng-controller="ControllerA">
<ul>
<li ng-repeat="item in menu">{{item}}</li>
</ul>
<input type="text" ng-model="newItem" /><input type="submit" ng-click="addItem()" />
</div>
<div ng-controller="ControllerA">
<ul>
<li ng-repeat="item in menu">{{item}}</li>
</ul>
</div>
</body>
</html>
</code></pre> |
13,054,950 | Can Nexus or Artifactory store simple tar.gz artifacts? | <p>I have cloud servers located in separate data centers across the world. Each data center is separate from the others.</p>
<p>I'm looking for an easy way to deploy artifacts to individual clusters of servers (that may be running different versions of software i.e. a dev, test, and production cluster) in each of these regions with ease and consistency. It seems to me that an artifact server is what I need because I could execute an install script on the cloud server, which pulls down the correct software artifact.</p>
<p>Now, I work on the operations side. I don't care about doing builds, or managing software build dependencies. I simply want an artifact server where I can store all the different versions of my packages for access at a later time. The kicker, is that I have several different types of artifacts to store.</p>
<ul>
<li>Shell scripts</li>
<li>Python scripts</li>
<li>Puppet manifests</li>
<li>Debian files (often delivered as a tar.gz file of multiple debians)</li>
</ul>
<p>Can Nexus or Artifactory manage all of these types of packages, or should I be looking in a different direction? I'm not opposed to adding make files to my shell script projects that simply generate tar.gz files. I just don't want to go down the path of setting up an artifact repository, when ultimately, a little scripting, wget, and an apache server would work just fine.</p> | 13,082,709 | 5 | 0 | null | 2012-10-24 17:54:51.25 UTC | 3 | 2021-01-15 16:03:38.91 UTC | 2012-10-24 18:09:01.803 UTC | null | 1,255,551 | null | 592,965 | null | 1 | 32 | deployment|nexus|artifactory|artifacts | 32,591 | <p><strong>Both Artifactory</strong> and <strong>Nexus</strong> can handle any type of file, as they both are <strong>"Binary Repository Managers"</strong>.</p>
<p>Albeit that, Nexus can technically store any file, but lacks support for binaries that do not adhere to the Maven repository layout. For example, such files will not be indexed and cannot be retrieved in searches; Also, if non-Maven artifacts encumber module information in their path, then currently Artifactory is the only repository that can make use of that and allow version based operations on artifacts (e.g., download latest version query)</p>
<p>Although both of these tools have started out by solving a problem in the <a href="http://maven.apache.org/" rel="noreferrer">Maven</a> world, the need for smart binary management has been recognized in many other fields, <a href="http://wiki.jfrog.org/confluence/display/RTF/YUM+Repositories" rel="noreferrer"><em>operations included</em></a>.</p>
<p>Binaries do need a specialized manager, and although <strong>network shares/SCM/file servers</strong> seem like a viable option in the beginning; they just <strong>don't scale</strong>.</p>
<p>Also see <a href="https://stackoverflow.com/questions/11513360/is-it-good-idea-to-store-python-package-eggs-in-artifactory/11516508#11516508">my answer to a similar question</a> for some of the benefits of a manager over the other ad-hoc solutions.</p> |
13,216,092 | How to sort a hash by value in descending order and output a hash in ruby? | <pre><code>output.sort_by {|k, v| v}.reverse
</code></pre>
<p>and for keys</p>
<pre><code>h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
=> {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
Hash[h.sort]
</code></pre>
<p>Right now I have these two. But I'm trying to sort hash in descending order by value so that it will return</p>
<pre><code>=> {"d"=>4, "c"=>3, "b"=>2, "a"=>1 }
</code></pre>
<p>Thanks in advance.</p>
<p>Edit:
let me post the whole code.</p>
<pre><code>def count_words(str)
output = Hash.new(0)
sentence = str.gsub(/,/, "").gsub(/'/,"").gsub(/-/, "").downcase
words = sentence.split()
words.each do |item|
output[item] += 1
end
puts Hash[output.sort_by{ |_, v| -v }]
return Hash[output.sort_by{|k, v| v}.reverse]
end
</code></pre> | 13,216,103 | 2 | 1 | null | 2012-11-04 04:30:06.043 UTC | 14 | 2012-11-04 04:59:29.07 UTC | 2012-11-04 04:59:29.07 UTC | null | 445,345 | null | 445,345 | null | 1 | 41 | ruby-on-rails|ruby|sorting|hash | 42,060 | <p>Try:</p>
<pre><code>Hash[h.sort.reverse]
</code></pre>
<p>This should return what you want. </p>
<p><strong>Edit:</strong></p>
<p>To do it by value:</p>
<pre><code>Hash[h.sort_by{|k, v| v}.reverse]
</code></pre> |
17,013,227 | Select only rows if its value in a particular column is 'NA' in R | <p>I'm trying to create a subset of data that contains only the rows with missing data in one of my columns.</p>
<p>The data:</p>
<pre><code>data<-structure(list(ID = c(1, 2, 3, 4, 7, 9, 10, 12, 13, 14, 15, 16,
17, 18, 20, 21, 22, 23, 24, 25, 27, 28, 29, 31, 34, 37, 38, 39,
40, 41), QnSinV1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L), QnSinV2 = c(1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L), QnSinV3 = c(0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), QnSize = c(0.032140423, 0.017620319,
NA, -0.093448167, -0.051090375, 0.001188913, NA, -0.144868599,
-0.000260992, 0.008502255, -0.00346349, 0.017208373, 0.004301855,
0.004420431, -0.007564124, NA, 0.174388101, -0.142412328, 0.064935852,
-0.052174354, NA, 0.005180317, 0.05728222, 0.041215822, -0.002449455,
-0.040942923, -0.082284946, -0.173656321, 0.022723036, -0.061326436
), QnWt = c(15.8, 16.5, 11.9, 13.7, 15, 15.3, 13.7, 15.8, 16.3,
15.9, 15.1, 14.5, 14.4, 15.7, 14.4, 13.3, 14.8, 15.1, 15.1, 14.7,
15.8, 17.8, 16.4, 13.4, 15.1, 14.8, 14.2, 12.7, 17.9, 16.2),
QnWtLsCL = c(NA, 0.503030303, 0.596638655, NA, 0.446666667,
0.509803922, 0.408759124, 0.462025316, 0.552147239, 0.509433962,
0.456953642, 0.455172414, 0.506944444, NA, 0.486111111, 0.473684211,
0.513513514, 0.516556291, 0.582781457, 0.537414966, 0.474683544,
0.43258427, 0.432926829, NA, 0.569536424, 0.445945946, 0.485915493,
0.543307087, NA, 0.543209877), ClaustPer = c(NA, 1L, 2L,
NA, 3L, 0L, 2L, 0L, 1L, 0L, 0L, 0L, 1L, NA, 0L, 7L, 1L, 0L,
1L, 0L, 1L, 2L, 2L, NA, 2L, 3L, 2L, 2L, NA, 0L), QnSurvCL = c(0L,
1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L),
ColWtCL = c(NA, 11.7, 7.3, NA, 9.1, 11.1, 9.6, 11.2, 9, 11.2,
12, 11, 10.9, NA, 9.9, 8.6, 10.8, 10.9, 8.7, 10.8, 11.6,
13.7, 10.8, NA, 9.3, 9.6, 9.8, 8.7, NA, 11.1), ColWtCL_6 = c(NA,
57.1, 45, NA, 73.6, NA, NA, NA, 43.8, NA, NA, 71.1, NA, NA,
53.7, NA, 84.4, NA, NA, NA, 56, 56.1, NA, NA, 59.4, NA, 45.7,
NA, NA, NA), ColGrowthCL_6 = c(NA, 4.88034188, 6.164383562,
NA, 8.087912088, NA, NA, NA, 4.866666667, NA, NA, 6.463636364,
NA, NA, 5.424242424, NA, 7.814814815, NA, NA, NA, 4.827586207,
4.094890511, NA, NA, 6.387096774, NA, 4.663265306, NA, NA,
NA), QnSurvCL_6 = c(NA, 1L, NA, NA, 1L, NA, NA, NA, 1L, NA,
NA, 1L, NA, NA, 1L, 0L, 1L, NA, NA, NA, 1L, 1L, NA, NA, 1L,
NA, 1L, NA, NA, NA), IR = c(-0.1919695, 0.0214441, NA, 0.0886954,
0.4221713, 0.0869788, 0.2716466, 0.0289674, -0.0291414, -0.1739616,
-0.0215773, -0.1473209, 0.0370336, 0.254584, 0.0332632, -0.0203844,
0.1524175, -0.051451, -0.0612144, 0.1617955, 0.0354173, 0.0904954,
0.3344705, 0.0990583, 0.1985931, 0.0419539, -0.0159598, 0.1159526,
-0.0057495, -0.1811458), SH = c(1.2064, 1.1093, NA, 0.922,
0.643, 0.9284, 0.7225, 0.9866, 1.0804, 1.2226, 1.0315, 1.1953,
1.007, 0.6991, 1.0264, 1.0265, 0.8865, 1.1184, 1.094, 0.829,
1.0142, 0.9824, 0.6793, 0.9188, 0.7853, 1.0352, 1.0648, 0.9654,
1.0366, 1.2044), HL = c(0.3774, 0.4349, NA, 0.5091, 0.6187,
0.5168, 0.6405, 0.4691, 0.4555, 0.3444, 0.4908, 0.3819, 0.4846,
0.6256, 0.4638, 0.4778, 0.5219, 0.433, 0.447, 0.564, 0.4899,
0.4612, 0.6542, 0.5162, 0.5549, 0.4928, 0.4471, 0.4959, 0.4523,
0.3511), MLH = c(0.534090909090909, 0.5, NA, 0.40506329113924,
0.298507462686567, 0.410958904109589, 0.293103448275862,
0.442105263157895, 0.48, 0.554347826086957, 0.453488372093023,
0.535353535353535, 0.443298969072165, 0.304878048780488,
0.457446808510638, 0.455555555555556, 0.397849462365591,
0.494252873563218, 0.48314606741573, 0.377777777777778, 0.457446808510638,
0.445652173913043, 0.3, 0.412371134020619, 0.354838709677419,
0.464646464646465, 0.474226804123711, 0.43010752688172, 0.46078431372549,
0.541666666666667)), .Names = c("ID", "QnSinV1", "QnSinV2",
"QnSinV3", "QnSize", "QnWt", "QnWtLsCL", "ClaustPer", "QnSurvCL",
"ColWtCL", "ColWtCL_6", "ColGrowthCL_6", "QnSurvCL_6", "IR",
"SH", "HL", "MLH"), row.names = c(1L, 2L, 3L, 4L, 7L, 9L, 10L,
12L, 13L, 14L, 15L, 16L, 17L, 18L, 20L, 21L, 22L, 23L, 24L, 25L,
27L, 28L, 29L, 31L, 34L, 37L, 38L, 39L, 40L, 41L), class = "data.frame")
</code></pre>
<p>My guess (which doesn't work):</p>
<pre><code>test<-subset(data, data$ColWtCL_6=='NA')
test
</code></pre> | 17,013,250 | 3 | 0 | null | 2013-06-09 19:17:41.887 UTC | 8 | 2021-12-31 06:23:19.067 UTC | 2021-12-31 06:23:19.067 UTC | null | 15,293,191 | null | 1,009,215 | null | 1 | 14 | r | 64,738 | <p>You can do it also without <code>subset()</code>. To select NA values you should use function <code>is.na()</code>.</p>
<pre><code>data[is.na(data$ColWtCL_6),]
</code></pre>
<p>Or with <code>subset()</code></p>
<pre><code>subset(data,is.na(ColWtCL_6))
</code></pre> |
16,856,650 | Android Studio failed to open by giving error "Files Locked" | <p>After running once successfully, Android Studio is getting failed to open.
The error is:</p>
<blockquote>
<p>Files in C:\Program Files (x86)\Android\android-studio\system\caches are locked. Android Studio will not be able to start.</p>
</blockquote>
<p>Did any one find its solution?</p> | 17,019,393 | 7 | 2 | null | 2013-05-31 11:51:28.93 UTC | 6 | 2019-12-05 06:27:26.037 UTC | null | null | null | null | 1,927,210 | null | 1 | 64 | android-studio | 25,438 | <p>Solved in Windows 7:</p>
<ol>
<li><p>Go to folder where android-studio is installed. (e.g. <code>C:\Program Files (x86)\Android\android-studio</code>)</p></li>
<li><p>Now go up one folder. (i.e. <code>C:\Program Files (x86)\Android</code>)</p></li>
<li><p>Right click on the <code>android-studio</code> folder and go to <strong>Properties</strong>.</p></li>
<li><p>In the <strong>Properties</strong> window, go to the <strong>Security</strong> tab.</p></li>
<li><p>Click the <strong>Edit</strong> button.</p></li>
<li><p>A new window will open, here you click the <strong>Users</strong> (your-username-or-your-group-name)</p></li>
<li><p>From the list below, check <strong>Allow</strong> in front of <strong>Full control</strong>.</p></li>
<li><p>Press <strong>OK</strong>, then again <strong>OK</strong>.</p></li>
</ol>
<p>Now you can use Android Studio easily instead of "Running it As Administrator" every time.</p> |
20,393,093 | How to get the ajax response from success and assign it in a variable using jQuery? | <p>Hello guys I have a problem in getting the response from my ajax. If I display it in the console. I can view it. But How do I assign it in a variable?</p>
<p>Here's what I have.
In my PHP code I have this</p>
<pre><code>public function checkPassword($password){
$username = $this->session->userdata('username');
$validate = $this->members_model->checkPassword($password,$username);
echo $validate;
}
</code></pre>
<p>In my jquery I have this</p>
<pre><code>$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var g = response;
if(g == 1){
$('#existing_info').html('Password is VALID'); //Doesn't display the VALID if the response is 1. Why?
}else{
$('#existing_info').html('Password is INVALID!');
}
}
});
});
</code></pre> | 20,393,170 | 10 | 7 | null | 2013-12-05 06:32:25.777 UTC | 1 | 2018-06-08 12:21:33.413 UTC | 2013-12-05 06:40:46.093 UTC | null | 2,706,036 | null | 2,706,036 | null | 1 | 2 | javascript|php|jquery|ajax | 42,900 | <pre><code>$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var k=response;
if(k.indexOf("1") != -1)
$('#existing_info').html('Password is VALID');
else
$('#existing_info').html('Password is INVALID!');
}
});
</code></pre>
<p><code>response</code> is in response variable of success function.</p>
<p><strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf" rel="nofollow">indexof</a></strong> returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex,
<strong>returns -1 if the value is not found</strong>.</p> |
51,053,280 | Modifying a global variable in a constexpr function in C++17 | <p>In C++17, are you allowed to modify global variables in a <code>constexpr</code> function?</p>
<pre><code>#include <iostream>
int global = 0;
constexpr int Foo(bool arg) {
if (arg) {
return 1;
}
return global++;
}
int main() {
std::cout << global;
Foo(true);
std::cout << global;
Foo(false);
std::cout << global;
}
</code></pre>
<p>I wouldn't expect you to be able to, but clang 6 allows it: <a href="https://godbolt.org/g/UB8iK2" rel="noreferrer">https://godbolt.org/g/UB8iK2</a></p>
<p>GCC, however, doesn't: <a href="https://godbolt.org/g/ykAJMA" rel="noreferrer">https://godbolt.org/g/ykAJMA</a></p>
<p>Which compiler is correct?</p> | 51,053,445 | 2 | 6 | null | 2018-06-27 01:19:05.59 UTC | 5 | 2018-06-28 00:29:47.013 UTC | 2018-06-28 00:29:47.013 UTC | null | 963,864 | null | 595,605 | null | 1 | 36 | c++|language-lawyer|c++17|constexpr | 2,732 | <blockquote>
<p>Which compiler is correct?</p>
</blockquote>
<p>Clang is right.</p>
<p>The definition of a <code>constexpr</code> function as per <a href="https://timsong-cpp.github.io/cppwp/dcl.constexpr#3" rel="noreferrer">dcl.constexpr/3</a></p>
<blockquote>
<p>The definition of a <code>constexpr</code> function shall satisfy the following
requirements:<br><br>
(3.1) its return type shall be a literal type;<br>
(3.2) each of its parameter types shall be a literal type;<br>
(3.3) its function-body shall be <code>= delete</code>, <code>= default</code>, or a compound-statement
that does <strong>not</strong> contain:<br><br>
(3.3.1) an asm-definition,<br>
(3.3.2) a goto statement,<br>
(3.3.3) an identifier label,<br>
(3.3.4) a try-block, or<br>
(3.3.5) a <em>definition</em> of a variable of non-literal type or of <em>static</em> or
thread storage duration or for which no initialization is performed.</p>
</blockquote>
<p>Also as per <a href="https://timsong-cpp.github.io/cppwp/dcl.constexpr#5" rel="noreferrer">dcl.constexpr/5</a>:</p>
<blockquote>
<p>For a <code>constexpr</code> function or constexpr constructor that is neither
defaulted nor a template, if <em>no argument values exist</em> such that an
invocation of the function or constructor <strong>could be</strong> an evaluated
subexpression of a core constant expression,</p>
</blockquote>
<p><code>Foo(true)</code> could be evaluated to a <em>core constant expression</em> (i.e <code>1</code>).<br></p>
<p>Also, <code>Foo(false)</code> <em>could be</em> but is not required to be constant evaluated.</p>
<p><strong>CONCLUSION</strong></p>
<p>Thus, a <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86327" rel="noreferrer">bug</a> in GCC.</p>
<p><hr>
Many thanks to @Barry, @aschepler and @BenVoigt for helping me with this answer.</p> |
57,856,561 | How to check when my widget screen comes to visibility in flutter like onResume in Android | <p>In android if an activity is visible <code>onResume</code> is called. What is the equivalent method of <code>onResume</code> in <strong>Flutter</strong>? </p>
<p>I need the know when my widget screen is visible so I can auto-play a video based on that. I might go to another widget screen an when I come back it should auto-play. </p>
<p>My approach was to play the video in <code>didUpdateWidget</code> but <code>didUpdateWidget</code> is called every-time even the widget screen is not visible. </p>
<p><strong>Note:</strong> I'm not asking about <code>didChangeAppLifecycleState</code> from <code>WidgetsBindingObserver</code> as it gives <code>onResume</code> etc callbacks for the app lifecycle not a particular widget screen. </p> | 58,504,433 | 5 | 4 | null | 2019-09-09 14:57:08.307 UTC | 10 | 2022-03-18 17:42:50.907 UTC | 2019-12-28 07:40:51.627 UTC | null | 4,768,512 | null | 4,768,512 | null | 1 | 50 | android|flutter | 27,559 | <p>All of the problems are solved.</p>
<p>Put an observer on the navigator from the root of the widget tree (materialappwidget).</p>
<p>If you need more explanation please follow this link:
<a href="https://api.flutter.dev/flutter/widgets/RouteObserver-class.html" rel="noreferrer">https://api.flutter.dev/flutter/widgets/RouteObserver-class.html</a></p>
<p>I have implemented in my project and its working great @Sp4Rx</p>
<pre><code>// Register the RouteObserver as a navigation observer.
final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
void main() {
runApp(MaterialApp(
home: Container(),
navigatorObservers: [routeObserver],
));
}
class RouteAwareWidget extends StatefulWidget {
State<RouteAwareWidget> createState() => RouteAwareWidgetState();
}
// Implement RouteAware in a widget's state and subscribe it to
// the
// RouteObserver.
class RouteAwareWidgetState extends State<RouteAwareWidget> with RouteAware {
@override
void didChangeDependencies() {
super.didChangeDependencies();
routeObserver.subscribe(this, ModalRoute.of(context));
}
@override
void dispose() {
routeObserver.unsubscribe(this);
super.dispose();
}
@override
void didPush() {
// Route was pushed onto navigator and is now topmost route.
}
@override
void didPopNext() {
// Covering route was popped off the navigator.
}
@override
Widget build(BuildContext context) => Container();
}
</code></pre> |
58,128,248 | How can I resolve the error "URL scheme must be "http" or "https" for CORS request." for this code | <p>It shows below message in the <code>console</code>.</p>
<blockquote>
<p>sandbox.js:1 Fetch API cannot load
file:///C:/Users/Lizzi/Desktop/novice%20to%20ninja/todos/luigi.json.
URL scheme must be "http" or "https" for CORS request </p>
</blockquote>
<p>I'm new to <code>aynchronouse</code> programming but I have read up on <code>CORS</code> solutions and tried things like getting a chrome extension and disabling web security for my google chrome but it still doesn't work.</p>
<pre><code>fetch('todos/luigi.json').then((response)=>{
console.log('resolved',response);
}).catch((err)=>{
console.log('rejected', err);
});
</code></pre> | 58,129,062 | 1 | 6 | null | 2019-09-27 05:16:01.39 UTC | 5 | 2019-09-27 06:36:07.56 UTC | 2019-09-27 05:37:00.753 UTC | null | 9,763,011 | null | 9,035,071 | null | 1 | 22 | javascript|promise|fetch | 84,501 | <p>You need to be serving your index.html locally or have your site hosted on a live server somewhere for the Fetch API to work properly. The files need to be served using the http or https protocols.</p>
<p>If you just clicked on your index.html from your file explorer than your browser is grabbing those files directly from your file system. This is why the error is showing you an absolute path from the root folder on you computer. </p>
<p>Try installing one of these...
- npm serve
- Live server (an extension for Visual Studio Code if you are using that)</p>
<p>Or whatever server that will work with your environment.</p>
<p>Should work fine once you spin up a server :) happy coding!</p> |
4,294,752 | Using a string as the argument to a Django filter query | <p>I'm trying to do a django query, but with the possibility of several different <code>WHERE</code> parameters. So I was thinking of doing something like:</p>
<pre><code>querystring = "subcat__id__in=[1,3,5]"
Listing.objects.filter(querystring)
</code></pre>
<p>Here Listing is defined in my model, and it contains the Many-To-Many field <code>subcat</code>. However, that raises a <code>ValueError</code> because filter doesn't accept a string as its argument. Is there a way in Python to have a string evaluated as just its contents rather than as a string? Something like a print statement that prints the value of the string inline rather than to the standard output.</p>
<p>By the way, the reason I don't just do </p>
<pre><code>querystring = [1,3,5]
Listing.objects.filter(subcat__id__in=querystring)
</code></pre>
<p>is that I'm not always filtering for <code>subcat__id</code>, sometimes it's one or several other parameters, and I'd rather not have to write out a bunch of separate queries controlled by if statements. Any advice is much appreciated.</p> | 4,294,771 | 2 | 0 | null | 2010-11-28 00:53:09.5 UTC | 9 | 2018-05-25 11:36:38.113 UTC | 2018-05-25 11:36:38.113 UTC | null | 9,663,023 | null | 480,815 | null | 1 | 29 | django|django-queryset | 13,958 | <p>Perhaps...</p>
<pre><code>filter_dict = {'subcat__id__in': [1,3,5]}
Listing.objects.filter(**filter_dict)
</code></pre> |
4,161,662 | How do I describe an Action<T> delegate that returns a value (non-void)? | <p>The <code>Action<T></code> delegate return void. Is there any other built-in delegate which returns non void value?</p> | 4,161,690 | 2 | 0 | null | 2010-11-12 04:39:49.143 UTC | 8 | 2010-11-12 04:51:53.68 UTC | 2010-11-12 04:51:53.68 UTC | null | 414,076 | null | 496,949 | null | 1 | 42 | c#|.net|delegates | 37,478 | <p>Yes. <code>Func<></code> returns the type specified as the final generic type parameter, such that <code>Func<int></code> returns an <code>int</code> and <code>Func<int, string></code> accepts an integer and returns a string. Examples:</p>
<pre><code>Func<int> getOne = () => 1;
Func<int, string> convertIntToString = i => i.ToString();
Action<string> printToScreen = s => Console.WriteLine(s);
// use them
printToScreen(convertIntToString(getOne()));
</code></pre> |
4,095,696 | Mercurial .hgignore for Visual Studio 2010 projects | <p>Not to be confused with <a href="https://stackoverflow.com/questions/34784/mercurial-hgignore-for-visual-studio-2008-projects">Mercurial .hgignore for Visual Studio 2008 projects</a></p>
<p>I was asking whether if that same file can be reused for Visual Studio 2010, or some other extensions, etc should be added to it, & why?</p> | 4,095,783 | 2 | 0 | null | 2010-11-04 10:26:13.51 UTC | 58 | 2013-08-21 07:05:58.207 UTC | 2017-05-23 12:05:59.473 UTC | null | -1 | null | 406,464 | null | 1 | 119 | visual-studio-2010|visual-studio|mercurial|hgignore | 14,767 | <p>The new things are related to MSTest stuff. This is the one that I use:</p>
<pre><code># use glob syntax
syntax: glob
*.obj
*.pdb
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.scc
*.DotSettings
[Bb]in
[Dd]ebug*/**
obj/
[Rr]elease*/**
_ReSharper*/**
NDependOut/**
packages/**
[Tt]humbs.db
[Tt]est[Rr]esult*
[Bb]uild[Ll]og.*
*.[Pp]ublish.xml
*.resharper
*.ncrunch*
*.ndproj
</code></pre> |
26,459,911 | --resource-rules has been deprecated in mac os x >= 10.10 | <p>I tried to resign my ipa file with new provisioning profile on Mac Os 10.10 with iResign app but I got this warning: "Warning: --resource-rules has been deprecated in Mac OS X >= 10.10". </p>
<p>What should I do now? </p> | 26,678,311 | 8 | 4 | null | 2014-10-20 06:49:07.513 UTC | 19 | 2018-09-14 12:44:39.533 UTC | 2017-03-17 21:34:17.067 UTC | null | 5,115,977 | null | 1,468,082 | null | 1 | 69 | ios|iphone|code-signing|ipa|osx-yosemite | 30,372 | <p>I found <strong>workaround</strong>: if you run the iResign app from XCode — then you will resign app without problem (warning will appears in console instead of popup).
But if you close XCode and run app alone — then popup will back to you!</p>
<p>BTW: bug found :)
The condition</p>
<pre><code>if (systemVersionFloat < 10.9f)
</code></pre>
<p>Is broken for Yosemite 10.10. Funny.</p>
<p>Thanks,</p> |
9,847,843 | Looking for example code to implement a SNMP table using AgentX | <p>I've written an AgentX app (Linux, gcc, g++) which works well at sending back scalers. Here is what I'm doing now:</p>
<pre><code>init_agent( "blah" );
netsnmp_register_read_only_scalar( netsnmp_create_handler_registration( "foo1", handle_foo1, oid, oid.size(), HANDLER_CAN_RONLY ) );
init_snmp( "blah" );
while ( true )
{
// internal stuff
agent_check_and_process(1); // where 1==block
}
</code></pre>
<p>The functions like <code>handle_foo1(...)</code> call <code>snmp_set_var_typed_value(...)</code> to return the values which are cached in a global C struct within the application.</p>
<p>What I'm trying to do now is modify this code to also support a SNMP table. The content of the table is stored/cached as a STL container within the application. This is a relatively simple SNMP table, with consecutive rows, and all columns are composed of types like Integer32, Gauge32, InetAddress, and TruthValue. The problem is I don't see great code examples on the net-snmp web site, just a lot of doxygen pages.</p>
<p><em><strong>My question:</em></strong></p>
<p>What API should I be looking at? Are these the right calls:</p>
<pre><code>netsnmp_register_read_only_table_data();
netsnmp_create_table_data();
netsnmp_create_table_data_row();
netsnmp_table_data_add_row();
</code></pre>
<p>...or is there something simpler I should be using?</p> | 10,038,553 | 1 | 1 | null | 2012-03-23 23:43:47.573 UTC | 12 | 2013-12-10 11:03:28.67 UTC | null | null | null | null | 13,022 | null | 1 | 8 | c++|c|snmp|net-snmp | 18,248 | <p>I think the biggest pain when it comes to net-snmp is all those Doxygen pages the Google indexes but which provides near-zero usable content. Reading the <code>.h</code> files is probably already obvious to most developers, and the truth is that net-snmp provides many different layers of APIs with very little documentation I found useful. What we need isn't several dozen identical copies of web sites hosting Doxygen, but instead some good examples.</p>
<p>In the end, the mib2c tool is how I got enough example code to get the whole thing working. I think I tried running mib2c with every single net-snmp <code>.conf</code> file, and spent a lot of time reading the code it generated to get a better understanding. Here are the ones I found gave me the best hints:</p>
<ul>
<li>mib2c -c mib2c.create-dataset.conf MyMib</li>
<li>mib2c -c mib2c.table_data.conf MyMib</li>
</ul>
<p>The <code>.conf</code> files are here: <code>/etc/snmp/mib2c.*</code></p>
<p>Also useful were the following pages:</p>
<ul>
<li>FAQ: <a href="http://www.net-snmp.org/FAQ.html" rel="noreferrer">http://www.net-snmp.org/FAQ.html</a></li>
<li>Example code for tables: <a href="http://www.net-snmp.org/dev/agent/data__set_8c-example.html" rel="noreferrer">http://www.net-snmp.org/dev/agent/data__set_8c-example.html</a></li>
<li>Doxygen pages: <a href="http://www.net-snmp.org/dev/agent/group__library.html" rel="noreferrer">http://www.net-snmp.org/dev/agent/group__library.html</a></li>
</ul>
<p>From what I understand, there are many helpers/layers available in the net-snmp API. So this example pseudocode may not work for everyone, but this is how I personally got my tables to work using net-snmp v5.4:</p>
<p><strong><em>Variable needed across several functions (make it global, or a member of a struct?)</em></strong></p>
<pre><code>netsnmp_tdata *table = NULL;
</code></pre>
<p><strong><em>Structure to represent one row of the table (must match the MIB definition)</em></strong></p>
<pre><code>struct MyTable_entry
{
long myTableIndex;
...insert one line here for each column of the table...
int valid; // add this one to the end
}
</code></pre>
<p><strong><em>Initialize the table with snmpd</em></strong></p>
<pre><code>std::string name( "name_of_the_table_from_mib" );
table = netsnmp_tdata_create_table( name.c_str(), 0 );
netsnmp_table_registration_info *table_info = SNMP_MALLOC_TYPEDEF( netsnmp_table_registration_info );
netsnmp_table_helper_add_indexes( table_info, ASN_INTEGER, 0 ); // index: myTableIndex
// specify the number of columns in the table (exclude the index which was already added)
table_info->min_column = COLUMN_BLAH;
table_info->max_column = MAX_COLUMN_INDEX;
netsnmp_handler_registration *reg = netsnmp_create_handler_registration( name.c_str(), MyTable_handler, oid, oid.size(), HANDLER_CAN_RONLY );
netsnmp_tdata_register( reg, table, table_info );
</code></pre>
<p><strong><em>Handler to process requests</em></strong></p>
<pre><code>int myTable_handler( netsnmp_mib_handler *handler, netsnmp_handler_registration *reginfo, netsnmp_agent_request_info *reqinfo, netsnmp_request_info *requests )
{
if ( reqInfo->mode != MODE_GET ) return SNMP_ERR_NOERROR;
for ( netsnmp_request_info *request = requests; request; request = request->next )
{
MyTable_entry *table_entry = (MyTable_entry*)netsnmp_tdata_extract_entry( request );
netsnmp_table_request_info *table_info = netsnmp_extract_table_info( request );
if ( table_entry == NULL ) { netsnmp_set_request_error( reqinfo, request, SNMP_NOSUCHINSTANCE); continue; }
switch ( table_info->colnum )
{
// ...this is similar to non-table situations, eg:
case COLUMN_BLAH:
snmp_set_var_typed_integer( request->requestvb, ASN_INTEGER, table_entry->blah ); break;
// ...
default: netsnmp_set_request_error( reqinfo, request, SNMP_NOSUCHOBJECT );
}
}
return SNMP_ERR_NOERROR;
}
</code></pre>
<p><strong><em>Building/adding rows to the table</em></strong></p>
<pre><code>if ( table == NULL ) return; // remember our "global" variable named "table"?
// start by deleting all of the existing rows
while ( netsnmp_tdata_row_count(table) > 0 )
{
netsnmp_tdata_row *row = netsnmp_tdata_row_first( table );
netsnmp_tdata_remove_and_delete_row( table, row );
}
for ( ...loop through all the data you want to add as rows into the table... )
{
MyTable_entry *entry = SNMP_MALLOC_TYPEDEF( MyTable_entry );
if ( entry == NULL ) ... return;
netsnmp_tdata_row *row = netsnmp_tdata_create_row();
if ( row == NULL ) SNMP_FREE( entry ); .... return;
entry->myTableIndex = 123; // the row index number
// populate the table the way you need
entry->blah = 456;
// ...
// add the data into the row, then add the row to the table
entry->valid = 1;
row->data = entry;
netsnmp_tdata_row_add_index( row, ASN_INTEGER, &(entry->myTableIndex), sizeof(entry->myTableIndex) );
netsnmp_tdata_add_row( table, row );
}
</code></pre>
<p><strong><em>Putting it together</em></strong></p>
<p>In my case, that last function that builds the rows is triggered periodically by some other events in the system. So every once in a while when new stats are available, the table is rebuilt, all old rows are removed, and the new ones are inserted. I didn't bother trying to modify existing rows. Instead, I found it was easier to just rebuild the table from scratch.</p> |
10,121,693 | Decode JSON to NSArray or NSDictionary | <p>I hope to decode the JSON data below:</p>
<pre><code>{
"content":
[
{
"1":"a",
"2":"b",
"3":"c",
"4":"d",
"mark":"yes"
}
]
}
</code></pre>
<p>Not sure if put it in NSArray or NSDictionary</p>
<p>Welcome any comment</p> | 10,121,757 | 5 | 1 | null | 2012-04-12 10:20:48.687 UTC | 4 | 2015-11-09 12:33:11.113 UTC | 2012-04-12 10:26:56.763 UTC | null | 713,558 | null | 262,325 | null | 1 | 12 | objective-c|json | 42,074 | <p>which iOS version are you using? in iOS 5 you have the <code>NSJSONSerialization</code> class to parse JSON data, if you need to target older iOSs or MAC OSX you should use third parties lib such as <code>SBJSON</code>. The string posted will be a NSDictionary with an array with one dictionary. The array will be accessible using the key <code>@"content"</code></p>
<p>In code:</p>
<pre><code>NSString * jsonString = @"blblblblblb";
NSStringEncoding encoding;
NSData * jsonData = [jsonString dataUsingEncoding:encoding];
NSError * error=nil;
NSDictionary * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
</code></pre>
<p>In SWIFT 2.0:<br></p>
<pre><code> let jsonString = "blblblblblb"
let encoding = NSUTF8StringEncoding
let jsonData = jsonString.dataUsingEncoding(encoding)
guard let jData = jsonData else {return}
do {
let parsedData = try NSJSONSerialization.JSONObjectWithData(jData, options: [])
} catch let error {
print("json error: \(error)")
}
</code></pre>
<p>[UPDATE]
The <code>NSJSONSerialization</code> class is also available for 10.7 my comment wasn't correct.</p> |
9,823,140 | multiple mongo update operator in a single statement? | <p>Can i combine $pushAll and $inc in one statement ?</p>
<p>Before combine, this works fine :</p>
<pre><code>db.createCollection("test");
db.test.insert({"name" : "albert", "bugs" : []});
db.test.update({"name":"albert"},
{"$pushAll" : {"bugs" : [{"name":"bug1", "count":1}]}});
db.test.update({"name":"albert"},
{"$inc" : {"bugs.0.count" : 1}});
db.test.update({"name":"albert"},
{"$pushAll" : {"bugs" : [{"name":"bug2", "count":1}]}});
</code></pre>
<p>But when i try combining it like this :</p>
<pre><code>db.createCollection("test");
db.test.insert({"name" : "albert", "bugs" : []});
db.test.update({"name":"albert"},
{"$pushAll" : {"bugs" : [{"name":"bug1", "count":1}]}});
db.test.update({"name":"albert"},
{
"$pushAll" : {"bugs" : [{"name":"bug2", "count":1}]},
"$inc" : {"bugs.0.count" : 1}
}
);
</code></pre>
<p>This error happens :</p>
<pre><code>have conflicting mods in update
</code></pre>
<p>I wonder it is possible to do this, and also, i imagine combining more than just pushAll and inc, but i am not sure whether this is supported or not ?</p>
<hr>
<h2> update march 23, 2012</h2>
<p>I tried multiple $inc on different elements of an array, and it works (although not correctly. quoted from the answer below to clarify why this doensnt work well and what works : <code>The correct way to increment both fields is as follows: > db.test.update({"name":"albert"}, {"$inc" : {"bugs.0.count" : 1, "bugs.1.count" : 1}})</code> :</p>
<pre><code>db.test.update({"name":"albert"},
{
"$inc" : {"bugs.0.count" : 1},
"$inc" : {"bugs.1.count" : 1}
}
);
</code></pre>
<p>And this combination of $set and $inc on different elements of an array also works :</p>
<pre><code>db.test.update({"name":"albert"},
{
"$set" : {"bugs.0.test" : {"name" : "haha"}},
"$inc" : {"bugs.0.count" : 1},
"$inc" : {"bugs.1.count" : 1}
}
);
</code></pre>
<p>But combine any of these with $push or $pushAll, all will go error.</p>
<p>So, my current conclusion is, it is not about multiple operations on multiple elements within the same array which is the problem, but combining these operations with $push or $pushAll that can change the the array is the problem.</p> | 9,825,001 | 1 | 4 | null | 2012-03-22 13:21:54.94 UTC | 9 | 2012-05-02 02:30:29.77 UTC | 2012-05-02 02:30:29.77 UTC | null | 500,451 | null | 500,451 | null | 1 | 22 | mongodb | 28,951 | <p>Multiple updates may be performed on the same document, as long as those updates do not conflict (hence the "have conflicting mods in update" error). </p>
<p>Because "$push" : {"bugs" : [{"name":"bug1", "count":1}]} and "$inc" : {"bugs.0.count" : 1} are both attempting to modify the same portion of the document (namely the "bugs" array), they conflict. </p>
<p>Multiple updates may be combined if each affects a different part of the document:</p>
<p>for example:</p>
<pre><code>> db.test.drop()
true
> db.test.save({ "_id" : 1, "name" : "albert", "bugs" : [ ] })
> db.test.update({"name":"albert"}, {"$pushAll" : {"bugs" : [{"name":"bug1", "count":1}]}, "$inc" : {"increment" : 1}, $set:{"note":"Here is another field."}})
> db.test.find()
{ "_id" : 1, "bugs" : [ { "name" : "bug1", "count" : 1 } ], "increment" : 1, "name" : "albert", "note" : "Here is another field." }
>
</code></pre>
<p>The update contained three different operations ($pushAll, $inc, and $set), but was able to complete successfully, because each operation affected a different part of the document. </p>
<p>I realize this is not exactly what you were hoping to do, but hopefully it will provide you with a little better understanding of how updates work, and perhaps provide some ideas how your updates and/or documents may be restructured to perform the functionality that your application requires. Good luck. </p> |
8,009,379 | how to output a standings table on the fly from a mysql table of football [soccer] results? | <p>I have been trying to find something about this topic and I can't seem to find anything, there were a few questions on here but they didn't work for my particular project. </p>
<p>I asked a similar question about updating the table but its not going to work for what I actually want
here is the list of result.</p>
<pre><code> --------------------------------------------------------
|id | hometeam |goalsfor|goalsagainst| awayteam |
--------------------------------------------------------
| 1 |Inter Milan | 3 | 1 | FC Barcelona |
--------------------------------------------------------
| 2 |FC Barcelona | 1 | 0 | Inter Milan |
--------------------------------------------------------
| 3 |Inter Milan | 4 | 0 | AC Milan |
--------------------------------------------------------
| 4 |AC Milan | 0 | 2 | Inter Milan |
--------------------------------------------------------
| 5 |Real Madrid | 2 | 0 | AC Milan |
--------------------------------------------------------
| 6 |AC Milan | 2 | 2 | Real Madrid |
--------------------------------------------------------
| 7 |FC Barcelona | 2 | 2 | AC Milan |
--------------------------------------------------------
| 8 |Real Madrid | 2 | 0 | Inter Milan |
--------------------------------------------------------
| 9 |Inter Milan | 3 | 1 | Real Madrid |
--------------------------------------------------------
| 10 |FC Barcelona | 2 | 0 | Real Madrid |
--------------------------------------------------------
| 11 |Real Madrid | 1 | 1 | FC Barcelona |
--------------------------------------------------------
</code></pre>
<p>Basically I want to be able to create a standings table ranking the teams in order, I want to present this table on the fly and not put it into the database</p>
<pre><code>Pos Team Pld W D L F A GD Pts
1 FC Barcelona 5 2 3 0 8 5 3 9
2 Inter Milan 6 2 2 2 11 10 1 8
3 Real Madrid 6 2 2 2 8 8 0 8
4 AC Milan 5 0 3 2 8 12 -4 3
</code></pre>
<p>POS=Position W=won D=Draw L=Loss F=Goals scored For A=Goals scored against GD=Goals difference Pts=Points</p>
<p>I think the most efficient way to do this would be to assign wins, draws and losses, sum the goals scored and goals scored against and when echoing out the data - calculate the total number of games played and the points. </p>
<p>But how would I assign wins draws or losses? And calculate the goals scored and goals against?</p> | 8,009,883 | 3 | 8 | null | 2011-11-04 12:47:05.337 UTC | 13 | 2019-02-07 00:02:48.927 UTC | 2019-02-07 00:02:48.927 UTC | null | 2,370,483 | null | 1,010,198 | null | 1 | 16 | php|mysql|sql-order-by | 9,566 | <p>First union the scores table together swapping the hometeam with the awayteam and swapping the goal counts. This gives you some source data that is easily aggregated and the query to generate the score card is something like this:</p>
<pre><code>select
team,
count(*) played,
count(case when goalsfor > goalsagainst then 1 end) wins,
count(case when goalsagainst> goalsfor then 1 end) lost,
count(case when goalsfor = goalsagainst then 1 end) draws,
sum(goalsfor) goalsfor,
sum(goalsagainst) goalsagainst,
sum(goalsfor) - sum(goalsagainst) goal_diff,
sum(
case when goalsfor > goalsagainst then 3 else 0 end
+ case when goalsfor = goalsagainst then 1 else 0 end
) score
from (
select hometeam team, goalsfor, goalsagainst from scores
union all
select awayteam, goalsagainst, goalsfor from scores
) a
group by team
order by score desc, goal_diff desc;
</code></pre> |
7,991,770 | InputStreamReader vs FileReader | <p>I can't seem to determine any difference between <code>InputStreamReader</code> and <code>FileReader</code> besides the way the two are initialized. Is there any benefit to using one or the other? Most other articles cover <code>FileInputStream</code> vs <code>InputStreamReader</code>, but I am contrasting with <code>FileReader</code> instead. Seems to me they both have the same purpose.</p> | 7,991,813 | 3 | 1 | null | 2011-11-03 08:07:25.027 UTC | 11 | 2022-03-06 14:45:06.867 UTC | null | null | null | null | 1,025,053 | null | 1 | 33 | java|stream | 21,664 | <p>First, <code>InputStreamReader</code> can handle all input streams, not just files. Other examples are network connections, classpath resources and ZIP files.</p>
<p>Second, <code>FileReader</code> until Java 11 did not allow you to specify an encoding and instead only used the plaform default encoding, which made it pretty much useless as using it would result in corrupted data when the code is run on systems with different platform default encodings.</p>
<p>Since Java 11, <code>FileReader</code> is a useful shortcut for wrapping an <code>InputStreamReader</code> around a <code>FileInputStream</code>.</p> |
8,053,491 | Passing lambda functions as named parameters in C# | <p>Compile this simple program:</p>
<pre><code>class Program
{
static void Foo( Action bar )
{
bar();
}
static void Main( string[] args )
{
Foo( () => Console.WriteLine( "42" ) );
}
}
</code></pre>
<p>Nothing strange there. If we make an error in the lambda function body:</p>
<pre><code>Foo( () => Console.LineWrite( "42" ) );
</code></pre>
<p>the compiler returns an error message:</p>
<pre><code>error CS0117: 'System.Console' does not contain a definition for 'LineWrite'
</code></pre>
<p>So far so good. Now, let's use a named parameter in the call to <code>Foo</code>:</p>
<pre><code>Foo( bar: () => Console.LineWrite( "42" ) );
</code></pre>
<p>This time, the compiler messages are somewhat confusing:</p>
<pre><code>error CS1502: The best overloaded method match for
'CA.Program.Foo(System.Action)' has some invalid arguments
error CS1503: Argument 1: cannot convert from 'lambda expression' to 'System.Action'
</code></pre>
<p><strong>What's going on? Why doesn't it report the <em>actual</em> error?</strong></p>
<p>Note that we do get the correct error message if we use an anonymous method instead of the lambda: </p>
<pre><code>Foo( bar: delegate { Console.LineWrite( "42" ); } );
</code></pre> | 8,056,678 | 3 | 5 | null | 2011-11-08 16:11:14.68 UTC | 10 | 2011-11-09 04:24:33.16 UTC | null | null | null | null | 19,241 | null | 1 | 35 | c#|lambda|named-parameters | 5,039 | <blockquote>
<p>Why doesn't it report the actual error?</p>
</blockquote>
<p>No, that's the problem; it <em>is</em> reporting the actual error. </p>
<p>Let me explain with a slightly more complicated example. Suppose you have this:</p>
<pre><code>class CustomerCollection
{
public IEnumerable<R> Select<R>(Func<Customer, R> projection) {...}
}
....
customers.Select( (Customer c)=>c.FristNmae );
</code></pre>
<p>OK, what is the error <em>according to the C# specification</em>? You have to read the specification very carefully here. Let's work it out.</p>
<ul>
<li><p>We have a call to Select as a function call with a single argument and no type arguments. We do a lookup on Select in CustomerCollection, searching for invocable things named Select -- that is, things like fields of delegate type, or methods. Since we have no type arguments specified, we match on any generic method Select. We find one and build a method group out of it. The method group contains a single element.</p></li>
<li><p>The method group now must be analyzed by overload resolution to first determine the <em>candidate set</em>, and then from that determine the <em>applicable candidate set</em>, and from that determine the <em>best applicable candidate</em>, and from that determine the <em>finally validated best applicable candidate</em>. If any of those operations fail then overload resolution must fail with an error. Which one of them fails?</p></li>
<li><p>We start by building the candidate set. In order to get a candidate we must perform <em>method type inference</em> to determine the value of type argument R. How does method type inference work?</p></li>
<li><p>We have a lambda whose parameter types are all known -- the formal parameter is Customer. In order to determine R, we must make a mapping from the return type of the lambda to R. What is the return type of the lambda?</p></li>
<li><p>We assume that c is Customer and attempt to analyze the lambda body. Doing so does a lookup of FristNmae in the context of Customer, and the lookup fails.</p></li>
<li><p>Therefore, lambda return type inference fails and no bound is added to R.</p></li>
<li><p>After all the arguments are analyzed there are no bounds on R. Method type inference is therefore unable to determine a type for R. </p></li>
<li><p>Therefore method type inference fails.</p></li>
<li><p>Therefore no method is added to the candidate set.</p></li>
<li><p>Therefore, the candidate set is empty.</p></li>
<li><p>Therefore there can be no applicable candidates.</p></li>
<li><p>Therefore, the <em>correct</em> error message here would be something like "overload resolution was unable to find a finally-validated best applicable candidate because the candidate set was empty."</p></li>
</ul>
<p><strong>Customers would be very unhappy with that error message.</strong> We have built a considerable number of heuristics into the error reporting algorith that attempts to deduce the more "fundamental" error that the user could actually take action on to fix the error. We reason: </p>
<ul>
<li><p>The actual error is that the candidate set was empty. Why was the candidate set empty?</p></li>
<li><p>Because there was only one method in the method group and type inference failed.</p></li>
</ul>
<p>OK, should we report the error "overload resolution failed because method type inference failed"? Again, customers would be unhappy with that. Instead we again ask the question "why did method type inference fail?" </p>
<ul>
<li>Because the bound set of R was empty.</li>
</ul>
<p>That's a lousy error too. Why was the bounds set empty?</p>
<ul>
<li>Because the only argument from which we could determine R was a lambda's whose return type could not be inferred.</li>
</ul>
<p>OK, should we report the error "overload resolution failed because lambda return type inference failed to infer a return type"? <strong>Again</strong>, customers would be unhappy with that. Instead we ask the question "why did the lambda fail to infer a return type?"</p>
<ul>
<li>Because Customer does not have a member named FristNmae.</li>
</ul>
<p>And <em>that</em> is the error we actually report. </p>
<p>So you see the absolutely tortuous chain of reasoning we have to go through in order to give the error message that you want. We can't just say what went wrong -- that overload resolution was given an empty candidate set -- <strong>we have to dig back into the past to determine how overload resolution got into that state.</strong></p>
<p>The code that does so is <em>exceedingly complex</em>; it deals with more complicated situations than the one I just presented, including cases where there are n different generic methods and type inference fails for m different reasons and we have to work out from among all of them what is the "best" reason to give the user. Recall that in reality there are a dozen different kinds of Select and overload resolution on all of them might fail for different reasons or the same reason.</p>
<p>There are heuristics in the error reporting of the compiler for dealing with all kinds of overload resolution failures; the one I described is just one of them.</p>
<p>So now let's look at your particular case. What is the real error?</p>
<ul>
<li><p>We have a method group with a single method in it, Foo. Can we build a candidate set?</p></li>
<li><p>Yes. There is a candidate. The method Foo is a candidate for the call because it has every <em>required</em> parameter supplied -- bar -- and no extra parameters.</p></li>
<li><p>OK, the candidate set has a single method in it. Is there an applicable member of the candidate set?</p></li>
<li><p>No. The argument corresponding to bar cannot be converted to the formal parameter type because the lambda body contains an error.</p></li>
<li><p>Therefore the applicable candidate set is empty, and therefore there is no finally validated best applicable candidate, and therefore overload resolution fails.</p></li>
</ul>
<p>So what should the error be? Again, we can't just say "overload resolution failed to find a finally validated best applicable candidate" because customers would hate us. We have to start digging for the error message. Why did overload resolution fail?</p>
<ul>
<li>Because the applicable candidate set was empty.</li>
</ul>
<p>Why was it empty?</p>
<ul>
<li>Because every candidate in it was rejected.</li>
</ul>
<p>Was there a best possible candidate?</p>
<ul>
<li>Yes, there was only one candidate.</li>
</ul>
<p>Why was it rejected?</p>
<ul>
<li>Because its argument was not convertible to the formal parameter type.</li>
</ul>
<p>OK, at this point apparently the heuristic that handles overload resolution problems that involve named arguments decides that we've dug far enough and that this is the error we should report. If we do not have named arguments then some other heuristic asks:</p>
<p>Why was the argument not convertible?</p>
<ul>
<li>Because the lambda body contained an error.</li>
</ul>
<p>And we then report that error.</p>
<p><strong>The error heuristics are not perfect</strong>; far from it. Coincidentally I am this week doing a heavy rearchitecture of the "simple" overload resolution error reporting heuristics -- just stuff like when to say "there wasn't a method that took 2 parameters" and when to say "the method you want is private" and when to say "there's no parameter that corresponds to that name", and so on; it is entirely possible that you are calling a method with two arguments, there are no public methods of that name with two parameters, there is one that is private but one of them has a named argument that does not match. Quick, what error should we report? We have to make a best guess, and sometimes there is a better guess that we could have made but were not sophisticated enough to make.</p>
<p>Even getting that right is proving to be a very tricky job. When we eventually get to rearchitecting the big heavy duty heuristics -- like how to deal with failures of method type inference inside of LINQ expressions -- I'll revisit your case and see if we can improve the heuristic. </p>
<p>But since the error message you are getting is completely <em>correct</em>, this is not a bug in the compiler; rather, it is merely a shortcoming of the error reporting heuristic in a particular case.</p> |
11,733,483 | Ember.js routing, outlets and animation | <p>It seems like if you want to animate a transition between states using the new Ember.js router and outlets, you're out of luck, since the previous content of an outlet will be destroyed before you have a chance to animate it. In cases where you can completely animate one view out before transitioning to the new state, there's no problem. It's only the case where both old and new views need to be visible that's problematic.</p>
<p>It looks like some of the functionality needed to animate both the previous outlet content and the new was added in <a href="https://github.com/emberjs/ember.js/pull/1198" rel="nofollow noreferrer">this commit</a>, but I'm not sure I understand how to use it.</p>
<p>There's also been some discussion about using extra transitional routes/states to explicitly model the "in-between" states that animations can represent (<a href="https://github.com/emberjs/ember.js/issues/779" rel="nofollow noreferrer">here</a> and <a href="https://github.com/emberjs/ember.js/commit/b5ff0edb41f50e1f55446c14605fb566aa419ed4" rel="nofollow noreferrer">here</a>), but I'm not sure if it's currently possible to match this approach up with outletted controllers and views.</p>
<p>This is similar to <a href="https://stackoverflow.com/questions/11083392/ember-js-routing-how-not-to-destroy-view-when-exiting-a-route?rq=1">How *not* to destroy View when exiting a route in Ember.js</a>, but I'm not sure overriding the <code>outlet</code> helper is a good solution.</p>
<p>Any ideas?</p> | 15,886,642 | 2 | 1 | null | 2012-07-31 05:11:41.683 UTC | 15 | 2014-01-30 14:57:43.153 UTC | 2017-05-23 12:17:00.147 UTC | null | -1 | null | 501,204 | null | 1 | 20 | ember.js|ember-old-router | 6,941 | <p>You should check this out: <a href="https://github.com/billysbilling/ember-animated-outlet" rel="nofollow">https://github.com/billysbilling/ember-animated-outlet</a>.</p>
<p>Then you can do this in your Handlebars templates:</p>
<pre><code>{{animatedOutlet name="main"}}
</code></pre>
<p>And transition from within a route like this:</p>
<pre><code>App.ApplicationRoute = Ember.Route.extend({
showInvoice: function(invoice) {
this.transitionToAnimated('invoices.show', {main: 'slideLeft'}, invoice);
}
});
</code></pre> |
11,744,089 | PhantomJS create page from string | <p>Is it possible to create a page from a string? </p>
<p>example:</p>
<pre><code>html = '<html><body>blah blah blah</body></html>'
page.open(html, function(status) {
// do something
});
</code></pre>
<p>I have already tried the above with no luck....</p>
<p>Also, I think it's worth mentioning that I'm using nodejs with phantomjs-node(https://github.com/sgentle/phantomjs-node)</p>
<p>Thanks!</p> | 11,746,057 | 5 | 0 | null | 2012-07-31 15:50:59.783 UTC | 12 | 2015-08-05 08:51:47.673 UTC | null | null | null | null | 201,255 | null | 1 | 35 | javascript|node.js|phantomjs | 24,537 | <p>Looking at the phantomjs <a href="http://code.google.com/p/phantomjs/wiki/Interface" rel="nofollow">API</a>, page.open requires a URL as the first argument, not an HTML string. This is why the what you tried does not work. </p>
<p>However, one way that you might be able to achieve the effect of creating a page from a string is to host an empty "skeleton page," somewhere with a URL (could be localhost), and then include Javascript (using includeJs) into the empty page. The Javascript that you include into the blank page can use <code>document.write("<p>blah blah blah</p>")</code> to dynamically add content to the webpage. </p>
<p>I've ever done this, but AFAIK this should work. </p>
<p>Sample skeleton page:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head></head>
<body></body>
</html>
</code></pre> |
11,703,010 | Background tasks in Meteor | <p>I'm wondering, is there is way to implement background taks, maybe with workers pool. Can you show me direction, i'm thinking about writing package for this?</p> | 21,351,966 | 4 | 0 | null | 2012-07-28 17:05:23.33 UTC | 50 | 2019-01-30 05:22:19.603 UTC | 2016-11-05 02:35:36.63 UTC | null | 1,269,037 | null | 688,665 | null | 1 | 59 | javascript|meteor|npm | 15,241 | <h2>2019 update</h2>
<p>Before thinking about writing a package for anything, first look if there are existing packages that do what you need. In the Meteor world, this means looking on Atmosphere for "job/queue/task/worker management/scheduling" packages, then on npm for the same search terms. You also need to define your requirements more precisely:</p>
<ul>
<li>do you want persistence, or would an in-memory solution work?</li>
<li>do you want to be able to distribute jobs to different machines?</li>
</ul>
<h2>Meteor-specific</h2>
<ul>
<li><a href="https://github.com/vsivsi/meteor-job-collection/" rel="nofollow noreferrer">job-collection</a> - reliable (I used it in 2014 in production at a startup), but currently in maintenance mode. Lets you schedule persistent jobs to be run anywhere (servers, clients).</li>
<li><a href="https://github.com/msavin/stevejobs" rel="nofollow noreferrer">SteveJobs</a> - actively maintained by Max Savin, the author of several <a href="http://www.maxsavin.com/" rel="nofollow noreferrer">powerful Meteor tools</a></li>
<li><a href="https://github.com/percolatestudio/meteor-synced-cron/" rel="nofollow noreferrer">littledata:synced-cron</a> - "A simple cron system for Meteor. It supports syncronizing jobs between multiple processes."</li>
</ul>
<p><em>Abandoned packages:</em></p>
<ul>
<li><a href="https://atmospherejs.com/artwells/queue" rel="nofollow noreferrer">artwells:queue</a> - priorities, scheduling, logging, re-queuing. Queue backed by MongoDB. Last <a href="https://github.com/artwells/meteor-queue/commits/master" rel="nofollow noreferrer">code commit</a>: 2015-Oct.</li>
<li>super basic cron packages: <a href="https://atmospherejs.com/chfritz/easycron" rel="nofollow noreferrer">easycron</a>. Last update: Dec 2015.</li>
<li><a href="https://atmospherejs.com/differential/workers" rel="nofollow noreferrer">differential:workers</a> - Spawn headless worker meteor processes to work on async jobs. Last <a href="https://github.com/Differential/meteor-workers/commits/master" rel="nofollow noreferrer">code commit</a>: Jan 2015</li>
<li><a href="https://atmospherejs.com/mrt/cron" rel="nofollow noreferrer">cron</a> (<a href="https://github.com/alexsuslov/Meteor.cron" rel="nofollow noreferrer">since 2015</a>)</li>
<li><a href="https://github.com/CollectionFS/Meteor-power-queue" rel="nofollow noreferrer">PowerQueue</a> - abandoned <a href="https://github.com/CollectionFS/Meteor-power-queue/commits/master" rel="nofollow noreferrer">since 2014</a>. Queue async tasks, throttle resource usage, retry failed. Supports sub queues. <a href="https://github.com/CollectionFS/Meteor-power-queue/issues/15" rel="nofollow noreferrer">No scheduling</a>. No tests, but <a href="http://power-queue-test.meteor.com/" rel="nofollow noreferrer">nifty demo</a>. Not suitable for running for a long while due to using <a href="https://github.com/CollectionFS/Meteor-power-queue/issues/31" rel="nofollow noreferrer">recursive calls</a>.</li>
</ul>
<h2>Npm packages</h2>
<p>Meteor has been able to use npm packages directly for several years now, so this question amounts to finding <a href="https://github.com/sindresorhus/awesome-nodejs#job-queues" rel="nofollow noreferrer">job/worker/queue management packages</a> on NPM. If you don't care about persistence:</p>
<ul>
<li><a href="https://caolan.github.io/async" rel="nofollow noreferrer">Async</a> "provides around 70 functions that include the usual 'functional' suspects (<code>map</code>, <code>reduce</code>, <code>filter</code>, <code>each</code>...) as well as some common patterns for asynchronous control flow (<code>parallel</code>, <code>series</code>, <code>waterfall</code>...)"</li>
<li><a href="https://github.com/d3/d3-queue" rel="nofollow noreferrer">d3-queue</a> - minimalistic, written by D3 author Mike Bostock</li>
</ul>
<p>If you do want persistence, since Meteor uses MongoDB already, it may be advantageous to use a job scheduling package with persistence to MongoDb. The most powerful and popular seems to be <a href="https://github.com/agenda/agenda" rel="nofollow noreferrer">Agenda</a>, but unfortunately it hasn't been maintained in months, and it has a significant backlog of <a href="https://github.com/agenda/agenda/issues" rel="nofollow noreferrer">issues</a>.</p>
<p>If you're willing to add a dependency backed by <a href="http://redis.io/" rel="nofollow noreferrer">redis</a> to your project, there are more choices:</p>
<ul>
<li><a href="https://www.npmjs.com/package/bull#feature-comparison" rel="nofollow noreferrer">bull</a> - the most full-featured job queue solution for Node, backed by Redis</li>
<li><a href="https://github.com/bee-queue/bee-queue" rel="nofollow noreferrer">bee</a> - simple, fast, robust. Does not suffer from a <a href="https://github.com/OptimalBits/bull/issues/1110#issuecomment-436473121" rel="nofollow noreferrer">memory leak that Bull exhibits</a></li>
<li><a href="https://www.npmjs.com/package/kue" rel="nofollow noreferrer">Kue</a> - priority job queue for Node</li>
</ul>
<p>Like MongoDB, Redis can also provide high-availability (via Redis Sentinel), and if you want to distribute jobs among multiple worker machines, you can <a href="https://github.com/OptimalBits/bull/issues/873#issuecomment-437445002" rel="nofollow noreferrer">point them all at the same Redis server</a>.</p> |
20,329,403 | Android Push Notification without using GCM | <p>I need brief steps to implement GCM without using android's standard way. Instead, I need to set up my own central server for device registration and upload file from server to registered device without using GCM.</p>
<p>I also need some suggestions to block certain applications via admin console(For example: Need to choose and send a notification to a particular device to block user to launch Gmail/Google Play application installed on device). It's more like the concept of Mobile application Management. Let me have suggestions on these.</p> | 20,331,937 | 1 | 5 | null | 2013-12-02 13:23:38.957 UTC | 14 | 2021-08-25 10:53:56.693 UTC | 2021-08-25 10:53:56.693 UTC | null | 11,343,720 | null | 393,953 | null | 1 | 36 | android|push-notification | 32,463 | <p>A few things to get your started:</p>
<p><strong>MQTT / Paho</strong><br>
The Paho project provides open-source client implementations of MQTT and MQTT-SN messaging protocols aimed at new, existing, and emerging applications for Machine‑to‑Machine (M2M) and Internet of Things (IoT).<br>
<a href="http://www.eclipse.org/paho/" rel="noreferrer">http://www.eclipse.org/paho/</a>
<a href="https://developer.motorolasolutions.com/docs/DOC-2315" rel="noreferrer">https://developer.motorolasolutions.com/docs/DOC-2315</a></p>
<p><strong>AndroidPN</strong><br>
This is an open source project to provide push notification support for Android. A xmpp based notification server and a client tool kit.
<a href="https://sourceforge.net/projects/androidpn/" rel="noreferrer">https://sourceforge.net/projects/androidpn/</a></p>
<p><strong>Tutorail</strong><br>
Quick example on how to implement push notifications for your Android app using MQTT protocol. I will NOT discuss here why an application might need push notifications or the advantages of Push over Pull. I assume that you know exactly what I mean by push notifications are and why you might need them. However, before jumping in straight to the good stuff, let’s go over how it all started.
<a href="http://tokudu.com/post/50024574938/how-to-implement-push-notifications-for-android" rel="noreferrer">http://tokudu.com/post/50024574938/how-to-implement-push-notifications-for-android</a></p>
<p><strong>The Deacon Project (Deprecated)</strong><br>
The Deacon Project aims to produce an open-source push notifications library for the Android platform. “Deacon” is a Java class library used by Android developers to receive Push notifications from a Meteor comet web server. “Deacon-Demo” (<a href="http://github.com/davidrea/Deacon-Demo/" rel="noreferrer">http://github.com/davidrea/Deacon-Demo/</a>) is an Android app that is used for testing and demonstration of Deacon, and is also developed by members of the Deacon project.<br>
<a href="https://github.com/davidrea/Deacon" rel="noreferrer">https://github.com/davidrea/Deacon</a></p>
<p><strong>Similar Question:</strong>
<a href="https://stackoverflow.com/questions/14629490/android-push-message-without-gcm-possible">Android push message without gcm possible?</a></p>
<p>In addition, if you'd like to have your own server but would still let GCM take care of delivery (it really is one of the cheapest, if not free, and reliable ways to send notifications) there are lot's of alternatives. Like <a href="http://docs.pushjet.io" rel="noreferrer">PushJet</a> <a href="http://pushkin.io" rel="noreferrer">PushKin</a> and <a href="https://github.com/search?o=desc&q=android%20push%20notification&s=stars&type=Repositories&utf8=%E2%9C%93" rel="noreferrer">much more</a>.</p> |
3,845,600 | How to access the first character of a character array? | <pre><code>#include <stdio.h>
int main(void){
char x [] = "hello world.";
printf("%s \n", &x[0]);
return 0;
}
</code></pre>
<p>The above code prints out <code>"hello world."</code></p>
<p>How would i print out just <code>"h"</code>? Shouldn't the access <code>x[0]</code> ensure this?</p> | 3,845,627 | 5 | 0 | null | 2010-10-02 12:09:27.64 UTC | 1 | 2020-03-01 14:26:48.213 UTC | 2010-10-03 12:32:04.74 UTC | null | 227,665 | null | 234,712 | null | 1 | 3 | c|arrays|indexing|printf|character | 41,257 | <p>You should do:</p>
<pre><code>printf("%c \n", x[0]);
</code></pre>
<p>The <a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf/" rel="noreferrer">format specifier</a> to print a char is <code>c</code>. So the format string to be used is <code>%c</code>.</p>
<p>Also to access an array element at a valid index <code>i</code> you need to say <code>array_name[i]</code>. You should not be using the <code>&</code>. Using <code>&</code> will give you the address of the element.</p> |
3,634,627 | How to know the preferred display width (in columns) of Unicode characters? | <p>In different encodings of Unicode, for example <strong>UTF-16le</strong> or <strong>UTF-8</strong>, a character may occupy 2 or 3 bytes. Many Unicode applications doesn't take care of display width of Unicode chars just like they are all Latin letters. For example, in <strong>80</strong>-column text, which should contains <strong>40</strong> Chinese characters or <strong>80</strong> Latin letters in one line, but most application (like Eclipse, Notepad++, and all well-known text editors, I dare if there's any good exception) just count each Chinese character as 1 width as Latin letter. This certainly make the result format ugly and non-aligned. </p>
<p>For example, a tab-width of 8 will get the following ugly result (count all Unicode as 1 display width):</p>
<pre><code>apple 10
banana 7
苹果 6
猕猴桃 31
pear 16
</code></pre>
<p>However, the expected format is (Count each Chinese character as 2 width):</p>
<pre><code>apple 10
banana 7
苹果 6
猕猴桃 31
pear 16
</code></pre>
<p>The improper calculation on display width of chars make these editors totally useless when doing tab-align, and line wrapping and paragraph reformat. </p>
<p>Though, the width of a character may vary between different fonts, but in all cases of Fixed-size terminal font, Chinese character is always double width. That is to say, in despite of font, each Chinese character is preferred to display in 2 width. </p>
<p>One of solution is, I can get the correct width by convert the encoding to <strong>GB2312</strong>, in <strong>GB2312</strong> encoding each Chinese character takes 2 bytes. however, some Unicode characters doesn't exist in GB2312 charset (or <strong>GBK</strong> charset). And, in general it's not a good idea to compute the display width from the encoded size in bytes.</p>
<p>To simply calculate all character in Unicode in range of (<code>\u0080</code>..<code>\uFFFF</code>) as 2 width is also not correct, because there're also many 1-width chars scattered in the range. </p>
<p>There's also difficult when calculate the display width of Arabic letters and Korean letters, because they construct a word/character by arbitrary number of Unicode code points.</p>
<p>So, the display width of a Unicode code point maybe not an integer, I deem that is ok, they can be grounded to integer in practice, at least better than none. </p>
<p>So, is there any attribute related to the preferred display width of a char in Unicode standard?
Or any Java library function to calculate the display width?</p> | 9,145,712 | 5 | 1 | null | 2010-09-03 09:54:00.613 UTC | 18 | 2012-07-26 11:30:38.033 UTC | 2012-07-26 11:30:38.033 UTC | null | 217,071 | null | 217,071 | null | 1 | 21 | unicode|text-formatting|character-properties|mbcs | 8,944 | <p>Sounds like you're looking for something like <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/wcwidth.html" rel="noreferrer"><code>wcwidth</code></a> and <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/wcswidth.html" rel="noreferrer"><code>wcswidth</code></a>, defined in IEEE Std 1003.1-2001, but removed from ISO C:</p>
<blockquote>
<p>The <code>wcwidth()</code> function shall determine the number of column positions
required for the wide character <em>wc</em>. The <code>wcwidth()</code> function shall
either return 0 (if <em>wc</em> is a null wide-character code), or return the
number of column positions to be occupied by the wide-character code
<em>wc</em>, or return -1 (if <em>wc</em> does not correspond to a printable
wide-character code).</p>
</blockquote>
<p>Markus Kuhn wrote an open source version, <a href="http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c" rel="noreferrer">wcwidth.c</a>, based on Unicode 5.0. It includes a description of the problem, and an acknowledgement of the lack of standards in the area:</p>
<blockquote>
<p>In fixed-width output devices, Latin characters all occupy a single
"cell" position of equal width, whereas ideographic CJK characters
occupy two such cells. Interoperability between terminal-line
applications and (teletype-style) character terminals using the UTF-8
encoding requires agreement on which character should advance the
cursor by how many cell positions. No established formal standards
exist at present on which Unicode character shall occupy how many cell
positions on character terminals. These routines are a first attempt
of defining such behavior based on simple rules applied to data
provided by the Unicode Consortium. [...]</p>
</blockquote>
<p>It implements the following rules:</p>
<ul>
<li>The null character (U+0000) has a column width of 0.</li>
<li>Other C0/C1 control characters and DEL will lead to a return value of -1.</li>
<li>Non-spacing and enclosing combining characters (general category code Mn or Me in the Unicode database) have a column width of 0.</li>
<li>SOFT HYPHEN (U+00AD) has a column width of 1.</li>
<li>Other format characters (general category code Cf in the Unicode database) and ZERO WIDTH SPACE (U+200B) have a column width of 0.</li>
<li>Hangul Jamo medial vowels and final consonants (U+1160-U+11FF) have a column width of 0.</li>
<li>Spacing characters in the East Asian Wide (W) or East Asian Full-width (F) category as defined in Unicode Technical Report #11 have a column width of 2.</li>
<li>All remaining characters (including all printable ISO 8859-1 and WGL4 characters, Unicode control characters, etc.) have a column width of 1.</li>
</ul> |
3,408,150 | Add attribute 'checked' on click jquery | <p>I've been trying to figure out how to add the attribute "checked" to a checkbox on click. The reason I want to do this is so if I check off a checkbox; I can have my local storage save that as the html so when the page refreshes it notices the checkbox is checked. As of right now if I check it off, it fades the parent, but if I save and reload it stays faded but the checkbox is unchecked.</p>
<p>I've tried doing $(this).attr('checked'); but it does not seem to want to add checked.</p>
<p>EDIT:
After reading comments it seems i wasn't being clear.
My default input tag is:</p>
<pre><code><input type="checkbox" class="done">
</code></pre>
<p>I need it top be so when I click the checkbox, it adds "checked" to the end of that. Ex:</p>
<pre><code><input type="checkbox" class="done" checked>
</code></pre>
<p>I need it to do this so when I save the html to local storage, when it loads, it renders the checkbox as checked. </p>
<pre><code>$(".done").live("click", function(){
if($(this).parent().find('.editor').is(':visible') ) {
var editvar = $(this).parent().find('input[name="tester"]').val();
$(this).parent().find('.editor').fadeOut('slow');
$(this).parent().find('.content').text(editvar);
$(this).parent().find('.content').fadeIn('slow');
}
if ($(this).is(':checked')) {
$(this).parent().fadeTo('slow', 0.5);
$(this).attr('checked'); //This line
}else{
$(this).parent().fadeTo('slow', 1);
$(this).removeAttr('checked');
}
});
</code></pre> | 3,409,979 | 5 | 0 | null | 2010-08-04 17:36:53.097 UTC | 5 | 2020-06-22 01:05:14.59 UTC | 2010-08-04 18:39:13.193 UTC | null | 400,623 | null | 400,623 | null | 1 | 25 | javascript|jquery|html|local-storage | 171,257 | <p>It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's <code>attr()</code> method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. <strong>[UPDATE: Since jQuery 1.6.1, <a href="http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/" rel="noreferrer">the situation has changed slightly</a>]</strong></p>
<p>IE has some problems with the DOM <code>setAttribute</code> method but in this case it should be fine:</p>
<pre><code>this.setAttribute("checked", "checked");
</code></pre>
<p>In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the <code>checked</code> attribute, you need to set the <code>checked</code> property as well:</p>
<pre><code>this.setAttribute("checked", "checked");
this.checked = true;
</code></pre>
<p>To uncheck the checkbox and remove the attribute, do the following:</p>
<pre><code>this.setAttribute("checked", ""); // For IE
this.removeAttribute("checked"); // For other browsers
this.checked = false;
</code></pre> |
3,815,656 | simple encrypt/decrypt lib in python with private key | <p>Is there a simple way to encrypt/decrypt a string with a key?</p>
<p>Something like:</p>
<pre><code>key = '1234'
string = 'hello world'
encrypted_string = encrypt(key, string)
decrypt(key, encrypted_string)
</code></pre>
<p>I couldn't find anything simple to do that.</p> | 3,815,681 | 5 | 1 | null | 2010-09-28 17:57:32.8 UTC | 13 | 2021-02-21 11:27:24.723 UTC | 2020-04-18 09:40:29.957 UTC | null | 7,487,335 | null | 258,564 | null | 1 | 27 | python|encryption | 52,297 | <p><a href="http://www.dlitz.net/software/pycrypto/" rel="noreferrer">http://www.dlitz.net/software/pycrypto/</a> should do what you want.</p>
<p>Taken from their docs page.</p>
<pre><code>>>> from Crypto.Cipher import DES
>>> obj=DES.new('abcdefgh', DES.MODE_ECB)
>>> plain="Guido van Rossum is a space alien."
>>> len(plain)
34
>>> obj.encrypt(plain)
Traceback (innermost last):
File "<stdin>", line 1, in ?
ValueError: Strings for DES must be a multiple of 8 in length
>>> ciph=obj.encrypt(plain+'XXXXXX')
>>> ciph
'\021,\343Nq\214DY\337T\342pA\372\255\311s\210\363,\300j\330\250\312\347\342I\3215w\03561\303dgb/\006'
>>> obj.decrypt(ciph)
'Guido van Rossum is a space alien.XXXXXX'
</code></pre> |
3,763,423 | How to get form fields' id in Django | <p>Is there any way to get the id of a field in a template?</p>
<p>In the HTML I get: <code><input name="field_name" id="id_field_name"...</code></p>
<p>I know I can get the name with <code>{{ field.html_name }}</code>, but is there anything similar for getting the id?<br>
Or can I only get it like this: <code>id_{{ field.html_name }}</code>?</p> | 3,765,016 | 5 | 0 | null | 2010-09-21 18:46:59.96 UTC | 19 | 2022-01-17 07:40:51.873 UTC | 2021-08-14 19:42:42.213 UTC | null | 7,758,804 | null | 182,945 | null | 1 | 109 | django|django-forms|django-templates | 63,906 | <p>You can get the ID like this:</p>
<pre><code>{{ field.auto_id }}
</code></pre> |
3,724,242 | What is the difference between “int” and “uint” / “long” and “ulong”? | <p>I know about <code>int</code> and <code>long</code> (32-bit and 64-bit numbers), but what are <code>uint</code> and <code>ulong</code>?</p> | 3,724,255 | 6 | 0 | null | 2010-09-16 06:36:31.577 UTC | 27 | 2022-07-24 06:52:58.963 UTC | 2014-02-03 09:46:39.803 UTC | null | 635,809 | null | 427,224 | null | 1 | 144 | c#|types|integer|unsigned|signed | 247,522 | <p>The primitive data types prefixed with "u" are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand they can store positive numbers twice as large as their signed counterparts. The signed counterparts do not have "u" prefixed.</p>
<p>The limits for int (32 bit) are:</p>
<pre><code>int: –2147483648 to 2147483647
uint: 0 to 4294967295
</code></pre>
<p>And for long (64 bit):</p>
<pre><code>long: -9223372036854775808 to 9223372036854775807
ulong: 0 to 18446744073709551615
</code></pre> |
3,495,582 | Amazon EC2 as web server? | <p>I have thought a lot recently about the different hosting types that are available out there. We can get pretty decent latency (average) from an EC2 instance in Europe (we're situated in Sweden) and the cost is pretty good. Obviously, the possibility of scaling up and down instances is amazing for us that's in a really expansive phase right now.</p>
<p>From a logical perspective, I also believe that Amazon probably can provide better availability and stability than most hosting companies on the market. Probably it will also outweigh the need of having a phone number to dial when we wonder anything and force us to google the things by ourselves :)</p>
<p>So, what should we be concerned about if we were about to run our web server on EC2? What are the pro's and cons?</p>
<p>To clarify, we will run a pretty standard LAMP configuration with memcached added probably.</p>
<p>Thanks</p> | 3,523,776 | 8 | 1 | null | 2010-08-16 17:22:30.347 UTC | 42 | 2015-12-02 00:19:59.147 UTC | 2012-05-21 09:07:00.317 UTC | null | 45,773 | null | 198,128 | null | 1 | 63 | amazon-ec2|amazon-web-services|lamp | 48,040 | <blockquote>
<p>So, what should we be concerned about if we were about to run our web server on EC2? What are the pro's and cons?</p>
</blockquote>
<p>The pros and cons of EC2 are somewhat dependent on your business. Below is a list of issues that I believe affect large organizations:</p>
<ul>
<li><strong>Separation of duties</strong> Your existing company probably has separate networking and server operations teams. With EC2 it may be difficult to separate these concerns. ie. The guy defining your Security Groups (firewall) is probably the same person who can spin up servers.</li>
<li><strong>Home access to your servers</strong> Corporate environments are usually administered on-premise or through a Virtual Private Network (VPN) with two-factor authentication. Administrators with access to your EC2 control panel can likely make changes to your environment from home. Note further that your EC2 access keys/accounts may remain available to people who leave or get fired from your company, making home access an even bigger problem...</li>
<li><strong>Difficulty in validating security</strong> Some security controls may inadvertently become weak. Within your premises you can be 99% certain that all servers are behind a firewall that restricts any admin access from outside your premises. When you're in the cloud it's a lot more difficult to ensure such controls are in place for all your systems.</li>
<li><strong>Appliances and specialized tools do not go in the cloud</strong> Specialized tools cannot go into the cloud. This may impact your security posture. For example, you may have some sort of network intrusion detection appliances sitting in front of on-premise servers, and you will not be able to move these into the cloud.</li>
<li><strong>Legislation and Regulations</strong> I am not sure about regulations in your country, but you should be aware of cross-border issues. For example, running European systems on American EC2 soil may open your up to Patriot Act regulations. If you're dealing with credit card numbers or personally identifiable information then you may also have various issues to deal with if infrastructure is outside of your organization.</li>
<li><strong>Organizational processes</strong> Who has access to EC2 and what can they do? Can someone spin up an Extra Large machine and install their own software? (Side note: Our company <a href="http://LabSlice.com" rel="noreferrer">http://LabSlice.com</a> actually adds policies to stop this from happening). How do you backup and restore data? Will you start replicating processes within your company simply because you've got a separate cloud infrastructure?</li>
<li><strong>Auditing challenges</strong> Any auditing activities that you normally undertake may be complicated if data is in the cloud. A good example is PCI -- Can you actually always prove data is within your control if it's hosted outside of your environment somewhere in the ether?</li>
<li><strong>Public/private connectivity is a challenge</strong> Do you ever need to mix data between your public and private environments? It can become a challenge to send data between these two environments, and to do so securely.</li>
<li><strong>Monitoring and logging</strong> You will likely have central systems monitoring your internal environment and collecting logs from your servers. Will you be able to achieve the monitoring and log collection activities if you run servers off-premise?</li>
<li><strong>Penetration testing</strong> Some companies run periodic penetration testing activities directly on public infrastructure. I may be mistaken, but I think that running pen testing against Amazon infrastructure is against their contract (which make sense, as they would only see public hacking activity against infrastructure they own).</li>
</ul>
<p>I believe that EC2 is definitely a good idea for small/medium businesses. They are rarely encumbered by the above issues, and usually Amazon can offer better services than an SMB could achieve themselves. For large organizations EC2 can obviously raise some concerns and issues that are not easily dealt with.</p>
<p>Simon @ <a href="http://blog.LabSlice.com" rel="noreferrer">http://blog.LabSlice.com</a></p> |
4,015,613 | Good tutorial for using HTML5 History API (Pushstate?) | <p>I am looking into using the HTML5 History API to resolve deep linking problems with AJAX loaded content, but I am struggling to get off the ground. Does any one know of any good resources?</p>
<p>I want to use this as it seems a great way to allow to the possibility of those being sent the links may not have JS turned on. Many solutions fail when someone with JS sends a link to someone without.</p>
<p>My initial research seems to point to a History API within JS, and the pushState method.</p>
<p><a href="http://html5demos.com/history" rel="noreferrer">http://html5demos.com/history</a></p> | 4,843,248 | 9 | 0 | null | 2010-10-25 14:36:40.227 UTC | 102 | 2014-08-31 21:05:51.267 UTC | 2013-05-03 02:19:31.957 UTC | null | 1,858,225 | null | 445,126 | null | 1 | 167 | javascript|html|pushstate|html5-history | 130,044 | <p>For a great tutorial the Mozilla Developer Network page on this functionality is all you'll need: <a href="https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history" rel="noreferrer">https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history</a></p>
<p>Unfortunately, the HTML5 History API is implemented differently in all the HTML5 browsers (making it inconsistent and buggy) and has no fallback for HTML4 browsers. Fortunately, <a href="https://github.com/browserstate/History.js" rel="noreferrer">History.js</a> provides cross-compatibility for the HTML5 browsers (ensuring all the HTML5 browsers work as expected) and optionally provides a hash-fallback for HTML4 browsers (including maintained support for data, titles, pushState and replaceState functionality).</p>
<p>You can read more about History.js here:
<a href="https://github.com/browserstate/history.js" rel="noreferrer">https://github.com/browserstate/history.js</a></p>
<p>For an article about Hashbangs VS Hashes VS HTML5 History API, see here:
<a href="https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling" rel="noreferrer">https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling</a></p> |
3,392,493 | Adjust width of input field to its input | <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="text" value="1" style="min-width:1px;" /></code></pre>
</div>
</div>
</p>
<p>This is my code and it is not working. Is there any other way in HTML, JavaScript, PHP or CSS to set minimum width?</p>
<p>I want a text input field with a dynamically changing width, so that the input field fluids around its contents. Every input has a built-in padding of <code>2em</code>, that is the problem and second problem is that <code>min-width</code> ain't working on input at all.</p>
<p>If I set width more than it is needed than the whole program is messy, I need the width of 1px, more only if it's needed.</p> | 3,392,617 | 32 | 1 | null | 2010-08-02 23:11:08.813 UTC | 71 | 2022-07-27 13:51:04.317 UTC | 2022-07-27 13:51:04.317 UTC | null | 616,443 | null | 409,131 | null | 1 | 256 | javascript|html|css | 435,951 | <p>It sounds like your expectation is that the style be applied dynamically to the width of the textbox based on the contents of the textbox. If so you will need some js to run on textbox contents changing, something like <a href="http://jsfiddle.net/73T7S/" rel="noreferrer">this</a>:</p>
<pre><code><input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">
</code></pre>
<p>Note: this solution only works when every character is exactly <code>8px</code> wide. You could use the CSS-Unit "ch" (characters) which represents the width of the character "0" in the chosen font. You can read about it <a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units#Relative_length_units" rel="noreferrer">here</a>.</p> |
4,023,830 | How to compare two strings in dot separated version format in Bash? | <p>Is there any way to compare such strings on bash, e.g.: <code>2.4.5</code> and <code>2.8</code> and <code>2.4.5.1</code>?</p> | 4,025,065 | 36 | 0 | null | 2010-10-26 12:53:18.9 UTC | 81 | 2022-09-25 03:18:07.947 UTC | 2017-10-03 20:53:04.527 UTC | null | 6,862,601 | null | 486,405 | null | 1 | 250 | linux|bash|versioning | 127,368 | <p>Here is a pure Bash version that doesn't require any external utilities:</p>
<pre><code>#!/bin/bash
vercomp () {
if [[ $1 == $2 ]]
then
return 0
fi
local IFS=.
local i ver1=($1) ver2=($2)
# fill empty fields in ver1 with zeros
for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
do
ver1[i]=0
done
for ((i=0; i<${#ver1[@]}; i++))
do
if [[ -z ${ver2[i]} ]]
then
# fill empty fields in ver2 with zeros
ver2[i]=0
fi
if ((10#${ver1[i]} > 10#${ver2[i]}))
then
return 1
fi
if ((10#${ver1[i]} < 10#${ver2[i]}))
then
return 2
fi
done
return 0
}
testvercomp () {
vercomp $1 $2
case $? in
0) op='=';;
1) op='>';;
2) op='<';;
esac
if [[ $op != $3 ]]
then
echo "FAIL: Expected '$3', Actual '$op', Arg1 '$1', Arg2 '$2'"
else
echo "Pass: '$1 $op $2'"
fi
}
# Run tests
# argument table format:
# testarg1 testarg2 expected_relationship
echo "The following tests should pass"
while read -r test
do
testvercomp $test
done << EOF
1 1 =
2.1 2.2 <
3.0.4.10 3.0.4.2 >
4.08 4.08.01 <
3.2.1.9.8144 3.2 >
3.2 3.2.1.9.8144 <
1.2 2.1 <
2.1 1.2 >
5.6.7 5.6.7 =
1.01.1 1.1.1 =
1.1.1 1.01.1 =
1 1.0 =
1.0 1 =
1.0.2.0 1.0.2 =
1..0 1.0 =
1.0 1..0 =
EOF
echo "The following test should fail (test the tester)"
testvercomp 1 1 '>'
</code></pre>
<p>Run the tests:</p>
<pre><code>$ . ./vercomp
The following tests should pass
Pass: '1 = 1'
Pass: '2.1 < 2.2'
Pass: '3.0.4.10 > 3.0.4.2'
Pass: '4.08 < 4.08.01'
Pass: '3.2.1.9.8144 > 3.2'
Pass: '3.2 < 3.2.1.9.8144'
Pass: '1.2 < 2.1'
Pass: '2.1 > 1.2'
Pass: '5.6.7 = 5.6.7'
Pass: '1.01.1 = 1.1.1'
Pass: '1.1.1 = 1.01.1'
Pass: '1 = 1.0'
Pass: '1.0 = 1'
Pass: '1.0.2.0 = 1.0.2'
Pass: '1..0 = 1.0'
Pass: '1.0 = 1..0'
The following test should fail (test the tester)
FAIL: Expected '>', Actual '=', Arg1 '1', Arg2 '1'
</code></pre> |
8,170,450 | Combine static libraries on Apple | <p>I tried the approach in this <a href="https://stackoverflow.com/questions/3821916/how-to-merge-two-ar-static-libraries-into-one">question</a>, but it seems the linux version of <code>ar</code> is not the same as the mac version since I failed to combine the object files again.</p>
<p>What I basically want to do is is merge another static library into my Xcode static library build product via a run-script build phase.</p>
<p>Unfortunately I can't compile the other library directly into my project because it has it's own build system (therefore I use the compiled libs).</p>
<p>I think it should be possible to merge the other library via <code>ar</code> into the Xcode generated library without decompiling the build product. How do I accomplish this?</p> | 8,170,851 | 4 | 0 | null | 2011-11-17 16:12:45.367 UTC | 28 | 2021-05-11 17:29:07.35 UTC | 2021-05-11 17:29:07.35 UTC | null | 207,791 | user187676 | null | null | 1 | 50 | objective-c|c|xcode|static-libraries | 21,038 | <p>you can use <code>libtool</code> to do it</p>
<pre><code>libtool -static -o new.a old1.a old2.a
</code></pre> |
8,337,180 | Custom Single choice ListView | <p>I want to make a custom List View having Two TextViews and a radio Button in a single row. And on listitem click the radio button state should be toggle. I cannot use Simple Adapter here.</p>
<p>I have already asked that question <a href="https://stackoverflow.com/questions/8295026/single-choice-listview-custom-row-layout">Single choice ListView custom Row Layout</a> but don't find any satisfactory solution.</p>
<p>What I am currently doing is I am using simple_list_item_single_choice and putting data of both TextViews in a single one separated by some white spaces. But here it is getting worse (shown in the image below).</p>
<p><img src="https://i.stack.imgur.com/49M4f.png" alt="http://db.tt/ulP6pn7V"></p>
<p>What I want is to fix the location of size and price and make list view as single choice.</p>
<p>XML Layout for the list can be something like:</p>
<pre><code>**<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="15sp"
android:width="200dp" />
<TextView
android:id="@+id/tv_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="15sp"
android:width="70dp" />
<RadioButton
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>**
</code></pre>
<p>How to make custom adapter for that?</p> | 8,502,062 | 5 | 3 | null | 2011-12-01 06:00:27.113 UTC | 17 | 2022-04-28 22:28:54.547 UTC | 2017-10-08 06:41:56.263 UTC | null | 1,033,581 | null | 954,135 | null | 1 | 22 | android|listview|choice | 57,412 | <p>I've been searching for an answer to this problem all morning, and the most useful thing I've found so far is <a href="https://web.archive.org/web/20111205132234/http://tokudu.com/2010/android-checkable-linear-layout/" rel="nofollow noreferrer">this article</a>.</p>
<p>While I haven't implemented the solution it suggests yet, it sounds like it's on the right track.</p>
<p>Basically, the single-choice <code>ListView</code> expects the widgets you provide it with to implement the <code>Checkable</code> interface. <code>LinearLayout</code> and others don't. So you need to create a custom layout that inherits <code>LinearLayout</code> (or whatever layout you want to use for your items) and implements the necessary interface.</p> |
7,780,550 | Referencing a .css file in github repo as stylesheet in a .html file | <p>I've got a repository on github with a .css file in it. Is there any way to have github serve this file in a way that I can consume it in a web page?</p>
<p>In other words, I'd like to be able to reference this source file at github directly, from an HTML file on my local computer or a live domain. Something like:</p>
<pre><code><link rel="stylesheet"
type="text/css"
href="http://github.com/foouser/barproject/master/xenu-is-my-lover.css"
/>
</code></pre>
<p>I've tried including a<code><link></code> to the "raw" source file (<code>http://raw.github.com...</code>), but github serves its <code>Content-Type</code> as <code>text/plain</code>, and consequently, Chrome and FF are not adding its content as CSS styles to the page—the file's data is being discarded and a warning is shown in the debugger consoles of the browsers.</p> | 7,790,846 | 5 | 2 | null | 2011-10-15 20:47:42.147 UTC | 11 | 2019-03-08 00:00:22.213 UTC | 2011-10-15 21:08:01.38 UTC | null | 979,672 | null | 979,672 | null | 1 | 35 | github | 27,702 | <p>GitHub repos aren't web hosting, you should push that stuff up to a service specifically designed to serve files, like pages.github.com.</p> |
7,750,982 | Can Python's map function call object member functions? | <p>I need to do something that is functionally equivalent to this:</p>
<pre><code>for foo in foos:
bar = foo.get_bar()
# Do something with bar
</code></pre>
<p>My first instinct was to use <code>map</code>, but this did not work:</p>
<pre><code>for bar in map(get_bar, foos):
# Do something with bar
</code></pre>
<p>Is what I'm trying to accomplish possible with <code>map</code>? Do I need to use a list comprehension instead? What is the most Pythonic idiom for this?</p> | 7,751,029 | 5 | 2 | null | 2011-10-13 07:49:47.097 UTC | 9 | 2019-04-24 23:13:39.003 UTC | null | null | null | null | 58,994 | null | 1 | 49 | python | 29,819 | <p>Either with <code>lambda</code>:</p>
<pre><code>for bar in map(lambda foo: foo.get_bar(), foos):
</code></pre>
<p>Or simply with instance method reference on your instance's class:</p>
<pre><code>for bar in map(Foo.get_bar, foos):
</code></pre>
<p>As this was added from a comment, I would like to note that this requires the items of <code>foos</code> to be instances of <code>Foo</code> (i.e. <code>all(isinstance(foo, Foo) for foo in foos)</code> must be true) and not only as the other options do instances of classes with a <code>get_bar</code> method. This alone might be reason enough to not include it here.</p>
<p>Or with <code>methodcaller</code>:</p>
<pre><code>import operator
get_bar = operator.methodcaller('get_bar')
for bar in map(get_bar, foos):
</code></pre>
<p>Or with a generator expression:</p>
<pre><code>for bar in (foo.get_bar() for foo in foos):
</code></pre> |
7,703,049 | check 1 billion cell-phone numbers for duplicates | <p>It's an interview question:</p>
<blockquote>
<p>There are 1 billion cell-phone numbers which has 11 digits, they are stored randomly in a file, for
example 12345678910, the first digit gotta be 1. Go through these numbers to see whether there is
one with duplicate, just see if duplicate exists, if duplicate found,
return True, or return False.
<strong>Only 10 MB memory allowed.</strong></p>
</blockquote>
<p>Here is my solution:</p>
<p>Hash all these numbers into 1000 files using <code>hash(num)%1000</code>, then the duplicates should fall into the same file.</p>
<p>After the hashing, I got 1000 small files, each of which contains <code>1 million</code> numbers <code>at most</code>, right? I'm not sure about this, I simply do it <code>1 billion / 1000 = 1 million</code>.</p>
<p>Then for each file, build a hash table to store each number and a <code>flag</code> representing its occurrence. </p>
<p>I guess, it will take <code>5 B</code> to represent the number, <code>4 B</code> for the lower <code>8 digits</code> and <code>1 B</code> for the upper <code>3 digits</code>; and actually <code>1 bit</code> will suffice the <code>flag</code>, because I just need to find out whether duplicate exists, only how many times. But how can I apply the <code>1 bit</code> flag to each number? I'm stumbled, so I choose <code>bool</code> to be the flag, <code>1 B</code> is taken.
So finally, each number in the hash table will take <code>5B<for number> + 1B<for flag> + 4B<for the next-pointer> = 10B</code>, then each file will take <code>10M</code> for the hash table.</p>
<p>That's my stupid solution, Please give me a better one.</p>
<p>Thanks.</p>
<p><strong>FOLLOW UP:</strong></p>
<blockquote>
<p>If there are <code>no duplicates</code> in these 1 billion phone numbers, given one
phone number, how to find out the given one <code>is or is not in</code> these 1
billion numbers? Use <strong>as few memory as possible</strong>.</p>
</blockquote>
<p>I came up with 2 solutions,</p>
<ol>
<li><p>The phone number can be represented using 5B as I said above, scan through the file, read one number a time, and <code>xor the given number with the one read from the file</code>, if the result is <code>0</code>, then the given one is in the file, it'll take <code>O(n)</code> time, right?</p></li>
<li><p><code>Partition</code> these numbers into <code>2 small files</code> according to the <code>leading bit</code>, which means, those numbers with a <code>leading 1-bit</code> go to a file, <code>leading 0-bit</code> go to another file, meanwhile count how many numbers in each file, if the given number fall into the 1-bit file and the 1-bit file's <code>count</code> is <code>not full</code>, then <code>again partition</code> the 1-bit file according to the <code>secondary leading-bit</code>, and check the given number recursively; if the 1-bit file <code>is full</code>, then the given number gotta be in the file, it'll take <code>O(logn)</code> time, right?</p></li>
</ol> | 7,703,297 | 6 | 10 | null | 2011-10-09 11:02:04.563 UTC | 19 | 2017-09-22 07:31:02.92 UTC | 2017-09-22 17:44:54.74 UTC | null | -1 | null | 888,051 | null | 1 | 16 | algorithm|large-data | 7,641 | <p>Fastest solution (also in terms of programmer overhead :)</p>
<pre><code># Generate some 'phones'
yes 1 | perl -wne 'chomp; ++$a; print $_."$a\n";' > phones.txt
# Split phones.txt in 10MB chunks
split -C 10000000 phones.txt
# Sort each 10MB chunk with 10MB of memory
for i in x??; do sort -S 10M $i > $i.srt; echo -ne "$i.srt\0" >> merge.txt; done
# Merge the shorted chunks with 10MB of memory
sort -S 10M --files0-from=merge.txt -m > sorted.txt
# See if there is any duplicates
test -z $(uniq -d merge.txt)
</code></pre>
<p>Check that the memory usage constraint is met with pmap $(pidof sort) for example:</p> |
7,931,069 | How to fake time in javascript? | <p>I would like to mock the Date constructor so that whenever I call new Date(), it always return specific time.</p>
<p>I found Sinon.js provide useFakeTimers to mock time. But the following code doesn't work for me.</p>
<pre><code>sinon.useFakeTimers(new Date(2011,9,1));
//expect : 'Sat Oct 01 2011 00:00:00' ,
//result : 'Thu Oct 27 2011 10:59:44‘
var d = new Date();
</code></pre> | 11,679,436 | 6 | 1 | null | 2011-10-28 15:03:50.233 UTC | 6 | 2019-01-07 08:04:40.2 UTC | 2011-10-28 15:04:45.697 UTC | null | 370,103 | null | 832,847 | null | 1 | 41 | javascript | 32,564 | <p><code>sinon.useFakeTimers</code> accepts a timestamp (integer) as parameter, not a Date object.</p>
<p>Try with </p>
<pre><code>clock = sinon.useFakeTimers(new Date(2011,9,1).getTime());
new Date(); //=> return the fake Date 'Sat Oct 01 2011 00:00:00'
clock.restore();
new Date(); //=> will return the real time again (now)
</code></pre>
<p>If you use anything like <code>setTimeout</code>, make sure you read the docs because the <code>useFakeTimers</code> will disrupt the expected behavior of that code. </p> |
7,872,611 | In Python, what is the difference between pass and return | <p>I have seen some code in Pinax and other django apps that instead of pass, an empty return statement is used. What is the difference and would it have any effect on, for example, the django code below that I am running? The code is a signal method that automatically saves the hashtags into taggit Tag objects for a tweet object.</p>
<p>I saw a question here about whether having or not having a return statement in PHP makes a difference in the interpreted bytecode, but I am not sure if it is relevant to Python.</p>
<pre><code>import re
TAG_REGEX = re.compile(r'#(?P<tag>\w+)')
def get_tagged(sender, instance, **kwargs):
"""
Automatically add tags to a tweet object.
"""
if not instance:
return # will pass be better or worse here?
post = instance
tags_list = [smart_unicode(t).lower() for t in list(set(TAG_REGEX.findall(post.content)))]
if tags_list:
post.tags.add(*tags_list)
post.save()
else:
return # will a pass be better or worse here?
post_save.connect(get_tagged, sender=Tweet)
</code></pre> | 7,872,670 | 7 | 1 | null | 2011-10-24 07:50:01.027 UTC | 14 | 2021-04-25 00:20:49.463 UTC | null | null | null | null | 841,766 | null | 1 | 42 | python | 46,298 | <pre><code>if not instance:
return # will pass be better or worse here?
</code></pre>
<p>Worse. It changes the logic. <code>pass</code> actually means: Do nothing. If you would replace <code>return</code> with <code>pass</code> here, the control flow would continue, changing the semantic of the code.</p>
<p>The purpose for <code>pass</code> is to create empty blocks, which is not possible otherwise with Python's indentation scheme. For example, an empty function in C looks like this:</p>
<pre><code>void foo()
{
}
</code></pre>
<p>In Python, this would be a syntax error:</p>
<pre><code>def foo():
</code></pre>
<p>This is where <code>pass</code> comes handy:</p>
<pre><code>def foo():
pass
</code></pre> |
8,156,707 | gzip a file in Python | <p>I want to gzip a file in Python. I am trying to use the subprocss.check_call(), but it keeps failing with the error 'OSError: [Errno 2] No such file or directory'. Is there a problem with what I am trying here? Is there a better way to gzip a file than using subprocess.check_call?</p>
<pre><code>from subprocess import check_call
def gZipFile(fullFilePath)
check_call('gzip ' + fullFilePath)
</code></pre>
<p>Thanks!!</p> | 8,156,724 | 8 | 2 | null | 2011-11-16 18:25:41.267 UTC | 9 | 2022-07-21 02:54:15.09 UTC | null | null | null | null | 807,522 | null | 1 | 53 | python|gzip|subprocess | 107,741 | <p>Try this:</p>
<pre><code>check_call(['gzip', fullFilePath])
</code></pre>
<p>Depending on what you're doing with the data of these files, Skirmantas's link to <a href="http://docs.python.org/library/gzip.html">http://docs.python.org/library/gzip.html</a> may also be helpful. Note the examples near the bottom of the page. If you aren't needing to access the data, or don't have the data already in your Python code, executing gzip may be the cleanest way to do it so you don't have to handle the data in Python.</p> |
4,234,056 | Can we Execute SQL Queries in JQuery | <p>can we execute mySQL queries in jQuery Calllback functions & misc. functions</p>
<p>like simple query</p>
<pre><code>UPDATE EMPLOYEE SET PAY = PAY + 500 WHERE E_ID = '32'
</code></pre> | 4,234,069 | 4 | 2 | null | 2010-11-20 17:37:55.93 UTC | 2 | 2017-09-29 04:06:42.467 UTC | 2010-11-20 17:39:57.073 UTC | null | 13,249 | null | 158,455 | null | 1 | 5 | jquery|mysql | 55,029 | <p>The best thing you can do is to issue an AJAX request to a server and then execute this query using a server side code.</p>
<p>You can use <a href="http://api.jquery.com/jQuery.post/" rel="nofollow"><strong>jQuery.post()</strong></a> in this case.</p>
<p><strong><em>Edit</em></strong></p>
<p>To get an overview of AJAX Read <a href="http://www.tizag.com/ajaxTutorial/" rel="nofollow"><strong>this</strong></a></p>
<p>Read <a href="http://api.jquery.com/category/ajax/" rel="nofollow"><strong>this</strong></a> to get and overview of AJAX methods in jQuery.</p>
<p>Write a server side logic to execute the SQL command, in a page. Then using AJAX issue a request to that page.</p>
<p>Sample Code</p>
<pre><code>$(function(){
// Bind a click event to your anchor with id `updateSal`
$("#updateSal").click(function(){
// get your employeeID
var empID = "32";
// issue an AJAX request with HTTP post to your server side page.
//Here I used an aspx page in which the update login is written
$.post("test.aspx", { EmpID: empID},
function(data){
// callack function gets executed
alert("Return data" + data);
});
// to prevent the default action
return false;
});
});
</code></pre> |
4,701,108 | RSpec send_file testing | <p>How to test a controller action that sends a file?</p>
<p>If I do it with <code>controller.should_receive(:send_file)</code> test fails with "Missing template" because nothing gets rendered.</p> | 4,701,831 | 4 | 0 | null | 2011-01-15 17:43:54.697 UTC | 5 | 2020-02-06 21:47:44.057 UTC | null | null | null | null | 200,122 | null | 1 | 30 | ruby-on-rails|rspec|sendfile | 11,489 | <p>From <a href="http://www.ruby-forum.com/topic/179408" rel="noreferrer">Googling</a> <a href="http://www.ruby-forum.com/topic/181545" rel="noreferrer">around</a>, it appears that <code>render</code> will also be called at some point .. but with no template, will cause an error.</p>
<p>The solution seems to be to stub it out as well:</p>
<pre><code>controller.stub!(:render)</code></pre> |
4,429,966 | How to make a python script "pipeable" in bash? | <p>I wrote a script and I want it to be <em>pipeable</em> in bash. Something like:</p>
<pre><code>echo "1stArg" | myscript.py
</code></pre>
<p>Is it possible? How?</p> | 4,430,047 | 4 | 1 | null | 2010-12-13 14:45:37.45 UTC | 16 | 2022-07-07 09:51:28.223 UTC | 2016-10-10 11:33:43.663 UTC | null | 1,030,960 | null | 189,734 | null | 1 | 64 | python|pipe | 41,076 | <p>See this simple <code>echo.py</code>:</p>
<pre><code>import sys
if __name__ == "__main__":
for line in sys.stdin:
sys.stderr.write("DEBUG: got line: " + line)
sys.stdout.write(line)
</code></pre>
<p>running:</p>
<pre><code>ls | python echo.py 2>debug_output.txt | sort
</code></pre>
<p>output:</p>
<pre><code>echo.py
test.py
test.sh
</code></pre>
<p>debug_output.txt content:</p>
<pre><code>DEBUG: got line: echo.py
DEBUG: got line: test.py
DEBUG: got line: test.sh
</code></pre> |
4,708,754 | Optimising the Zend Framework | <p>I'm trying to get as much performance as I can out of my application, which uses the Zend Framework.</p>
<p>I'm considering using the Zend Server, with APC enabled. However, I need to know a few things first.</p>
<p>Is there any benefit of using Zend Server + Zend Framework, or should I just use any ordinary system to host this?</p>
<p>Shamil</p> | 4,718,334 | 5 | 5 | null | 2011-01-16 23:16:16.243 UTC | 11 | 2019-04-05 09:42:41.757 UTC | null | null | null | null | 114,865 | null | 1 | 7 | zend-framework|zend-server | 4,440 | <p>My tips for faster ZF (try from top to bottom):</p>
<h3>Optimize include path</h3>
<ul>
<li>zend path first</li>
<li>models next</li>
<li>rest at the end</li>
</ul>
<h3>Use PHP 5.5 with OPCache enabled [NEW]</h3>
<ul>
<li>I can't stress this enough</li>
<li>gains around 50%</li>
</ul>
<h3>Cache table metadata</h3>
<ul>
<li>should be cached even if no other caching is needed</li>
<li>one of our application performance improved by ~30% on Oracle server ;)</li>
</ul>
<h3>Favour viewHelpers over using action() <em>view helper</em></h3>
<ul>
<li>create view helper that access your model</li>
<li>or pass only the data from model and format them with view helpers</li>
</ul>
<h3>Use classmap autoloader</h3>
<ul>
<li>since ZF1.11</li>
<li>preferably with stripped require_once calls</li>
</ul>
<h3>Minimize path stacks</h3>
<ul>
<li>there are a lot of path stacks in ZF
<ul>
<li>form elements</li>
<li>view helpers </li>
<li>action helpers</li>
</ul></li>
<li>each path stack lookup means stat call = performance loss</li>
<li>default classes are more and more expensive with every path on stack</li>
</ul>
<h3>Strip require_once</h3>
<ul>
<li>strip require_once from Zend's classes in favour of autoloading <a href="http://framework.zend.com/manual/1.12/en/performance.classloading.html#performance.classloading.striprequires.sed" rel="nofollow">using find & sed</a></li>
</ul>
<h3>Favour render() over partial() view helper</h3>
<ul>
<li>no new view instance is created</li>
<li>you need to set variables outside the rendered view scope, inside the main view!</li>
<li>you can also replace <em>partialLoop()</em> with <em>foreach + render()</em></li>
</ul>
<h3>Cache anything possible</h3>
<ul>
<li>small chunks that require lot of work and change seldomly (like dynamic menus)</li>
<li>use profiler to find low-hanging fruit
<ul>
<li>what you <em>think</em> is slow may not really be so slow</li>
</ul></li>
<li>cache everything that can have cache set statically
<ul>
<li>see manual - <code>Zend_Locale::setCache(), Zend_Currency::setCache(), Zend_Db_Table::setDefaultMetadataCache(), configs...</code></li>
</ul></li>
</ul>
<h3>Never use <em>view helper</em> action() or <em>action helper</em> actionStack()</h3>
<ul>
<li>Never use them unless 100% needed - for example for complicated data output, but mind the performance loss they pose</li>
<li>They create whole new dispatch loop and are performance killers!</li>
</ul>
<h3>Disable viewRenderer</h3>
<ul>
<li><a href="http://till.klampaeckel.de/blog/archives/92-Zend-Framework-Slow-automatic-view-rendering.html" rel="nofollow">take care of view rendering yourself</a></li>
</ul>
<h3>Try my superlimunal plugin</h3>
<ul>
<li>it merges included classes to one long file to minimize stat calls</li>
<li>get if from <a href="https://github.com/tomasfejfar/ZF1-superluminal" rel="nofollow">GitHub</a>
<ul>
<li>it's port from <a href="https://github.com/EvanDotPro/EdpSuperluminal" rel="nofollow">ZF2 version from EDP</a></li>
<li>but beware - it's not tested in production yet, use with care</li>
</ul></li>
<li>measure performance gain
<ul>
<li>there was a loss for me on slow HDD and all ZF classes in it</li>
<li>try minimizing it with <a href="http://php.net/manual/en/function.php-strip-whitespace.php" rel="nofollow">strip whitespace function</a></li>
</ul></li>
</ul>
<h3>Server-side file minification</h3>
<ul>
<li>It makes sense for really big files - HDD is always the bottleneck</li>
<li>Even micro-optimization works fine sometimes
<ul>
<li>classmap with all ZF classes' paths is HUGE, striping whitespace and replacing long variables with <code>$a</code> and <code>$b</code> brought performance gain when having "dry" opcode cache and HDD under pressure.</li>
</ul></li>
</ul>
<p>Any opcode cache is of course a must have ;) (APC, ZendOptimizer, etc.)</p> |
4,830,164 | What is the best way to simulate a Click with MouseUp & MouseDown events or otherwise? | <p>In WPF most controls have <code>MouseUp</code> and <code>MouseDown</code> events (and the mouse-button-specific variations) but not a simple <code>Click</code> event that can be used right away. If you want to have a click-like behaviour using those events you need to handle both which i consider to be a bit of a pain.</p>
<p>The obvious problem is that you cannot simply omit the <code>MouseDown</code> event because if your click is started on another control and it is released over the control that only handles <code>MouseUp</code> your supposed click will fire while it really should not: Both <code>MouseUp</code> and <code>MouseDown</code> should occur over the same control.</p>
<p>So i would be interested in a more elegant solution to this general problem if there is any.</p>
<hr>
<p><strong>Notes:</strong> There are several good solutions to this as can be seen below, i chose to accept Rachel's answer because it seems to be well received, but additionally i'd like to add the following annotations:</p>
<p><a href="https://stackoverflow.com/questions/4830164/what-is-the-best-way-to-simulate-a-click-with-mouseup-mousedown-events-or-other/4831110#4831110">Rachel's button answer</a> is quite clean and straightforward, but you need to wrap your actual control in a button and in some cases you might not really consider your control to be a button just because it can be clicked (e.g. if it is more like a hyperlink), further you need to reference a template every time.</p>
<p><a href="https://stackoverflow.com/questions/4830164/what-is-the-best-way-to-simulate-a-click-with-mouseup-mousedown-events-or-other/4835678#4835678">Rick Sladkey's behaviour answer</a> more directly answers the original question of how to just simulate a click/make a control clickable, the drawback is that you need to reference <code>System.Windows.Interactivity</code> and like Rachel's solution it inflates the Xaml-code quite a bit.</p>
<p><a href="https://stackoverflow.com/questions/4830164/what-is-the-best-way-to-simulate-a-click-with-mouseup-mousedown-events-or-other/4831701#4831701">My attached event answer</a> has the advantage of being quite close to a normal click event in terms of Xaml-Markup which can be done with one attribute, the only problem i see with it is that the event-attachment in code is not cleanly encapsulated (if anyone knows a fix for that, please add a comment to the answer).</p> | 4,831,110 | 5 | 6 | null | 2011-01-28 15:50:22.163 UTC | 13 | 2014-04-24 14:17:47.487 UTC | 2017-05-23 12:33:56.653 UTC | null | -1 | null | 546,730 | null | 1 | 32 | wpf|controls|click|mouseevent | 15,455 | <p>I would use a <code>Button</code> control and overwrite the <code>Button.Template</code> to just show the content directly.</p>
<pre><code><ControlTemplate x:Key="ContentOnlyTemplate" TargetType="{x:Type Button}">
<ContentPresenter />
</ControlTemplate>
<Button Template="{StaticResource ContentOnlyTemplate}">
<Label Content="Test"/>
</Button>
</code></pre> |
4,126,811 | How do you track record relations in NoSQL? | <p>I am trying to figure out the equivalent of foreign keys and indexes in NoSQL KVP or Document databases. Since there are no pivotal tables (to add keys marking a relation between two objects) I am really stumped as to how you would be able to retrieve data in a way that would be useful for normal web pages.</p>
<p>Say I have a user, and this user leaves many comments all over the site. The only way I can think of to keep track of that users comments is to </p>
<ol>
<li>Embed them in the user object (which seems quite useless) </li>
<li>Create and maintain a <code>user_id:comments</code> value that contains a list of each comment's key [comment:34, comment:197, etc...] so that that I can fetch them as needed.</li>
</ol>
<p>However, taking the second example you will soon hit a brick wall when you use it for tracking other things like a key called "active_comments" which might contain 30 million ids in it making it <em>cost a TON</em> to query each page just to know some recent active comments. It also would be very prone to <em>race-conditions</em> as many pages might try to update it at the same time.</p>
<p><strong>How can I track relations like the following in a NoSQL database?</strong></p>
<ul>
<li>All of a user's comments</li>
<li>All active comments</li>
<li>All posts tagged with [keyword]</li>
<li>All students in a club - or all clubs a student is in</li>
</ul>
<p><em>Or am I thinking about this incorrectly?</em></p> | 4,210,561 | 5 | 4 | null | 2010-11-08 18:31:27.827 UTC | 48 | 2020-10-28 14:00:28.563 UTC | 2016-07-14 07:28:46.59 UTC | null | 364,274 | null | 99,923 | null | 1 | 138 | nosql|database-relations | 50,987 | <p>All the answers for how to store many-to-many associations in the "NoSQL way" reduce to the same thing: <strong>storing data redundantly.</strong></p>
<p>In NoSQL, you don't design your database based on the relationships between data entities. You design your database based on the queries you will run against it. Use the same criteria you would use to denormalize a relational database: if it's more important for data to have cohesion (think of values in a comma-separated list instead of a normalized table), then do it that way.</p>
<p>But this inevitably optimizes for one type of query (e.g. comments by any user for a given article) at the expense of other types of queries (comments for any article by a given user). If your application has the need for both types of queries to be equally optimized, you should not denormalize. And likewise, you should not use a NoSQL solution if you need to use the data in a relational way.</p>
<p>There is a risk with denormalization and redundancy that redundant sets of data will get out of sync with one another. This is called an <em>anomaly</em>. When you use a normalized relational database, the RDBMS can prevent anomalies. In a denormalized database or in NoSQL, it becomes your responsibility to write application code to prevent anomalies.</p>
<p>One might think that it'd be great for a NoSQL database to do the hard work of preventing anomalies for you. There is a paradigm that can do this -- the relational paradigm.</p> |
4,613,310 | How to call external url in jquery? | <p>I am trying to put comments on Facebook wall using jquery.</p>
<p>But my ajax call not alowing external url .</p>
<p>can anyone explain how can we use external url with jquery ?</p>
<p>below is my code :</p>
<pre><code>var fbUrl="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";
$.ajax({
url: fbURL ,
data: "message="+commentdata,
type: 'POST',
success: function (resp) {
alert(resp);
},
error: function(e){
alert('Error: '+e);
}
});
</code></pre>
<p>its giving xmlhtttprequest error.</p> | 4,613,640 | 7 | 1 | null | 2011-01-06 09:10:11.49 UTC | 9 | 2018-12-28 11:39:25.563 UTC | 2011-01-06 09:55:54.913 UTC | null | 80,111 | user319198 | null | null | 1 | 32 | jquery|ajax|cross-domain-policy | 164,025 | <p>All of these answers are wrong!</p>
<p>Like I said in my comment, the reason you're getting that error because the URL fails the "<a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">Same origin policy</a>", but you can still us the AJAX function to hit another domain, see <a href="https://stackoverflow.com/questions/3873636/no-response-from-mediawiki-api-using-jquery">Nick Cravers answer on this similar question</a>:</p>
<blockquote>
<p>You need to trigger JSONP behavior
with $.getJSON() by adding &callback=?
on the querystring, like this:</p>
<pre><code>$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?",
function(data) {
doSomethingWith(data);
});
</code></pre>
<p>You can test it here.</p>
<p>Without using JSONP you're hitting the
same-origin policy which is blocking
the XmlHttpRequest from getting any
data back.</p>
</blockquote>
<p>With this in mind, the follow code should work:</p>
<pre><code>var fbURL="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";
$.ajax({
url: fbURL+"&callback=?",
data: "message="+commentdata,
type: 'POST',
success: function (resp) {
alert(resp);
},
error: function(e) {
alert('Error: '+e);
}
});
</code></pre> |
4,079,920 | Is there a point to minifying PHP? | <p>I know you <em>can</em> minify PHP, but I'm wondering if there is any point. PHP is an interpreted language so will run a little slower than a compiled language. My question is: would clients see a visible speed improvement in page loads and such if I were to minify my PHP?</p>
<p>Also, is there a way to compile PHP or something similar?</p> | 4,079,952 | 8 | 2 | null | 2010-11-02 16:38:37.363 UTC | 32 | 2021-10-01 20:19:53.97 UTC | 2012-08-23 10:32:59.263 UTC | null | 383,609 | null | 383,609 | null | 1 | 107 | php|minify | 51,044 | <p>PHP is compiled into bytecode, which is then interpreted on top of something resembling a VM. Many other scripting languages follow the same general process, including Perl and Ruby. It's not really a traditional interpreted language like, say, BASIC.</p>
<p>There would be no effective speed increase if you attempted to "minify" the source. You would get a major increase by using a <a href="http://pecl.php.net/package/APC" rel="nofollow noreferrer">bytecode cache like APC</a>.</p>
<p>Facebook introduced a compiler named <a href="http://github.com/facebook/hiphop-php/wiki" rel="nofollow noreferrer">HipHop</a> that transforms PHP source into C++ code. Rasmus Lerdorf, one of the big PHP guys did a <a href="http://talks.php.net/show/digg" rel="nofollow noreferrer">presentation for Digg earlier this year</a> that covers the performance improvements given by HipHop. In short, it's not too much faster than optimizing code and using a bytecode cache. HipHop is overkill for the majority of users.</p>
<p>Facebook also recently unveiled <a href="https://www.facebook.com/note.php?note_id=10150415177928920" rel="nofollow noreferrer">HHVM</a>, a new virtual machine based on their work making HipHop. It's still rather new and it's not clear if it will provide a major performance boost to the general public.</p>
<p>Just to make sure it's stated expressly, please read <a href="http://talks.php.net/show/digg" rel="nofollow noreferrer">that presentation</a> in full. It points out numerous ways to benchmark and profile code and identify bottlenecks using tools like <a href="http://xdebug.org/" rel="nofollow noreferrer">xdebug</a> and <a href="http://pecl.php.net/package/xhprof" rel="nofollow noreferrer">xhprof</a>, also from Facebook.</p>
<hr />
<p><strong>2021 Update</strong></p>
<p>HHVM diverged away from vanilla PHP a couple versions ago. PHP 7 and 8 bring a whole bunch of amazing performance improvements that have pretty much closed the gap. You now no longer need to do weird things to get better performance out of PHP!</p>
<p>Minifying PHP source code continues to be useless for performance reasons.</p> |
4,250,149 | requestFeature() must be called before adding content | <p>I am trying to implement a custom titlebar:</p>
<p>Here is my Helper class:</p>
<pre><code>import android.app.Activity;
import android.view.Window;
public class UIHelper {
public static void setupTitleBar(Activity c) {
final boolean customTitleSupported = c.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
c.setContentView(R.layout.main);
if (customTitleSupported) {
c.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
}
}
}
</code></pre>
<p>Here is where I call it in onCreate():</p>
<pre><code>@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupUI();
}
private void setupUI(){
setContentView(R.layout.main);
UIHelper.setupTitleBar(this);
}
</code></pre>
<p>But I get the error:</p>
<pre><code>requestFeature() must be called before adding content
</code></pre> | 4,250,209 | 9 | 1 | null | 2010-11-22 20:54:06.757 UTC | 29 | 2022-07-07 15:05:56.69 UTC | 2014-01-28 10:03:09.57 UTC | null | 56,285 | null | 19,875 | null | 1 | 146 | android|android-layout|android-activity | 127,479 | <p>Well, just do what the error message tells you.</p>
<p>Don't call <code>setContentView()</code> before <code>requestFeature()</code>.</p>
<p><strong>Note:</strong></p>
<p>As said in comments, for both <code>ActionBarSherlock</code> and <code>AppCompat</code> library, it's necessary to call <code>requestFeature()</code> before <code>super.onCreate()</code></p> |
14,834,841 | When does 'quietly = TRUE' actually work in the require() function? | <p>I am trying to code a set of functions to check for missing R packages, and to install them if necessary. There's some good code to do that at StackOverflow: <a href="https://stackoverflow.com/questions/4090169/elegant-way-to-check-for-missing-packages-and-install-them?lq=1">start here</a>.</p>
<p>I would like to make the functions as silent as possible, especially since R returns even successful messages in red ink. Accordingly, I have tried to pass the <code>quietly = TRUE</code> argument to both <code>library</code> and <code>require</code>.</p>
<p>However, these options never seem to work:</p>
<pre><code># attempt to get a silent fail
require(xyz, quietly = TRUE)
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called ‘xyz’
</code></pre>
<p><strong>How can I get <code>require</code> to fail silently, and what am I not getting about the <code>quietly</code> option?</strong></p>
<p>The documentation says:</p>
<blockquote>
<p><code>quietly</code> a logical. If TRUE, no message confirming package loading is printed, and most often, no errors/warnings are printed if package loading fails.</p>
</blockquote>
<p>But it seems to me "most often" should be "almost never" in my personal experience. I would happily hear about your experience with that. Rationale: coding functions to help students.</p>
<hr>
<p><strong>Add.</strong> The same question applies to <code>quiet = TRUE</code> in <code>install.packages()</code>. It kills only the progress bar, but not the "downloaded binary packages are in" message (printed in black, yay!) that follows, even though it has no use to the median user.</p>
<hr>
<p><strong>Add.</strong> In case this might be of interest to anyone, the code so far:</p>
<pre><code>## getPackage(): package loader/installer
getPackage <- function(pkg, load = TRUE, silent = FALSE, repos = "http://cran.us.r-project.org") {
if(!suppressMessages(suppressWarnings(require(pkg, character.only = TRUE, quietly = TRUE)))) {
try(install.packages(pkg, repos = repos), silent = TRUE)
}
if(load) suppressPackageStartupMessages(library(pkg, character.only = TRUE, quietly = TRUE))
if(load & !silent) message("Loaded ", pkg)
}
## Not run:
x <- c("ggplot2", "devtools") # etc.
lapply(x, getPackage, silent = TRUE)
</code></pre>
<p>I'm thinking of just quitting the effort to use <code>quietly</code> in the function above, given that it does not seem to work when expected. I should probably ask the R userlists about that to get an explanation from the core devteam. The <code>suppressMessages(suppressWarnings(require(...)))</code> workaround can be unstable in my experience.</p> | 24,924,250 | 6 | 3 | null | 2013-02-12 14:29:54.377 UTC | 3 | 2021-05-23 04:08:36.287 UTC | 2017-05-23 11:54:05.047 UTC | null | -1 | null | 635,806 | null | 1 | 30 | r | 15,035 | <p>The simplest solution appears to be</p>
<pre><code>try(library(xyz), silent=TRUE)
</code></pre>
<p><code>require</code> is basically a wrapper around <code>tryCatch(library)</code>, so this just cuts out some extraneous code.</p> |
14,700,577 | Drawing transparent ShapeRenderer in libgdx | <p>I have a drawn a filled circle using ShapeRenderer and now I want to draw this circle as a transparent one. I am using the following code to do that: But the circle is not coming as transparent. Also, I checked th libgdx API and from the wiki, it says that, need to Create CameraStrategy. Has somebody faced similar issue ever before? If so, please give me some clues. Thanks in advance.</p>
<pre><code> Gdx.gl.glEnable(GL10.GL_BLEND);
Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
drawFilledCircle();
Gdx.gl.glDisable(GL10.GL_BLEND);
private void drawFilledCircle(){
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeType.FilledCircle);
shapeRenderer.setColor(new Color(0, 1, 0, 1));
shapeRenderer.filledCircle(470, 45, 10);
shapeRenderer.end();
}
</code></pre> | 14,721,570 | 4 | 2 | null | 2013-02-05 05:10:17.823 UTC | 9 | 2015-12-31 06:08:57.803 UTC | 2013-02-05 06:50:49.783 UTC | null | 527,617 | null | 527,617 | null | 1 | 44 | java|android|libgdx | 30,072 | <p>The following code is working for me in this case, maybe it will help someone else:</p>
<pre><code>Gdx.gl.glEnable(GL10.GL_BLEND);
Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeType.FilledCircle);
shapeRenderer.setColor(new Color(0, 1, 0, 0.5f));
shapeRenderer.filledCircle(470, 45, 10);
shapeRenderer.end();
Gdx.gl.glDisable(GL10.GL_BLEND);
</code></pre> |
14,465,668 | Elastic search, multiple indexes vs one index and types for different data sets? | <p>I have an application developed using the MVC pattern and I would like to index now multiple models of it, this means each model has a different data structure.</p>
<ul>
<li><p>Is it better to use mutliple indexes, one for each model or have a type within the same index for each model? Both ways would also require a different search query I think. I just started on this.</p></li>
<li><p>Are there differences performancewise between both concepts if the data set is small or huge?</p></li>
</ul>
<p>I would test the 2nd question myself if somebody could recommend me some good sample data for that purpose.</p> | 14,554,767 | 4 | 0 | null | 2013-01-22 18:40:36.683 UTC | 72 | 2017-03-20 21:48:19.833 UTC | 2013-07-23 09:50:26.53 UTC | null | 171,209 | null | 171,209 | null | 1 | 179 | database|search|elasticsearch | 49,906 | <p>There are different implications to both approaches. </p>
<p>Assuming you are using Elasticsearch's default settings, having 1 index for each model will significantly increase the number of your shards as 1 index will use 5 shards, 5 data models will use 25 shards; while having 5 object types in 1 index is still going to use 5 shards.</p>
<p>Implications for having each data model as index:</p>
<ul>
<li>Efficient and fast to search within index, as amount of data should be smaller in each shard since it is distributed to different indices.</li>
<li>Searching a combination of data models from 2 or more indices is going to generate overhead, because the query will have to be sent to more shards across indices, compiled and sent back to the user.</li>
<li>Not recommended if your data set is small since you will incur more storage with each additional shard being created and the performance gain is marginal.</li>
<li>Recommended if your data set is big and your queries are taking a long time to process, since dedicated shards are storing your specific data and it will be easier for Elasticsearch to process.</li>
</ul>
<p>Implications for having each data model as an object type within an index:</p>
<ul>
<li>More data will be stored within the 5 shards of an index, which means there is lesser overhead issues when you query across different data models but your shard size will be significantly bigger.</li>
<li>More data within the shards is going to take a longer time for Elasticsearch to search through since there are more documents to filter.</li>
<li>Not recommended if you know you are going through 1 terabytes of data and you are not distributing your data across different indices or multiple shards in your Elasticsearch mapping.</li>
<li>Recommended for small data sets, because you will not waste storage space for marginal performance gain since each shard take up space in your hardware.</li>
</ul>
<p>If you are asking what is too much data vs small data? Typically it depends on the processor speed and the RAM of your hardware, the amount of data you store within each variable in your mapping for Elasticsearch and your query requirements; using many facets in your queries is going to slow down your response time significantly. There is no straightforward answer to this and you will have to benchmark according to your needs.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.