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
18,028,706
PHP PDOException: "SQLSTATE[HY093]: Invalid parameter number"
<p>I'm getting the error "SQLSTATE[HY093]: Invalid parameter number" when I try to run the below function:</p> <pre><code>function add_persist($db, $user_id) { $hash = md5("per11".$user_id."sist11".time()); $future = time()+(60*60*24*14); $sql = "INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash"; $stm = $db-&gt;prepare($sql); $stm-&gt;execute(array(":user_id" =&gt; $user_id, ":hash" =&gt; $hash, ":expire" =&gt; $future)); return $hash; } </code></pre> <p>I feel like it's something simple that I'm just not catching. Any ideas?</p>
18,028,742
4
4
null
2013-08-03 02:35:10.95 UTC
6
2020-08-11 11:34:21.773 UTC
null
null
null
null
2,049,443
null
1
31
php|mysql|pdo
78,066
<p>Try:</p> <pre><code>$sql = &quot;INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash2&quot;; </code></pre> <p>and</p> <pre><code>$stm-&gt;execute( array(&quot;:user_id&quot; =&gt; $user_id, &quot;:hash&quot; =&gt; $hash, &quot;:expire&quot; =&gt; $future, &quot;:hash2&quot; =&gt; $hash) ); </code></pre> <p>Excerpt from the documentation (<a href="http://php.net/manual/en/pdo.prepare.php" rel="noreferrer">http://php.net/manual/en/pdo.prepare.php</a>):</p> <blockquote> <p>You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.</p> </blockquote>
18,023,870
java.lang.NoSuchMethodException: userAuth.User.<init>()
<p>I have the class with validation:</p> <pre><code>public class User { @Size(min=3, max=20, message="User name must be between 3 and 20 characters long") @Pattern(regexp="^[a-zA-Z0-9]+$", message="User name must be alphanumeric with no spaces") private String name; @Size(min=6, max=20, message="Password must be between 6 and 20 characters long") @Pattern(regexp="^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$", message="Password must contains at least one number") private String password; public User(String _name, String _password){ super(); name = _name; password = _password; } public String getName(){ return name; } public String getPassword(){ return password; } public void setPassword(String newPassword){ password = newPassword; } } </code></pre> <p>when I validate values, I got the message:</p> <pre><code>SEVERE: Servlet.service() for servlet osAppServlet threw exception java.lang.NoSuchMethodException: userAuth.User.&lt;init&gt;() </code></pre> <p>where is the problem?</p>
18,024,061
5
0
null
2013-08-02 18:35:21.727 UTC
4
2022-09-01 08:23:41.477 UTC
2013-08-02 18:44:59.167 UTC
null
1,115,554
null
1,062,103
null
1
55
java|spring|validation|hibernate-validator
100,388
<p>The message <code>java.lang.NoSuchMethodException: userAuth.User.&lt;init&gt;()</code> means that someone tried to call a constructor without any parameters. Adding a default constructor should solve this problem:</p> <pre><code>public class User { public User() { } .. } </code></pre>
17,779,293
CSS text-overflow: ellipsis; not working?
<p>I don't know why this simple CSS isn't working...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.app a { height: 18px; width: 140px; padding: 0; overflow: hidden; position: relative; margin: 0 5px 0 5px; text-align: center; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; color: #000; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="app"&gt; &lt;a href=""&gt;Test Test Test Test Test Test&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Should cut off around the 4th "Test"</p>
17,783,233
18
6
null
2013-07-22 03:01:43.197 UTC
161
2022-09-07 12:56:59.447 UTC
2019-01-07 21:26:58.003 UTC
null
1,850,382
null
1,850,382
null
1
571
overflow|ellipsis|css
576,372
<p><code>text-overflow:ellipsis;</code> only works when the following are true:</p> <ul> <li>The element's width must be constrained in <code>px</code> (pixels). Width in <code>%</code> (percentage) won't work.</li> <li>The element must have <code>overflow:hidden</code> and <code>white-space:nowrap</code> set.</li> </ul> <p>The reason you're having problems here is because the <code>width</code> of your <code>a</code> element isn't constrained. You do have a <code>width</code> setting, but because the element is set to <code>display:inline</code> (i.e. the default) it is ignoring it, and nothing else is constraining its width either.</p> <p>You can fix this by doing one of the following:</p> <ul> <li>Set the element to <code>display:inline-block</code> or <code>display:block</code> (probably the former, but depends on your layout needs).</li> <li>Set one of its container elements to <code>display:block</code> and give that element a fixed <code>width</code> or <code>max-width</code>.</li> <li>Set the element to <code>float:left</code> or <code>float:right</code> (probably the former, but again, either should have the same effect as far as the ellipsis is concerned).</li> </ul> <p>I'd suggest <code>display:inline-block</code>, since this will have the minimum collateral impact on your layout; it works very much like the <code>display:inline</code> that it's using currently as far as the layout is concerned, but feel free to experiment with the other points as well; I've tried to give as much info as possible to help you understand how these things interact together; a large part of understanding CSS is about understanding how various styles work together.</p> <p>Here's a snippet with your code, with a <code>display:inline-block</code> added, to show how close you were.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.app a { height: 18px; width: 140px; padding: 0; overflow: hidden; position: relative; display: inline-block; margin: 0 5px 0 5px; text-align: center; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; color: #000; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="app"&gt; &lt;a href=""&gt;Test Test Test Test Test Test&lt;/a&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Useful references:</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/white-space" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/white-space</a></li> </ul>
6,922,493
How to play the html5 video in IE8 Browsers
<p>I have develop a MVC3 Application in that i have use html5 video controls when i run the application it is playin Chrome but when i try to play in IE8 Browser it doesn't play the video just it show the white page only...How to play the video in all Browsers please help me..</p> <p>Here is my code what i did in my page</p> <pre><code>&lt;video controls="controls" poster="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" width="640" height="360"&gt; &lt;source src="../../Videos/Nenu Nuvvuantu - Orange - MyInfoland.mp4" type="video/mp4" /&gt; &lt;%-- &lt;source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm" /&gt;--%&gt; &lt;source src="../../Videos/Nenu Nuvvuantu - Orange - MyInfoland.ogv" type="video/ogv" /&gt; &lt;object type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" width="640" height="360"&gt; &lt;param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" /&gt; &lt;param name="allowFullScreen" value="true" /&gt; &lt;param name="wmode" value="transparent" /&gt; &lt;param name="flashVars" value="config={'playlist':['http%3A%2F%2Fsandbox.thewikies.com%2Fvfe-generator%2Fimages%2Fbig-buck-bunny_poster.jpg',{'url':'../../Videos/Nenu Nuvvuantu - Orange - MyInfoland.mp4','autoPlay':false}]}" /&gt; &lt;img alt="Big Buck Bunny" src="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" width="640" height="360" title="No video playback capabilities, please download the video below" /&gt; &lt;/object&gt; &lt;/video&gt; </code></pre>
6,922,624
3
1
null
2011-08-03 06:29:53.487 UTC
16
2016-10-19 08:51:55.2 UTC
2011-08-03 07:24:50.7 UTC
null
875,923
null
875,923
null
1
18
html5-video|telerik-mvc|asp.net-mvc-3
80,270
<p>There's a nice standard way of setting up HTML5 video with flash and other fallbacks.</p> <p>Please see <a href="http://sandbox.thewikies.com/vfe-generator/" rel="nofollow">Video for Everybody</a> for a nice generator of HTML5 tags with fallback options.</p> <p>Alternatively, here's <a href="http://videojs.com" rel="nofollow">another great library, with JS/CSS code to make it work consistently</a>.</p>
6,757,391
How to manually install software/plugin to Eclipse IDE?
<p>I have downloaded a RAR file from the following location, to be (manually) installed to Eclipse (Helios). How can I perform the manual installation?</p> <p><a href="http://sourceforge.net/projects/eclipsesql/files/SQL%20Explorer%20RCP%20%28exc%20JRE%29/3.6.1/sqlexplorer_rcp-3.6.1.macosx.cocoa.x86.tgz/download" rel="noreferrer">http://sourceforge.net/projects/eclipsesql/files/SQL%20Explorer%20RCP%20%28exc%20JRE%29/3.6.1/sqlexplorer_rcp-3.6.1.macosx.cocoa.x86.tgz/download</a></p>
6,757,629
3
1
null
2011-07-20 05:30:54.577 UTC
2
2014-05-09 15:26:05.193 UTC
null
null
null
null
475,247
null
1
19
eclipse
59,225
<p>From their website (http://www.sqlexplorer.org/):</p> <blockquote> <p>Eclipse Plugin</p> <p>Download</p> <p>Download the Eclipse SQL Explorer plugin and extract the zip file in your eclipse directory (requires Eclipse 3.3 or better). After restarting eclipse with the -clean option, a new SQL Explorer perspective should be available.</p> <p>Eclipse Update Site</p> <p>You can install and update Eclipse SQL Explorer via the eclipse update mechanism. The update site for Eclipse SQL Explorer is <a href="http://eclipsesql.sourceforge.net/" rel="nofollow">http://eclipsesql.sourceforge.net/</a></p> </blockquote> <p>I always go for the update site option if they present it, it's easier and lets you do updates easily. To use the update mechanism just select <em>Help > Insall New Software...</em> then enter the update site, press <em>Add</em> and go through the wizard.</p>
6,725,718
Android: Display Image from SD CARD
<p>This is driving me insane! Here's my code (I know this file exists):</p> <pre><code>File imageFile = new File("/sdcard/gallery_photo_4.jpg"); ImageView jpgView = (ImageView)findViewById(R.id.imageView); BitmapDrawable d = new BitmapDrawable(getResources(), imageFile.getAbsolutePath()); jpgView.setImageDrawable(d); </code></pre> <p>The error occurs on that last line (line 28, referenced below).</p> <p>Error output:</p> <pre><code>W/dalvikvm( 865): threadid=1: thread exiting with uncaught exception (group=0x4001d800) E/AndroidRuntime( 865): FATAL EXCEPTION: main E/AndroidRuntime( 865): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.camera/org.example.camera.Imgview}: java.lang.NullPointerException E/AndroidRuntime( 865): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) E/AndroidRuntime( 865): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) E/AndroidRuntime( 865): at android.app.ActivityThread.access$2300(ActivityThread.java:125) E/AndroidRuntime( 865): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) E/AndroidRuntime( 865): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime( 865): at android.os.Looper.loop(Looper.java:123) E/AndroidRuntime( 865): at android.app.ActivityThread.main(ActivityThread.java:4627) E/AndroidRuntime( 865): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 865): at java.lang.reflect.Method.invoke(Method.java:521) E/AndroidRuntime( 865): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) E/AndroidRuntime( 865): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) E/AndroidRuntime( 865): at dalvik.system.NativeStart.main(Native Method) E/AndroidRuntime( 865): Caused by: java.lang.NullPointerException E/AndroidRuntime( 865): at org.example.camera.Imgview.onCreate(Imgview.java:28) E/AndroidRuntime( 865): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) E/AndroidRuntime( 865): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) E/AndroidRuntime( 865): ... 11 more W/ActivityManager( 59): Force finishing activity org.example.camera/.Imgview </code></pre> <p>My layout looks like (probably not necessary):</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;ImageView android:id="@+id/imageView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scaleType="center"&gt; &lt;/ImageView&gt; &lt;/LinearLayout&gt; </code></pre> <p>Thank you very much for any help.</p>
6,725,793
4
2
null
2011-07-17 18:04:48.933 UTC
6
2015-07-01 08:40:30.727 UTC
null
null
null
null
548,170
null
1
15
android|android-sdcard|android-imageview
57,622
<p>I would rather use a <a href="http://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeFile%28java.lang.String%29"><code>BitmapFactory</code></a> to decode the Image from the file-path:</p> <pre><code>Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath()); jpgView.setImageBitmap(bitmap); </code></pre> <p>The Docs say:</p> <blockquote> <p>If the specified file name is null, or cannot be decoded into a bitmap, the function returns null.</p> </blockquote> <p>Can you check if the code works with another image and if you can open your image on your PC thought. Maybe the file is corrupt.</p>
23,872,946
Force NumPy ndarray to take ownership of its memory in Cython
<p>Following <a href="https://stackoverflow.com/a/18312855/396967">this answer to "Can I force a numpy ndarray to take ownership of its memory?"</a> I attempted to use the Python C API function <code>PyArray_ENABLEFLAGS</code> through Cython's NumPy wrapper and found it is not exposed.</p> <p>The following attempt to expose it manually (this is just a minimum example reproducing the failure)</p> <pre><code>from libc.stdlib cimport malloc import numpy as np cimport numpy as np np.import_array() ctypedef np.int32_t DTYPE_t cdef extern from "numpy/ndarraytypes.h": void PyArray_ENABLEFLAGS(np.PyArrayObject *arr, int flags) def test(): cdef int N = 1000 cdef DTYPE_t *data = &lt;DTYPE_t *&gt;malloc(N * sizeof(DTYPE_t)) cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &amp;N, np.NPY_INT32, data) PyArray_ENABLEFLAGS(arr, np.NPY_ARRAY_OWNDATA) </code></pre> <p>fails with a compile error:</p> <pre><code>Error compiling Cython file: ------------------------------------------------------------ ... def test(): cdef int N = 1000 cdef DTYPE_t *data = &lt;DTYPE_t *&gt;malloc(N * sizeof(DTYPE_t)) cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &amp;N, np.NPY_INT32, data) PyArray_ENABLEFLAGS(arr, np.NPY_ARRAY_OWNDATA) ^ ------------------------------------------------------------ /tmp/test.pyx:19:27: Cannot convert Python object to 'PyArrayObject *' </code></pre> <p><strong>My question:</strong> Is this the right approach to take in this case? If so, what am I doing wrong? If not, how do I force NumPy to take ownership in Cython, without going down to a C extension module?</p>
23,873,586
3
2
null
2014-05-26 15:00:15.99 UTC
11
2022-05-05 07:24:11.717 UTC
null
null
null
null
396,967
null
1
15
python|arrays|numpy|cython
4,472
<p>You just have some minor errors in the interface definition. The following worked for me:</p> <pre><code>from libc.stdlib cimport malloc import numpy as np cimport numpy as np np.import_array() ctypedef np.int32_t DTYPE_t cdef extern from "numpy/arrayobject.h": void PyArray_ENABLEFLAGS(np.ndarray arr, int flags) cdef data_to_numpy_array_with_spec(void * ptr, np.npy_intp N, int t): cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &amp;N, t, ptr) PyArray_ENABLEFLAGS(arr, np.NPY_OWNDATA) return arr def test(): N = 1000 cdef DTYPE_t *data = &lt;DTYPE_t *&gt;malloc(N * sizeof(DTYPE_t)) arr = data_to_numpy_array_with_spec(data, N, np.NPY_INT32) return arr </code></pre> <p>This is my <code>setup.py</code> file:</p> <pre><code>from distutils.core import setup, Extension from Cython.Distutils import build_ext ext_modules = [Extension("_owndata", ["owndata.pyx"])] setup(cmdclass={'build_ext': build_ext}, ext_modules=ext_modules) </code></pre> <p>Build with <code>python setup.py build_ext --inplace</code>. Then verify that the data is actually owned:</p> <pre><code>import _owndata arr = _owndata.test() print arr.flags </code></pre> <p>Among others, you should see <code>OWNDATA : True</code>.</p> <p>And <em>yes</em>, this is definitely the right way to deal with this, since <code>numpy.pxd</code> does exactly the same thing to export all the other functions to Cython.</p>
40,845,304
RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility
<p>I have this error for trying to load a saved SVM model. I have tried uninstalling sklearn, NumPy and SciPy, reinstalling the latest versions all-together again (using pip). I am still getting this error. Why?</p> <pre><code>In [1]: import sklearn; print sklearn.__version__ 0.18.1 In [3]: import numpy; print numpy.__version__ 1.11.2 In [5]: import scipy; print scipy.__version__ 0.18.1 In [7]: import pandas; print pandas.__version__ 0.19.1 In [10]: clf = joblib.load('model/trained_model.pkl') --------------------------------------------------------------------------- RuntimeWarning Traceback (most recent call last) &lt;ipython-input-10-5e5db1331757&gt; in &lt;module&gt;() ----&gt; 1 clf = joblib.load('sentiment_classification/model/trained_model.pkl') /usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/numpy_pickle.pyc in load(filename, mmap_mode) 573 return load_compatibility(fobj) 574 --&gt; 575 obj = _unpickle(fobj, filename, mmap_mode) 576 577 return obj /usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/numpy_pickle.pyc in _unpickle(fobj, filename, mmap_mode) 505 obj = None 506 try: --&gt; 507 obj = unpickler.load() 508 if unpickler.compat_mode: 509 warnings.warn("The file '%s' has been generated with a " /usr/lib/python2.7/pickle.pyc in load(self) 862 while 1: 863 key = read(1) --&gt; 864 dispatch[key](self) 865 except _Stop, stopinst: 866 return stopinst.value /usr/lib/python2.7/pickle.pyc in load_global(self) 1094 module = self.readline()[:-1] 1095 name = self.readline()[:-1] -&gt; 1096 klass = self.find_class(module, name) 1097 self.append(klass) 1098 dispatch[GLOBAL] = load_global /usr/lib/python2.7/pickle.pyc in find_class(self, module, name) 1128 def find_class(self, module, name): 1129 # Subclasses may override this -&gt; 1130 __import__(module) 1131 mod = sys.modules[module] 1132 klass = getattr(mod, name) /usr/local/lib/python2.7/dist-packages/sklearn/svm/__init__.py in &lt;module&gt;() 11 # License: BSD 3 clause (C) INRIA 2010 12 ---&gt; 13 from .classes import SVC, NuSVC, SVR, NuSVR, OneClassSVM, LinearSVC, \ 14 LinearSVR 15 from .bounds import l1_min_c /usr/local/lib/python2.7/dist-packages/sklearn/svm/classes.py in &lt;module&gt;() 2 import numpy as np 3 ----&gt; 4 from .base import _fit_liblinear, BaseSVC, BaseLibSVM 5 from ..base import BaseEstimator, RegressorMixin 6 from ..linear_model.base import LinearClassifierMixin, SparseCoefMixin, \ /usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py in &lt;module&gt;() 6 from abc import ABCMeta, abstractmethod 7 ----&gt; 8 from . import libsvm, liblinear 9 from . import libsvm_sparse 10 from ..base import BaseEstimator, ClassifierMixin __init__.pxd in init sklearn.svm.libsvm (sklearn/svm/libsvm.c:10207)() RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 80 </code></pre> <p><strong>UPDATE:</strong> OK, by following <a href="https://stackoverflow.com/questions/25752444/scipy-error-numpy-dtype-size-changed-may-indicate-binary-incompatibility-and">here</a>, and</p> <pre><code>pip uninstall -y scipy scikit-learn pip install --no-binary scipy scikit-learn </code></pre> <p>The error has now gone, though I still have no idea why it occurred in the first place...</p>
40,846,742
10
5
null
2016-11-28 13:17:48.93 UTC
32
2021-02-08 22:30:33.607 UTC
2018-08-02 11:12:11.03 UTC
null
1,332,370
null
3,319,713
null
1
168
python|numpy|scikit-learn
119,049
<p>According to <a href="https://github.com/numpy/numpy/pull/432" rel="noreferrer">MAINT: silence Cython warnings about changes dtype/ufunc size. - numpy/numpy</a>:</p> <blockquote> <p>These warnings are visible whenever you import scipy (or another package) that was compiled against an older numpy than is installed.</p> </blockquote> <p>and the checks are inserted by Cython (hence are present in any module compiled with it).</p> <p>Long story short, <strong>these warnings should be benign in the particular case of <code>numpy</code></strong>, and <strong>these messages are filtered out since <code>numpy 1.8</code></strong> (the branch this commit went onto). While <a href="http://scikit-learn.org/stable/install.html" rel="noreferrer"><code>scikit-learn 0.18.1</code> is compiled against <code>numpy 1.6.1</code></a>.</p> <p><strong>To filter these warnings yourself</strong>, you can do the same <a href="https://github.com/numpy/numpy/pull/432/commits/170ed4e33d6196d724dc18ddcd42311c291b4587?diff=split" rel="noreferrer">as the patch does</a>:</p> <pre><code>import warnings warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") </code></pre> <p>Of course, <strong>you can just recompile all affected modules from source against your local <code>numpy</code></strong> with <code>pip install --no-binary :all:</code>¹ <strong>instead</strong> if you have the <s>balls</s> tools for that.</p> <hr> <p>Longer story: the patch's proponent <a href="https://github.com/numpy/numpy/pull/432#issuecomment-8401294" rel="noreferrer">claims</a> there should be no risk specifically with <code>numpy</code>, and 3rd-party packages are intentionally built against older versions:</p> <blockquote> <p>[Rebuilding everything against current numpy is] not a feasible solution, and certainly shouldn't be necessary. Scipy (as many other packages) is compatible with a number of versions of numpy. So when we distribute scipy binaries, we build them against the lowest supported numpy version (1.5.1 as of now) and they work with 1.6.x, 1.7.x and numpy master as well.</p> <p>The real correct would be for Cython only to issue warnings when the size of dtypes/ufuncs has changes in a way that breaks the ABI, and be silent otherwise.</p> </blockquote> <p>As a result, Cython's devs <a href="http://thread.gmane.org/gmane.comp.python.cython.devel/14352/focus=14354" rel="noreferrer">agreed to trust the numpy team with maintaining binary compatibility by hand</a>, so we can probably expect that using versions with breaking ABI changes would yield a specially-crafted exception or some other explicit show-stopper.</p> <hr> <p>¹<sub>The previously available <code>--no-use-wheel</code> option has been removed <a href="https://github.com/pypa/pip/commit/95b9541ed4b73632a53c2bc192144bb9e9af1c6b" rel="noreferrer">since <code>pip 10.0.0</code></a>.</sub></p>
926,319
jQuery - remove table row <tr> by clicking a <td>
<p>I am making a table in which you can add aditional rows. When you add a row you can either save it or cancel it, by clicking cancel the row will be removed. It works with one row but when I create like six of them and click cancel the selected row wont be removed but the last row will. Here my Code so far. Does anyone know what I'm doing wrong? </p> <pre><code>&lt;head&gt; &lt;script src="../jquery.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $(".edit").click(function() { var id = $(this).attr("id"); alert("edit "+id); }); $(".delete").click(function() { var id = $(this).attr("id"); alert("delete "+id); }); $("#newbutton").click(function() { var randomnumber=Math.floor(Math.random()*100); $("tr:last").after("&lt;tr id="+randomnumber+"&gt;&lt;td&gt;&lt;form&gt;&lt;input style='width: 80%'&gt;&lt;/form&gt;&lt;/td&gt;&lt;td class=ok&gt;OK&lt;/td&gt;&lt;td id="+randomnumber+" class=cancel&gt;Cancel&lt;/td&gt;&lt;/tr&gt;").ready(function() { $("tr td .cancel").click(function() { $(this).remove(); }); $(".ok").click(function() { alert("OK!"); }); }); }) }); &lt;/script&gt; &lt;/head&gt; &lt;table border=1 id=table&gt; &lt;tr&gt;&lt;th&gt;Name&lt;/th&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Bombai&lt;/td&gt;&lt;td id=1 class=edit&gt;edit&lt;/td&gt;&lt;td id=1 class=delete&gt;delete&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;London&lt;/td&gt;&lt;td id=2 class=edit&gt;edit&lt;/td&gt;&lt;td id=2 class=delete&gt;delete&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Rom&lt;/td&gt;&lt;td id=3 class=edit&gt;edit&lt;/td&gt;&lt;td id=3 class=delete&gt;delete&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt;&lt;label id=newbutton&gt;New Place&lt;/label&gt; </code></pre>
926,363
7
2
null
2009-05-29 14:38:12.327 UTC
2
2019-04-23 08:59:08.09 UTC
null
null
null
null
114,338
null
1
16
jquery
70,830
<p>Since you are dynamically adding rows to the DOM I'd suggest you use the <strong><a href="http://docs.jquery.com/Events/live" rel="noreferrer">live</a></strong> function:</p> <pre><code>$("tr td .cancel").live("click", function(){ $(this).parent("tr:first").remove() }) </code></pre>
922,898
Embedding attached images in HTML emails
<p>If I attach an image to an email, how can I place it in the HTML content? I tried just using the filename as the image source but that doesn't seem to work.</p>
922,901
7
1
null
2009-05-28 20:07:16.467 UTC
8
2019-04-12 09:03:16.51 UTC
null
null
null
null
83,358
null
1
20
email|mime
61,982
<p>Be more specific on how you build the HTML mail message.</p> <p>The result will be a multipart-MIME message with a text/html part (if you really do it right with an alternate part of type text/plain) and several images, which are then referenced from within the HTML.</p> <p>See <a href="http://www.faqs.org/rfcs/rfc1873.html" rel="noreferrer">RFC 1813</a> and <a href="http://www.faqs.org/rfcs/rfc2387.html" rel="noreferrer">RFC 2378</a> for more information about content-id in mixed MIME and related data (referred by CID in the HTML source).</p>
352,885
Dependency injection in C++
<p>This is also a question that I asked in a comment in one of Miško Hevery's <a href="http://misko.hevery.com/2008/11/11/clean-code-talks-dependency-injection/" rel="noreferrer">google talks</a> that was dealing with dependency injection but it got buried in the comments.</p> <p>I wonder how can the factory / builder step of wiring the dependencies together can work in C++.</p> <p>I.e. we have a class A that depends on B. The builder will allocate B in the heap, pass a pointer to B in A's constructor while also allocating in the heap and return a pointer to A.</p> <p>Who cleans up afterwards? Is it good to let the builder clean up after it's done? It seems to be the correct method since in the talk it says that the builder should setup objects that are expected to have the same lifetime or at least the dependencies have longer lifetime (I also have a question on that). What I mean in code:</p> <pre><code>class builder { public: builder() : m_ClassA(NULL),m_ClassB(NULL) { } ~builder() { if (m_ClassB) { delete m_ClassB; } if (m_ClassA) { delete m_ClassA; } } ClassA *build() { m_ClassB = new class B; m_ClassA = new class A(m_ClassB); return m_ClassA; } }; </code></pre> <p>Now if there is a dependency that is expected to last longer than the lifetime of the object we are injecting it into (say ClassC is that dependency) I understand that we should change the build method to something like:</p> <pre><code>ClassA *builder::build(ClassC *classC) { m_ClassB = new class B; m_ClassA = new class A(m_ClassB, classC); return m_ClassA; } </code></pre> <p>What is your preferred approach?</p>
352,972
8
3
null
2008-12-09 14:26:17.52 UTC
14
2016-03-03 13:53:10.483 UTC
null
null
null
YoP
6,403
null
1
26
c++|unit-testing|dependency-injection
22,689
<p>This talk is about Java and dependency injection.<br></p> <p>In C++ we try <b>NOT</b> to pass RAW pointers around. This is because a RAW pointer have no ownership semantics associated with it. If you have no ownership then we don't know who is responsible for cleaning up the object.</p> <p>I find that most of the time dependency injection is done via references in C++.<br> In the rare cases where you must use pointers, wrap them in <a href="http://www.cplusplus.com/reference/memory/auto_ptr/" rel="nofollow noreferrer">std::unique_ptr&lt;></a> or <a href="http://www.cplusplus.com/reference/memory/shared_ptr/" rel="nofollow noreferrer">std::shared_ptr&lt;></a> depending on how you want to manage ownership.<br> In case you cannot use C++11 features, use std::auto_ptr&lt;> or boost::shared_ptr&lt;>.</p> <p>I would also point out that C++ and Java styles of programming are now so divergent that applying the style of one language to the other will inevitably lead to disaster. </p>
1,302,026
What does "Method '~' of object '~' failed" at runtime mean?
<p>I'm trying to run a legacy VB6 application on my desktop (it doesn't have a user interface, being a command-line app), and when I do, I get a message box saying</p> <pre><code>Run-time error '4099': Method '~' of object '~' failed </code></pre> <p>This means nothing to me; does anyone have an idea what is going wrong?</p>
1,302,240
9
2
null
2009-08-19 19:07:33.247 UTC
5
2021-09-08 11:06:41.23 UTC
2020-02-10 14:45:48.7 UTC
null
3,195,477
null
16,964
null
1
35
com|vb6
84,329
<p>That can happen when supporting libraries (dlls or ocxs) are not registered properly or the versions of the installed libraries are different (and incompatible) with the version the app was compiled against originally. </p> <p>Make sure all dependent libraries are registered and the proper version. </p> <p>You may have to recompile the app to make it work with newer versions of the supporting libraries.</p>
175,381
How to edit CSS style of a div using C# in .NET
<p>I'm trying to grab a div's ID in the code behind (C#) and set some css on it. Can I grab it from the DOM or do I have to use some kind of control?</p> <pre><code>&lt;div id="formSpinner"&gt; &lt;img src="images/spinner.gif" /&gt; &lt;p&gt;Saving...&lt;/p&gt; &lt;/div&gt; </code></pre>
175,475
9
3
null
2008-10-06 17:46:41.903 UTC
4
2013-01-15 20:08:09.797 UTC
2010-09-04 00:06:43.967 UTC
null
7,872
Jon Smock
25,538
null
1
46
c#|.net|css
143,184
<p>Add the <code>runat="server"</code> attribute to it so you have:</p> <pre><code>&lt;div id="formSpinner" runat="server"&gt; &lt;img src="images/spinner.gif"&gt; &lt;p&gt;Saving...&lt;/p&gt; &lt;/div&gt; </code></pre> <p>That way you can access the class attribute by using:</p> <pre><code>formSpinner.Attributes["class"] = "classOfYourChoice"; </code></pre> <p>It's also worth mentioning that the <code>asp:Panel</code> control is virtually synonymous (at least as far as rendered markup is concerned) with <code>div</code>, so you could also do:</p> <pre><code>&lt;asp:Panel id="formSpinner" runat="server"&gt; &lt;img src="images/spinner.gif"&gt; &lt;p&gt;Saving...&lt;/p&gt; &lt;/asp:Panel&gt; </code></pre> <p>Which then enables you to write:</p> <pre><code>formSpinner.CssClass = "classOfYourChoice"; </code></pre> <p>This gives you more defined access to the property and there are others that may, or may not, be of use to you.</p>
218,912
Linux command (like cat) to read a specified quantity of characters
<p>Is there a command like <code>cat</code> in linux which can return a specified quantity of characters from a file?</p> <p>e.g., I have a text file like:</p> <pre><code>Hello world this is the second line this is the third line </code></pre> <p>And I want something that would return the first 5 characters, which would be "hello".</p> <p>thanks</p>
218,940
9
1
null
2008-10-20 15:52:26.467 UTC
25
2020-04-19 00:47:44.847 UTC
2009-07-05 11:42:35.203 UTC
null
12,855
pbreault
2,011
null
1
136
linux|command-line
149,843
<p><code>head</code> works too:</p> <pre><code>head -c 100 file # returns the first 100 bytes in the file </code></pre> <p>..will extract the first 100 bytes and return them. </p> <p>What's nice about using <code>head</code> for this is that the syntax for <code>tail</code> matches:</p> <pre><code>tail -c 100 file # returns the last 100 bytes in the file </code></pre> <p>You can combine these to get ranges of bytes. For example, to get the <em>second</em> 100 bytes from a file, read the first 200 with <code>head</code> and use tail to get the last 100:</p> <pre><code>head -c 200 file | tail -c 100 </code></pre>
304,816
Most efficient way to append arrays in C#?
<p>I am pulling data out of an old-school ActiveX in the form of arrays of doubles. I don't initially know the final number of samples I will actually retrieve.</p> <p>What is the most efficient way to concatenate these arrays together in C# as I pull them out of the system?</p>
304,821
11
2
null
2008-11-20 09:54:28.653 UTC
10
2022-02-04 06:20:31.407 UTC
2008-11-21 14:21:52.687 UTC
Constantin
20,310
Huck
12,525
null
1
68
c#|arrays|memory-management
153,583
<p>You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a <code>List&lt;T&gt;</code> which can grow as it needs to.</p> <p>Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.</p> <p>See <a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/arrays-considered-somewhat-harmful" rel="nofollow noreferrer">Eric Lippert's blog post on arrays</a> for more detail and insight than I could realistically provide :)</p>
526,294
How might I force a floating DIV to match the height of another floating DIV?
<p>My HTML code is just dividing the pages into two columns, 65%,35% respectively.</p> <pre><code>&lt;div style="float : left; width :65%; height:auto;background-color:#FDD017;"&gt; &lt;div id="response"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div style="float : left; width :35%;height:auto; background-color:#FDD017;"&gt; &lt;div id="note"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>In the <code>response</code> <code>div</code>, I have variable data; in the <code>note</code> <code>div</code>, I have fixed data. Even though the two <code>div</code>s have two different sets of data, I need them to display with the same height so that the background colors appear to fill a box containing both. Naturally, the problem is the <code>response</code> <code>div</code>, as its height varies depending on the amount of data currently being displayed within it.</p> <p>How might I ensure that the height of the two columns are always equal?</p>
526,303
11
0
null
2009-02-08 20:20:22.147 UTC
39
2016-01-13 00:49:44.327 UTC
2009-02-08 20:30:54.087 UTC
Shog9
811
venkatachalam
44,984
null
1
68
html|css|height
123,061
<p>Wrap them in a containing div with the background color applied to it, and have a clearing div after the 'columns'.</p> <pre><code>&lt;div style="background-color: yellow;"&gt; &lt;div style="float: left;width: 65%;"&gt;column a&lt;/div&gt; &lt;div style="float: right;width: 35%;"&gt;column b&lt;/div&gt; &lt;div style="clear: both;"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <hr> <p>Updated to address some comments and my own thoughts:</p> <p>This method works because its essentially a simplification of your problem, in this somewhat 'oldskool' method I put two columns in followed by an empty clearing element, the job of the clearing element is to tell the parent (with the background) this is where floating behaviour ends, this allows the parent to essentially render 0 pixels of height at the position of the clear, which will be whatever the highest priorly floating element is.</p> <p>The reason for this is to ensure the parent element is as tall as the tallest column, the background is then set on the parent to give the appearance that both columns have the same height.</p> <p>It should be noted that this technique is 'oldskool' because the better choice is to trigger this height calculation behaviour with something like <a href="http://www.webtoolkit.info/css-clearfix.html" rel="noreferrer">clearfix</a> or by simply having overflow: hidden on the parent element.</p> <p>Whilst this works in this limited scenario, if you wish for each column to look visually different, or have a gap between them, then setting a background on the parent element won't work, there is however a trick to get this effect.</p> <p>The trick is to add bottom padding to all columns, to the max amount of size you expect that could be the difference between the shortest and tallest column, if you can't work this out then pick a large figure, you then need to add a negative bottom margin of the same number.</p> <p>You'll need overflow hidden on the parent object, but the result will be that each column will request to render this additional height suggested by the margin, but not actually request layout of that size (because the negative margin counters the calculation). </p> <p>This will render the parent at the size of the tallest column, whilst allowing all the columns to render at their height + the size of bottom padding used, if this height is larger than the parent then the rest will simply clip off.</p> <pre><code>&lt;div style="overflow: hidden;"&gt; &lt;div style="background: blue;float: left;width: 65%;padding-bottom: 500px;margin-bottom: -500px;"&gt;column a&lt;br /&gt;column a&lt;/div&gt; &lt;div style="background: red;float: right;width: 35%;padding-bottom: 500px;margin-bottom: -500px;"&gt;column b&lt;/div&gt; &lt;/div&gt; </code></pre> <p>You can see an example of this technique on the <a href="http://www.bowers-wilkins.com/Speakers/Home_Audio/Nautilus/Overview.html" rel="noreferrer">bowers and wilkins website</a> (see the four horizontal spotlight images the bottom of the page).</p>
89,909
How do I verify that a string only contains letters, numbers, underscores and dashes?
<p>I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.</p>
89,919
11
1
null
2008-09-18 04:04:58.17 UTC
25
2019-05-15 11:44:16.36 UTC
2017-02-05 13:23:49.183 UTC
Marcel Levy
724,176
Ethan Post
4,527
null
1
96
python|regex|string
153,180
<p>A regular expression will do the trick with very little code:</p> <pre><code>import re ... if re.match("^[A-Za-z0-9_-]*$", my_little_string): # do something here </code></pre>
259,660
Painless 'Analysis of Algorithms' Training?
<p>I had a painful experience with the "Analysis of Algorithms" classes back in college but have recently found a need for it in the <em>real world</em>. -- Anyway, I'm looking for a simple-yet-effective crash course. Any ideas?</p> <p><em>Related Sidenote:</em> It sure would be nice if there were a "Cartoon Guide to Algorithm Analysis", taught by Dilbert.</p> <p><strong>UPDATE:</strong> A very similar question can be found at: <a href="https://stackoverflow.com/questions/366418/how-to-get-started-on-algorithms">How to get started on ALGORITHMS?</a></p>
259,667
12
1
null
2008-11-03 19:30:19.707 UTC
23
2012-08-29 04:32:01.847 UTC
2017-05-23 12:33:54.23 UTC
Nate
-1
Nate
11,760
null
1
17
algorithm
6,887
<p>There are a lot of good books on the subject. I like <a href="https://rads.stackoverflow.com/amzn/click/com/020140009X" rel="noreferrer" rel="nofollow noreferrer">An Introduction to the Analysis of Algorithms</a>. Also check out the algorithms course on <a href="http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-046JFall-2005/CourseHome/" rel="noreferrer">MIT OpenCourseWare</a> (using <a href="https://rads.stackoverflow.com/amzn/click/com/0262032937" rel="noreferrer" rel="nofollow noreferrer">CLRS</a> as the course text). It's a little bit deep, but having it online allows you to go at your own pace.</p> <p>A couple of other books that I've started reading recently are <a href="http://oreilly.com/catalog/9780596516246/" rel="noreferrer">Algorithms in a Nutshell</a> and the <a href="https://rads.stackoverflow.com/amzn/click/com/0387948600" rel="noreferrer" rel="nofollow noreferrer">Algorithm Design Manual</a>. They both take a lighter approach than most algorithms books. Instead of heavy math and formal proofs these books give you realistic problem statements and show you the steps taken to refine an algorithm. They also show you how to <em>estimate</em> and <em>measure</em> the complexity of a solution. I would highly recommend either book.</p>
1,014,766
jQuery UI Calendar displays too large, would like the demo size?
<p>So I downloaded a custom themed UI for jQuery and added the calendar control to my site (Example: <a href="http://jqueryui.com/demos/datepicker/" rel="noreferrer">link text</a>). In the example it shows/displays the size I would like but on my webpage it's about twice the size. why??? </p> <p>I do have a ton of other CSS but I don't have control over the look and feel of the page (Can't touch current CSS, MEH!!). Is there a way to get the demo look on my site?</p> <p>I think this is the code that jQuery UI has that might be complicating things</p> <pre><code>/* Component containers ----------------------------------*/ .ui-widget { font-family: Arial, Helvetica, Verdana, sans-serif; font-size: 1.1em; } .ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Arial, Helvetica, Verdana, sans-serif; font-size: 1em; } .ui-widget-content { border: 1px solid #B9C4CE; background: #ffffff url(../images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x; color: #616161; } .ui-widget-content a { color: #616161; } .ui-widget-header { border: 1px solid #467AA7; background: #467AA7 url(../images/ui-bg_highlight-soft_75_467AA7_1x100.png) 50% 50% repeat-x; color: #fff; font-weight: bold; } .ui-widget-header a { color: #fff; } </code></pre> <p>It's part of the Custom UI CSS</p>
1,028,369
12
3
null
2009-06-18 19:40:09.017 UTC
7
2017-02-25 22:21:33.123 UTC
2017-02-25 22:21:33.123 UTC
null
1,857,295
null
93,966
null
1
35
jquery|user-interface|jquery-ui
35,914
<p>I figured it out. It was the font size that was throwing the whole thing off. I added this tag to correctly display the size I wanted:</p> <pre class="lang-css prettyprint-override"><code>#ui-datepicker-div { font-size: 12px; } </code></pre> <p>Works great if anyone else needs something like this</p>
482,763
JQuery to check for duplicate ids in a DOM
<p>I'm writing applications with ASP.NET MVC. In contrast to traditional ASP.NET you're a lot more responsible for creating all the ids in your generated page. ASP.NET would give you nasty, but unique ids.</p> <p>I'd like to add a quick little jQuery script to check my document for duplicate ids. They may be ids for DIVS, images, checkboxes, buttons etc.</p> <pre><code>&lt;div id="pnlMain"&gt; My main panel &lt;/div&gt; &lt;div id="pnlMain"&gt; Oops we accidentally used the same ID &lt;/div&gt; </code></pre> <p>I'm looking for a set and forget type utility that'll just warn me when I do something careless.</p> <p>Yes i'd be using this only during testing, and alternatives (such as firebug plugins) are welcome too. </p>
509,965
12
0
null
2009-01-27 09:24:30.777 UTC
59
2021-10-18 05:40:11.247 UTC
2009-02-04 05:08:55.493 UTC
Simon
16,940
Simon
16,940
null
1
111
jquery|dom
54,131
<p>The following will log a warning to the console:</p> <pre><code>// Warning Duplicate IDs $('[id]').each(function(){ var ids = $('[id="'+this.id+'"]'); if(ids.length&gt;1 &amp;&amp; ids[0]==this) console.warn('Multiple IDs #'+this.id); }); </code></pre>
312,170
Is VARCHAR like totally 1990s?
<ol> <li>VARCHAR does not store Unicode characters.</li> <li>NVARCHAR does store Unicode characters.</li> <li>Today's applications should always be Unicode compatible.</li> <li>NVARCHAR takes twice the amount of space to store it.</li> <li>Point 4 doesn't matter because storage space is extremely inexpensive.</li> </ol> <p>Ergo: When designing SQL Server databases today, one should always use NVARCHAR.</p> <p>Is this sound reasoning? Does anyone disagree with any of the premises? Are there any reasons to choose VARCHAR over NVARCHAR today?</p>
312,233
14
2
null
2008-11-23 05:44:56.16 UTC
7
2012-08-29 03:50:14.33 UTC
2008-11-24 06:08:13.413 UTC
doofledorfer
31,641
Edward Tanguay
4,639
null
1
46
sql-server|nvarchar
10,951
<p>You match the datatype with the data that will be stored in the column. By a similar argument you could say why not store all data in NVARCHAR columns, because numbers and dates can be represented as strings of digits.</p> <p>If the best match for the data that will be stored in the column is VARCHAR, then use it.</p>
1,080,026
Is there a map without result in python?
<p>Sometimes, I just want to execute a function for a list of entries -- eg.:</p> <pre><code>for x in wowList: installWow(x, 'installed by me') </code></pre> <p>Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:</p> <pre><code>map(lambda x: installWow(x, 'installed by me'), wowList) </code></pre> <p>But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.</p> <p>(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)</p>
47,193,484
16
4
null
2009-07-03 16:20:11.683 UTC
8
2022-02-28 21:01:52.927 UTC
null
null
null
null
122,012
null
1
32
python|iteration
20,247
<p>You can use the built-in <code>any</code> function to apply a function <strong>without return statement</strong> to any item returned by a generator without creating a list. This can be achieved like this:</p> <pre><code>any(installWow(x, 'installed by me') for x in wowList) </code></pre> <p>I found this the most concise idom for what you want to achieve.</p> <p>Internally, the <code>installWow</code> function does return <code>None</code> which evaluates to <code>False</code> in logical operations. <code>any</code> basically applies an <code>or</code> reduction operation to all items returned by the generator, which are all <code>None</code> of course, so it has to iterate over all items returned by the generator. In the end it does return <code>False</code>, but that doesn't need to bother you. The good thing is: no list is created as a side-effect.</p> <p>Note that this only works as long as your function returns something that evaluates to <code>False</code>, e.g., <code>None</code> or 0. If it does return something that evaluates to <code>True</code> at some point, e.g., <code>1</code>, it will not be applied to any of the remaining elements in your iterator. To be safe, use this idiom mainly for functions without return statement.</p>
865,987
Do I need to heartbeat to keep a TCP connection open?
<p>I have two components that that communicate via TCP/IP. Component A acts as a server/listener and Component B is the client. The two should communicate as quickly as possible. There can only ever be one connection at any time (though that is aside to this question). A senior developer at my company has said I need to use application level heartbeats between the two components to ensure the connection stays open. </p> <p>I thought the connection stays open with TCP/IP but I've read a number of blogs/sites saying it's pretty standard practice to heartbeat between these applications. </p> <p>I know part of the reason component A heartbeats component B is so it can inform support if there are communications problems with component B (either the link is down or component B is not running). Are heartbeats needed for any other reason? Such as to ensure there is frequently something "in the pipe" to keep it open?</p> <p>Component A currently heartbeats component B every 20 seconds and closes the connection if nothing is received back from component B in 120 seconds. It then resumes listening for connections under the assumption that component B will periodically try a reconnect if the link is broken. This works successfully. </p> <p>To reiterate my question: Are heartbeats necessary to keep a TCP/IP connection alive?</p>
866,003
16
3
null
2009-05-14 21:44:17.407 UTC
60
2021-03-31 13:28:58.803 UTC
null
null
null
null
5,691
null
1
108
sockets|tcp
93,159
<p>The connection <em>should</em> remain open regardless but yes it's often common to see protocols implement a heartbeat in order to help detect dead connections, IRC with the <a href="https://www.rfc-editor.org/rfc/rfc2812#section-3.7.2" rel="nofollow noreferrer">PING</a> command for example.</p>
245,395
Hidden features of Windows batch files
<p>What are some of the lesser know, but important and useful features of Windows batch files?</p> <p>Guidelines:</p> <ul> <li>One feature per answer</li> <li>Give both a short <strong>description</strong> of the feature and an <strong>example</strong>, not just a link to documentation</li> <li>Limit answers to <strong>native funtionality</strong>, i.e., does not require additional software, like the <em>Windows Resource Kit</em></li> </ul> <p>Clarification: We refer here to scripts that are processed by cmd.exe, which is the default on WinNT variants.</p> <p>(See also: <a href="https://stackoverflow.com/questions/148968/windows-batch-files-bat-vs-cmd">Windows batch files: .bat vs .cmd?</a>)</p>
245,434
91
0
2008-10-29 21:55:07.08 UTC
2008-10-29 00:34:22.39 UTC
643
2012-02-21 22:08:23.11 UTC
2017-05-23 12:34:23.73 UTC
Chris Noe
-1
Chris Noe
14,749
null
1
232
windows|batch-file|hidden-features
224,969
<p>Line continuation:</p> <pre><code>call C:\WINDOWS\system32\ntbackup.exe ^ backup ^ /V:yes ^ /R:no ^ /RS:no ^ /HC:off ^ /M normal ^ /L:s ^ @daily.bks ^ /F daily.bkf </code></pre>
34,613,761
detect non ascii characters in a string
<p>How can I detect non-ascii characters in a vector of strings in a grep like fashion. For example below I'd like to return <code>c(1, 3)</code> or <code>c(TRUE, FALSE, TRUE, FALSE)</code>:</p> <pre><code>x &lt;- c(&quot;façile test of showNonASCII(): details{&quot;, &quot;This is a good line&quot;, &quot;This has an ümlaut in it.&quot;, &quot;OK again. }&quot;) </code></pre> <p>Attempt:</p> <pre><code>y &lt;- tools::showNonASCII(x) str(y) p &lt;- capture.output(tools::showNonASCII(x)) </code></pre>
34,614,485
5
7
null
2016-01-05 14:15:20.587 UTC
7
2021-10-07 15:10:02.203 UTC
2021-03-22 14:25:20.353 UTC
null
3,058,123
null
1,000,343
null
1
34
r
7,440
<p>another possible way is to try to convert your string to ASCII and the try to detect all the generated <em>non printable control characters</em> which couldn't be converted</p> <pre><code>grepl("[[:cntrl:]]", stringi::stri_enc_toascii(x)) ## [1] TRUE FALSE TRUE FALSE </code></pre> <p>Though it seems <code>stringi</code> has a built in function for this type of things too</p> <pre><code>stringi::stri_enc_mark(x) # [1] "latin1" "ASCII" "latin1" "ASCII" </code></pre>
34,500,147
Angular 2: getting RouteParams from parent component
<p>How do I get the RouteParams from a parent component?</p> <p><code>App.ts</code>:</p> <pre><code>@Component({ ... }) @RouteConfig([ {path: '/', component: HomeComponent, as: 'Home'}, {path: '/:username/...', component: ParentComponent, as: 'Parent'} ]) export class HomeComponent { ... } </code></pre> <p>And then, in the <code>ParentComponent</code>, I can easily get my username param and set the child routes.</p> <p><code>Parent.ts</code>:</p> <pre><code>@Component({ ... }) @RouteConfig([ { path: '/child-1', component: ChildOneComponent, as: 'ChildOne' }, { path: '/child-2', component: ChildTwoComponent, as: 'ChildTwo' } ]) export class ParentComponent { public username: string; constructor( public params: RouteParams ) { this.username = params.get('username'); } ... } </code></pre> <p>But then, how can I get this same 'username' parameter in those child components? Doing the same trick as above, doesn't do it. Because those params are defined at the ProfileComponent or something??</p> <pre><code>@Component({ ... }) export class ChildOneComponent { public username: string; constructor( public params: RouteParams ) { this.username = params.get('username'); // returns null } ... } </code></pre>
37,973,553
13
9
null
2015-12-28 20:17:46.563 UTC
20
2021-08-06 11:28:20.587 UTC
null
null
null
null
4,107,083
null
1
81
angular|angular2-routing
49,183
<p><strong>UPDATE:</strong></p> <p>Now that Angular2 final was officially released, the correct way to do this is the following:</p> <pre><code>export class ChildComponent { private sub: any; private parentRouteId: number; constructor(private route: ActivatedRoute) { } ngOnInit() { this.sub = this.route.parent.params.subscribe(params =&gt; { this.parentRouteId = +params["id"]; }); } ngOnDestroy() { this.sub.unsubscribe(); } } </code></pre> <hr> <p><strong>ORIGINAL:</strong></p> <p>Here is how i did it using the "@angular/router": "3.0.0-alpha.6" package:</p> <pre><code>export class ChildComponent { private sub: any; private parentRouteId: number; constructor( private router: Router, private route: ActivatedRoute) { } ngOnInit() { this.sub = this.router.routerState.parent(this.route).params.subscribe(params =&gt; { this.parentRouteId = +params["id"]; }); } ngOnDestroy() { this.sub.unsubscribe(); } } </code></pre> <p>In this example the route has the following format: /parent/:id/child/:childid</p> <pre><code>export const routes: RouterConfig = [ { path: '/parent/:id', component: ParentComponent, children: [ { path: '/child/:childid', component: ChildComponent }] } ]; </code></pre>
6,685,249
jQuery: Performing synchronous AJAX requests
<p>I've done some jQuery in the past, but I am completely stuck on this. I know about the pros and cons of using synchronous ajax calls, but here it will be required. </p> <p>The remote page is loaded (controlled with firebug), but no return is shown.</p> <p><strong>What should I do different to make my function to return properly?</strong></p> <pre><code>function getRemote() { var remote; $.ajax({ type: "GET", url: remote_url, async: false, success : function(data) { remote = data; } }); return remote; } </code></pre>
6,685,294
4
13
null
2011-07-13 20:31:48.863 UTC
40
2016-10-04 07:49:41.95 UTC
null
null
null
null
198,128
null
1
203
ajax|jquery|synchronous
361,407
<p>As you're making a synchronous request, that should be</p> <pre><code>function getRemote() { return $.ajax({ type: "GET", url: remote_url, async: false }).responseText; } </code></pre> <p>Example - <a href="http://api.jquery.com/jQuery.ajax/#example-3" rel="noreferrer">http://api.jquery.com/jQuery.ajax/#example-3</a></p> <p><strong>PLEASE NOTE:</strong> Setting async property to false is <strong>deprecated</strong> and in the process of being removed (<a href="https://xhr.spec.whatwg.org/#sync-warning" rel="noreferrer">link</a>). Many browsers including Firefox and Chrome have already started to print a warning in the console if you use this:</p> <p>Chrome:</p> <blockquote> <p>Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check <a href="https://xhr.spec.whatwg.org/" rel="noreferrer">https://xhr.spec.whatwg.org/</a>.</p> </blockquote> <p>Firefox:</p> <blockquote> <p>Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help <a href="http://xhr.spec.whatwg.org/" rel="noreferrer">http://xhr.spec.whatwg.org/</a></p> </blockquote>
6,963,534
C++: How do I cast an int to an unsigned long and not change any bits?
<p>C++: How do I cast an int to an unsigned long and not change any bits? I want to pack and unpack values into memory. The word size is 64 bits.</p> <p>This snippet illustrates the problem:</p> <pre><code>int v1 = -2; // 0xfe unsigned long v2=(unsigned long)v1; // 0xfffe, I want 0x00fe </code></pre> <p>The simple solution is:</p> <pre><code>unsigned long v2=(unsigned int)v1; // 0x00fe </code></pre> <p>However, this code is in a template where the target type is a parameter, so I had to resort to this:</p> <pre><code>uint64 target = mem[index] &amp; mask; uint64 v; if (value &lt; 0) { switch (bits) { case 8: v = (uint8)value; break; case 16: v = (uint16)value; break; case 32: v = (uint32)value; break; } } else { v = value; } v = v &lt;&lt; lShift; target |= v; mem[index] = target; </code></pre> <p>Assume, for example, the type for "value" is an int (16 bits) and bits=16. The goal is to mask the bits in memory for value and replace them.</p> <p>Does anyone know an easier way?</p>
6,985,206
6
3
null
2011-08-05 23:12:15.907 UTC
3
2011-08-08 16:58:59.243 UTC
null
null
null
null
161,590
null
1
10
c++|casting|bit-manipulation
38,506
<p>Using the idea put forth by "Kerrek SB" I came up with a solution.</p> <pre><code>template &lt;typename Tint&gt; uint64 ToMemdata(Tint value) { return (uint64)value;}; template &lt;&gt; uint64 ToMemdata&lt;int8&gt;(int8 value) { return (uint64)((uint8)value);}; template &lt;&gt; uint64 ToMemdata&lt;int16&gt;(int16 value) { return (uint64)((uint16)value);}; template &lt;&gt; uint64 ToMemdata&lt;int32&gt;(int32 value) { return (uint64)((uint32)value);}; template &lt;&gt; uint64 ToMemdata&lt;int64&gt;(int64 value) { return (uint64)((uint64)value);}; template &lt;typename Tint&gt; void packedWrite(Tint value, int vectorIndex, uint64* pData) { uint64 v = ToMemdata(value); // This call eliminates a run time test for minus and a switch statement // Instead the compiler does it based on the template specialization uint64 aryix, itemofs; vectorArrayIndex(vectorIndex, &amp;aryix, &amp;itemofs); // get the memory index and the byte offset uint64 mask = vectorItemMask(itemofs); // get the mask for the particular byte uint64 aryData = pData[aryix]; // get the word in memory aryData &amp;= mask; // mask it uint64 lShift = (uint64)(itemofs * sizeof(Tint) * 8); uint64 d = v &lt;&lt; lShift; // shift the value into the byte position aryData |= d; // put the value into memory pData[aryix] = aryData; } </code></pre> <p>Using this concept I was able to make other improvements to the code. For example, the call to vectorItemMask() is now templateized also.</p>
6,335,153
Casting a byte array to a managed structure
<p><strong>Update: Answers to this question helped me code the open sourced project <a href="https://github.com/AlicanC/AlicanC-s-Modern-Warfare-2-Tool" rel="noreferrer">AlicanC's Modern Warfare 2 Tool on GitHub</a>. You can see how I am reading these packets in <a href="https://github.com/AlicanC/AlicanC-s-Modern-Warfare-2-Tool/blob/master/ACMW2HostTool/MW2Packets.cs" rel="noreferrer">MW2Packets.cs</a> and the extensions I've coded to read big endian data in <a href="https://github.com/AlicanC/AlicanC-s-Modern-Warfare-2-Tool/blob/master/ACMW2HostTool/Extensions.cs" rel="noreferrer">Extensions.cs</a>.</strong></p> <p>I am capturing UDP packets of <a href="http://store.steampowered.com/app/10180/" rel="noreferrer">Call of Duty: Modern Warfare 2</a> using <a href="http://pcapdotnet.codeplex.com/" rel="noreferrer">Pcap.Net</a> in my C# application. I receive a <code>byte[]</code> from the library. I tried to parse it like a string, but that didn't work well.</p> <p>The <code>byte[]</code> I have has a generic packet header, then another header specific to the packet type then info about each player in the lobby.</p> <p>A helpful person inspected some packets for me and came up with these structures:</p> <pre><code>// Fields are big endian unless specified otherwise. struct packet_header { uint16_t magic; uint16_t packet_size; uint32_t unknown1; uint32_t unknown2; uint32_t unknown3; uint32_t unknown4; uint16_t unknown5; uint16_t unknown6; uint32_t unknown7; uint32_t unknown8; cstring_t packet_type; // \0 terminated string }; // Fields are little endian unless specified otherwise. struct header_partystate //Header for the "partystate" packet type { uint32_t unknown1; uint8_t unknown2; uint8_t player_entry_count; uint32_t unknown4; uint32_t unknown5; uint32_t unknown6; uint32_t unknown7; uint8_t unknown8; uint32_t unknown9; uint16_t unknown10; uint8_t unknown11; uint8_t unknown12[9]; uint32_t unknown13; uint32_t unknown14; uint16_t unknown15; uint16_t unknown16; uint32_t unknown17[10]; uint32_t unknown18; uint32_t unknown19; uint8_t unknown20; uint32_t unknown21; uint32_t unknown22; uint32_t unknown23; }; // Fields are little endian unless specified otherwise. struct player_entry { uint8_t player_id; // The following fields may not actually exist in the data if it's an empty entry. uint8_t unknown1[3]; cstring_t player_name; uint32_t unknown2; uint64_t steam_id; uint32_t internal_ip; uint32_t external_ip; uint16_t unknown3; uint16_t unknown4; uint32_t unknown5; uint32_t unknown6; uint32_t unknown7; uint32_t unknown8; uint32_t unknown9; uint32_t unknown10; uint32_t unknown11; uint32_t unknown12; uint16_t unknown13; uint8_t unknown14[???]; // Appears to be a bit mask, sometimes the length is zero, sometimes it's one. (First entry is always zero?) uint8_t unknown15; uint32_t unknown16; uint16_t unknown17; uint8_t unknown18[???]; // Most of the time this is 4 bytes, other times it is 3 bytes. }; </code></pre> <p>I recreated the packet header structure in my C# application like this:</p> <pre><code>[StructLayout(LayoutKind.Sequential, Pack=1)] struct PacketHeader { public UInt16 magic; public UInt16 packetSize; public UInt32 unknown1; public UInt32 unknown2; public UInt32 unknown3; public UInt32 unknown4; public UInt16 unknown5; public UInt16 unknown6; public UInt32 unknown7; public UInt32 unknown8; public String packetType; } </code></pre> <p>Then I tried to make a structure for the "partystate" header, but I got errors saying <code>fixed</code> keyword is unsafe:</p> <pre><code>[StructLayout(LayoutKind.Sequential, Pack=1)] struct PartyStateHeader { UInt32 unknown1; Byte unknown2; Byte playerEntryCount; UInt32 unknown4; UInt32 unknown5; UInt32 unknown6; UInt32 unknown7; Byte unknown8; UInt32 unknown9; UInt16 unknown10; Byte unknown11; fixed Byte unknown12[9]; UInt32 unknown13; UInt32 unknown14; UInt16 unknown15; UInt16 unknown16; fixed UInt32 unknown17[10]; UInt32 unknown18; UInt32 unknown19; Byte unknown20; UInt32 unknown21; UInt32 unknown22; UInt32 unknown23; } </code></pre> <p>I couldn't do anything for the player entries because of the varying size of <code>unknown14</code> and <code>unknown18</code>. (Player entries are the most important.)</p> <p>Now, somehow, I have to cast the <code>byte[]</code> I have to these <code>PacketHeader</code> structures. Sadly, it's not easy as <code>(PacketHeader)bytes</code>. I tried this method I've found on the internet but it threw an <code>AccessViolationException</code>:</p> <pre><code>GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); PacketHeader packetHeader = (PacketHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(PacketHeader)); </code></pre> <p>How can I achieve this?</p>
6,336,196
7
1
null
2011-06-13 19:17:55.88 UTC
14
2021-11-24 15:56:54.12 UTC
2011-06-29 22:10:34.413 UTC
null
667,234
null
667,234
null
1
22
c#|bytearray|structure|pcap.net
46,514
<p>I'd turn the byte array into a memory stream. Then instantiate a binary reader on that stream. And then define helper functions that take a binary reader and parse a single class.</p> <p>The built in <code>BinaryReader</code> class always uses little endian.</p> <p>I'd use classes instead of structs here. </p> <pre><code>class PacketHeader { uint16_t magic; uint16_t packet_size; uint32_t unknown1; uint32_t unknown2; uint32_t unknown3; uint32_t unknown4; uint16_t unknown5; uint16_t unknown6; uint32_t unknown7; uint32_t unknown8; string packet_type; // replaced with a real string }; PacketHeader ReadPacketHeader(BinaryReader reader) { var result=new PacketHeader(); result.magic = reader.ReadInt16(); ... result.packet_type=ReadCString();//Some helper function you might need to define yourself return result; } </code></pre>
6,983,553
Why are private fields private to the type, not the instance?
<p>In C# (and many other languages) it's perfectly legitimate to access private fields of other instances of the same type. For example:</p> <pre><code>public class Foo { private bool aBool; public void DoBar(Foo anotherFoo) { if (anotherFoo.aBool) ... } } </code></pre> <p>As the <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809" rel="noreferrer">C# specification</a> (sections 3.5.1, 3.5.2) states access to private fields is on a type, not an instance. I've been discussing this with a colleague and we're trying to come up with a reason why it works like this (rather than restricting access to the same instance).</p> <p>The best argument we could come up with is for equality checks where the class may want to access private fields to determine equality with another instance. Are there any other reasons? Or some golden reason that absolutely means it must work like this or something would be completely impossible?</p>
6,983,855
10
9
null
2011-08-08 14:21:27.427 UTC
42
2018-09-08 01:32:40.103 UTC
2018-09-08 01:32:40.103 UTC
null
3,800,096
null
255,231
null
1
157
c#|oop|language-design|language-features|private-members
8,883
<p>I think one reason it works this way is because access modifiers work at <em>compile time</em>. As such, determining whether or not a given object is also the <em>current</em> object isn't easy to do. For example, consider this code:</p> <pre><code>public class Foo { private int bar; public void Baz(Foo other) { other.bar = 2; } public void Boo() { Baz(this); } } </code></pre> <p>Can the compiler necessarily figure out that <code>other</code> is actually <code>this</code>? Not in all cases. One could argue that this just shouldn't compile then, but that means we have a code path where a private instance member <em>of the correct instance</em> isn't accessible, which I think is even worse.</p> <p>Only requiring type-level rather than object-level visibility ensures that the problem is tractable, as well as making a situation that seems like it <em>should</em> work <em>actually</em> work.</p> <p><strong>EDIT</strong>: Danilel Hilgarth's point that this reasoning is backwards does have merit. Language designers can create the language they want, and compiler writers must conform to it. That being said, language designers do have some incentive to make it easier for compiler writers to do their job. (Though in this case, it's easy enough to argue that private members could then <em>only</em> be accessed via <code>this</code> (either implicitly or explicitly)).</p> <p>However, I believe that makes the issue more confusing than it needs to be. Most users (myself included) would find it unneccessarily limiting if the above code didn't work: after all, that's <em>my</em> data I'm trying to access! Why should I have to go through <code>this</code>?</p> <p>In short, I think I may have overstated the case for it being "difficult" for the compiler. What I really meant to get across is that above situation seems like one that the designers would like to have work.</p>
12,597,328
SQL select case when clause
<p>The following is the query</p> <pre><code>select *, "Price Range" = CASE WHEN ListPrice = 0 THEN 'Mfg item - not for resale' WHEN ListPrice &lt; 50 THEN 'Under $50' WHEN ListPrice &gt;= 50 and ListPrice &lt; 250 THEN 'Under $250' WHEN ListPrice &gt;= 250 and ListPrice &lt; 1000 THEN 'Under $1000' ELSE 'Over $1000' END FROM Production.Product ORDER BY ProductNumber </code></pre> <p>But there is SQL error, missing important words before FROM.</p> <p>What is the blueprint for us to use <code>case</code> if I want to select all the columns ?</p>
12,597,508
5
2
null
2012-09-26 08:12:01.41 UTC
2
2015-07-19 23:08:54.253 UTC
2015-07-19 23:08:54.253 UTC
null
1,567,352
null
683,482
null
1
2
sql|oracle|plsql|case
40,253
<p>Try This</p> <pre><code>select *, CASE WHEN ListPrice = 0 THEN 'Mfg item - not for resale' WHEN ListPrice &lt; 50 THEN 'Under $50' WHEN ListPrice &gt;= 50 and ListPrice &lt; 250 THEN 'Under $250' WHEN ListPrice &gt;= 250 and ListPrice &lt; 1000 THEN 'Under $1000' ELSE 'Over $1000' END AS [Price Range] FROM Production.Product ORDER BY ProductNumber </code></pre>
38,187,833
How to combine ReactJs Router Link and material-ui components (like a button)?
<p>I need to find a solution to be able to combine together the functionality of react router with the material ui components.</p> <p>For instance, I've this scenario: a router and a button. What I tried to do it is to mix them together, and restyle them.</p> <p>So from a simple link</p> <pre><code>&lt;Link className={this.getClass(this.props.type)} to={`${url}`} title={name}&gt;{name}&lt;/Link&gt; </code></pre> <p>I tried to create a material ui button as the following</p> <pre><code>&lt;Link className={this.getClass(this.props.type)} to={`${url}`} title={name}&gt; &lt;FlatButton label={name} /&gt; &lt;/Link&gt; </code></pre> <p>but I have the following error and Javascript breaks</p> <blockquote> <p>invariant.js?4599:38Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's <code>render</code> method, or you have multiple copies of React loaded (details: <a href="https://gist.github.com/jimfb/4faa6cbfb1ef476bd105" rel="noreferrer">https://gist.github.com/jimfb/4faa6cbfb1ef476bd105</a>).</p> </blockquote> <p>Do you have any idea how to manage this situation? Thank you in advance and if you need more information let me know</p>
59,187,804
4
1
null
2016-07-04 15:10:22.987 UTC
8
2020-05-11 18:49:47.943 UTC
null
null
null
null
1,901,526
null
1
51
javascript|reactjs|react-router|client-side|material-ui
29,666
<p>The way to do in new versions is:</p> <pre><code>import { Link } from 'react-router-dom'; // ... some code render(){ return ( &lt;Button component={Link} to={'/my_route'}&gt;My button&lt;/Button&gt; ); } </code></pre> <p>Look at this <a href="https://github.com/mui-org/material-ui/issues/7186#issuecomment-523629450" rel="noreferrer">thread</a> or this <a href="https://stackoverflow.com/questions/58585373/integrates-react-route-links-into-material-ui-list">question</a> </p>
38,351,820
Negation of %in% in R
<p>Is there a short negation of <code>%in%</code> in R like <code>!%in%</code> or <code>%!in%</code>?</p> <hr> <p>Of course I can negate <code>c("A", "B") %in% c("B", "C")</code> by <code>!(c("A", "B") %in% c("B", "C"))</code> (cf. <a href="https://stackoverflow.com/questions/5831794/opposite-of-in">this question</a>) but I would prefere a more straight forward approach and save a pair of brackets (alike presumably most people would prefer <code>c("A", "B") != c("B", "C")</code> over <code>!(c("A", "B") == c("B", "C"))</code>).</p>
38,352,065
4
2
null
2016-07-13 12:31:45.077 UTC
13
2022-02-23 10:43:10.257 UTC
2018-02-26 19:49:38.85 UTC
null
6,256,241
null
6,256,241
null
1
53
r|match|negation
59,911
<p>No, there isn't a built in function to do that, but you could easily code it yourself with</p> <pre class="lang-r prettyprint-override"><code>`%nin%` = Negate(`%in%`) </code></pre> <p>Or</p> <pre class="lang-r prettyprint-override"><code>`%!in%` = Negate(`%in%`) </code></pre> <hr /> <p>See this thread and followup discussion: <a href="http://r.789695.n4.nabble.com/in-operator-NOT-IN-td3506655.html" rel="noreferrer">%in% operator - NOT IN</a> (alternatively <a href="https://stat.ethz.ch/pipermail/r-help/2011-May/277498.html" rel="noreferrer">here</a>)</p> <hr /> <p>Also, it was pointed out the package <code>Hmisc</code> includes the operator <code>%nin%</code>, so if you're using it for your applications it's already there.</p> <pre><code>library(Hmisc) &quot;A&quot; %nin% &quot;B&quot; #[1] TRUE &quot;A&quot; %nin% &quot;A&quot; #FALSE </code></pre>
41,535,322
Setting freq of pandas DatetimeIndex after DataFrame creation
<p>Im using pandas datareader to get stock data. </p> <pre><code>import pandas as pd import pandas_datareader.data as web ABB = web.DataReader(name='ABB.ST', data_source='yahoo', start='2000-1-1') </code></pre> <p>However by default freq is not set on the resulting dataframe. I need freq to be able to navigate using the index like this:</p> <pre><code>for index, row in ABB.iterrows(): ABB.loc[[index + 1]] </code></pre> <p>If freq is not set on DatetimeIndex im not able to use <code>+1</code> etc to navigate.</p> <p>What I have found are two functions <code>astype</code> and <code>resample</code>. Since I already know to freq <code>resample</code> looks like overkill, I just want to set freq to daily.</p> <p>Now my question is how can i use astype on ABB to set freq to daily?</p>
41,536,899
3
2
null
2017-01-08 17:03:37.203 UTC
4
2020-03-28 16:06:14.437 UTC
2017-01-08 18:01:28.75 UTC
null
3,139,545
null
3,139,545
null
1
31
python|pandas
42,000
<p>Try:</p> <pre><code>ABB = ABB.asfreq('d') </code></pre> <p>This should change the frequency to daily with <code>NaN</code> for days without data.</p> <p>Also, you should rewrite your <code>for-loop</code> as follows:</p> <pre><code>for index, row in ABB.iterrows(): print(ABB.loc[[index + pd.Timedelta(days = 1)]]) </code></pre> <p>Thanks!</p>
15,700,355
Update only time from my Datetime field in sql
<p>I have a date 2013-12-14 05:00:00.000 in my table.</p> <p>Now i want to update only time of that date. E.G to 2013-12-14 04:00:00.000</p> <p>Is there any query to update only time from datetime field?</p>
15,700,563
9
4
null
2013-03-29 09:11:08.843 UTC
9
2021-09-01 13:03:22.277 UTC
null
null
null
null
1,268,865
null
1
36
sql|sql-server-2008
96,975
<pre><code>UPDATE MyTable SET MyDate = DATEADD(HOUR, 4, CAST(CAST(MyDate AS DATE) AS DATETIME)) </code></pre> <p>Or this</p> <pre><code>UPDATE MyTable SET MyDate = DATEADD(HOUR, 4, CAST(FLOOR(CAST(MyDate AS FLOAT)) AS DATETIME)) </code></pre>
15,662,258
How to save a bitmap on internal storage
<p>this is my code I and I want to save this bitmap on my internal storage. The public boolean saveImageToInternalStorage is a code from google but I don't know how to use it. when I touch button2 follow the button1 action.</p> <pre><code>public class MainActivity extends Activity implements OnClickListener { Button btn, btn1; SurfaceView sv; Bitmap bitmap; Canvas canvas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.button1); btn1=(Button)findViewById(R.id.button2); sv=(SurfaceView)findViewById(R.id.surfaceView1); btn.setOnClickListener(this); btn1.setOnClickListener(this); bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); } @Override public void onClick(View v) { canvas=sv.getHolder().lockCanvas(); if(canvas==null) return; canvas.drawBitmap(bitmap, 100, 100, null); sv.getHolder().unlockCanvasAndPost(canvas); } public boolean saveImageToInternalStorage(Bitmap image) { try { // Use the compress method on the Bitmap object to write image to // the OutputStream FileOutputStream fos = openFileOutput("desiredFilename.png", Context.MODE_PRIVATE); // Writing the bitmap to the output stream image.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); return true; } catch (Exception e) { Log.e("saveToInternalStorage()", e.getMessage()); return false; } } } </code></pre>
15,662,384
5
0
null
2013-03-27 15:08:23 UTC
21
2019-03-28 12:32:46.14 UTC
null
null
null
null
2,212,477
null
1
49
android|bitmap|save
132,004
<p>To Save your bitmap in sdcard use the following code</p> <p><strong>Store Image</strong></p> <pre><code>private void storeImage(Bitmap image) { File pictureFile = getOutputMediaFile(); if (pictureFile == null) { Log.d(TAG, "Error creating media file, check storage permissions: ");// e.getMessage()); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); image.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.close(); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } } </code></pre> <p><strong>To Get the Path for Image Storage</strong></p> <pre><code>/** Create a File for saving an image or video */ private File getOutputMediaFile(){ // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/" + getApplicationContext().getPackageName() + "/Files"); // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. // Create the storage directory if it does not exist if (! mediaStorageDir.exists()){ if (! mediaStorageDir.mkdirs()){ return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date()); File mediaFile; String mImageName="MI_"+ timeStamp +".jpg"; mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName); return mediaFile; } </code></pre> <p><strong>EDIT</strong> From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.</p> <pre><code>public onClick(View v){ switch(v.getId()){ case R.id.button1: //Your button 1 function break; case R.id. button2: //Your button 2 function break; } } </code></pre>
15,551,618
Get the creation date of a stash
<p>Is there a way to tell when a stash was created?</p> <p><code>git stash list</code> only lists the stashes, and <code>git stash show XXXXXX</code> shows all the files and changes, but not the <strong>date</strong> of the stash creation.</p>
15,551,690
3
0
null
2013-03-21 15:25:55.367 UTC
44
2016-08-15 15:29:12.82 UTC
2015-05-12 13:34:12.24 UTC
null
2,936,460
null
128,532
null
1
311
git|git-stash
46,915
<p>Try:</p> <pre><code>git stash list --date=local </code></pre> <p>It should print something like:</p> <pre><code>stash@{Thu Mar 21 10:30:17 2013}: WIP on master: 2ffc05b Adding resource </code></pre>
10,840,030
Django post_save preventing recursion without overriding model save()
<p>There are many Stack Overflow posts about recursion using the <code>post_save</code> signal, to which the comments and answers are overwhelmingly: "why not override save()" or a save that is only fired upon <code>created == True</code>.</p> <p>Well I believe there's a good case for not using <code>save()</code> - for example, I am adding a temporary application that handles order fulfillment data completely separate from our Order model.</p> <p>The rest of the framework is blissfully unaware of the fulfillment application and using post_save hooks isolates all fulfillment related code from our Order model.</p> <p>If we drop the fulfillment service, nothing about our core code has to change. We delete the fulfillment app, and that's it.</p> <p>So, are there any decent methods to ensure the post_save signal doesn't fire the same handler twice?</p>
28,369,908
10
3
null
2012-05-31 19:27:44.657 UTC
21
2021-01-17 16:45:14.07 UTC
null
null
null
null
267,887
null
1
40
python|django|django-signals
23,757
<p>What you think about this solution?</p> <pre><code>@receiver(post_save, sender=Article) def generate_thumbnails(sender, instance=None, created=False, **kwargs): if not instance: return if hasattr(instance, '_dirty'): return do_something() try: instance._dirty = True instance.save() finally: del instance._dirty </code></pre> <p>You can also create decorator</p> <pre><code>def prevent_recursion(func): @wraps(func) def no_recursion(sender, instance=None, **kwargs): if not instance: return if hasattr(instance, '_dirty'): return func(sender, instance=instance, **kwargs) try: instance._dirty = True instance.save() finally: del instance._dirty return no_recursion @receiver(post_save, sender=Article) @prevent_recursion def generate_thumbnails(sender, instance=None, created=False, **kwargs): do_something() </code></pre>
10,605,653
Converting char* to float or double
<p>I have a value I read in from a file and is stored as a char*. The value is a monetary number, #.##, ##.##, or ###.##. I want to convert the char* to a number I can use in calculations, I've tried atof and strtod and they just give me garbage numbers. What is the correct way to do this, and why is the way I am doing it wrong?</p> <p>This is essentially what I am doing, just the char* value is read in from a file. When I print out the temp and ftemp variables they are just garbage, gigantic negative numbers.</p> <p>Another Edit:</p> <p>I am running exactly this in gcc</p> <pre><code>#include &lt;stdio.h&gt; int main() { char *test = "12.11"; double temp = strtod(test,NULL); float ftemp = atof(test); printf("price: %f, %f",temp,ftemp); return 0; </code></pre> <p>}</p> <p>and my output is price: 3344336.000000, 3344336.000000</p> <p>Edit: Here is my code</p> <pre><code>if(file != NULL) { char curLine [128]; while(fgets(curLine, sizeof curLine, file) != NULL) { tempVal = strtok(curLine,"|"); pairs[i].name= strdup(tempVal); tempVal = strtok(NULL,"|"); pairs[i].value= strdup(tempVal); ++i; } fclose(file); } double temp = strtod(pairs[0].value,NULL); float ftemp = atof(pairs[0].value); printf("price: %d, %f",temp,ftemp); </code></pre> <p>my input file is very simple name, value pairs like this:</p> <pre><code>NAME|VALUE NAME|VALUE NAME|VALUE </code></pre> <p>with the value being dollar amounts</p> <p>SOLVED: Thank you all, I was using %d instead of %f and didn't have the right headers included.</p>
10,606,023
3
4
null
2012-05-15 17:11:17.037 UTC
3
2012-05-15 18:01:21.803 UTC
2012-05-15 18:01:21.803 UTC
null
767,700
null
767,700
null
1
15
c|strtod|atof
135,611
<p>You are missing an include : <code>#include &lt;stdlib.h&gt;</code>, so GCC creates an implicit declaration of <code>atof</code> and <code>atod</code>, leading to garbage values.</p> <p>And the format specifier for double is <code>%f</code>, not <code>%d</code> (that is for integers).</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main() { char *test = "12.11"; double temp = strtod(test,NULL); float ftemp = atof(test); printf("price: %f, %f",temp,ftemp); return 0; } /* Output */ price: 12.110000, 12.110000 </code></pre>
10,835,365
Authenticate programmatically to Google with OAuth2
<p>How can I authenticate programmatically to Google? Now that ClientLogin (<a href="https://developers.google.com/accounts/docs/AuthForInstalledApps" rel="noreferrer">https://developers.google.com/accounts/docs/AuthForInstalledApps</a>) is deprecated, how can we perform a programmatic authentication to Google with OAuth2?</p> <p>With ClientLogin we could perform a post to <a href="https://www.google.com/accounts/ClientLogin" rel="noreferrer">https://www.google.com/accounts/ClientLogin</a> with email and password parameters and obtain the authentication token.</p> <p>With OAuth2 i can't find a solution!</p> # <p>My app is a java background process. I saw, following this link: developers.google.com/accounts/docs/OAuth2InstalledApp#refresh, how to obtain a new access token using a refreshed token.</p> <p>The problem is that I can't find a java example about how to instantiate an Analytics object (for example) to perform a query when I have a new valid access token</p> <p>This is my code that returns a 401 Invalid credentials when invoke the "execute()":</p> <pre><code>public class Test { static final String client_id = "MY_CLIENT_ID"; static final String client_secret = "MY_SECRET"; static final String appName = "MY_APP"; private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); private static final JsonFactory JSON_FACTORY = new JacksonFactory(); static String access_token = "xxxx"; static String refreshToken = "yyyyy"; public static void main (String args[]){ try { GoogleCredential credential = new GoogleCredential.Builder() .setTransport(HTTP_TRANSPORT) .setJsonFactory(JSON_FACTORY) .setClientSecrets(client_id, client_secret).build(); credential.setAccessToken(access_token); credential.setRefreshToken(refreshToken); //GoogleCredential Analytics analytics = Analytics.builder(HTTP_TRANSPORT, JSON_FACTORY) .setApplicationName(appName) .setHttpRequestInitializer(credential) .build(); Accounts accounts = analytics.management().accounts().list().execute(); } catch (Exception e) { e.printStackTrace(); } } </code></pre> <p>What is the problem?</p>
10,837,581
4
4
null
2012-05-31 14:13:22.91 UTC
17
2016-11-24 05:05:23.167 UTC
2016-01-02 00:58:12.523 UTC
null
752,167
null
1,246,821
null
1
30
java|google-oauth|google-signin
81,920
<p>Check the OAuth 2 flow for Installed Application:</p> <p><a href="https://developers.google.com/accounts/docs/OAuth2InstalledApp">https://developers.google.com/accounts/docs/OAuth2InstalledApp</a></p> <p>It still requires the user to authenticate with a browser the first time, but then you can store the refresh token and use it for subsequent requests.</p> <p>For alternative solutions, check the Device flow or Service Accounts, they are explained in the same documentation set.</p>
56,618,739
Matplotlib throws warning message because of findfont - python
<p>I want to plot a basic graph, basically consisting of two lists of the form x = [1,2,3,...,d], y = [y1,y2,...,yd]. after using_ <code>pyplot.plot(x,y)</code> I get a huge amount of warning messages referring to <strong>findfont errors</strong> (see below..)</p> <p>I just installed matplotlib. All the threads I could find refer to changing fonts manually and having warning messages popping up. I did not do anything like that. I just installed the package and that is it.</p> <p>I am using pycharm, python 3.6 and windows for programming.</p> <pre><code>DEBUG findfont: Matching :family=sans-serif:style=normal:variant=normal:weight=normal:stretch=normal:size=10.0. DEBUG findfont: score(&lt;Font 'cmex10' (cmex10.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'STIXSizeOneSym' (STIXSizOneSymReg.ttf) normal normal regular normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'cmb10' (cmb10.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'DejaVu Sans' (DejaVuSans-Bold.ttf) normal normal bold normal&gt;) = 0.33499999999999996 DEBUG findfont: score(&lt;Font 'STIXNonUnicode' (STIXNonUniBolIta.ttf) italic normal bold normal&gt;) = 11.335 DEBUG findfont: score(&lt;Font 'DejaVu Sans Mono' (DejaVuSansMono-Bold.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'DejaVu Serif' (DejaVuSerif.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'cmr10' (cmr10.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'STIXGeneral' (STIXGeneralItalic.ttf) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'STIXGeneral' (STIXGeneralBol.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'STIXSizeTwoSym' (STIXSizTwoSymBol.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'STIXSizeOneSym' (STIXSizOneSymBol.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'DejaVu Serif' (DejaVuSerif-BoldItalic.ttf) italic normal bold normal&gt;) = 11.335 DEBUG findfont: score(&lt;Font 'STIXGeneral' (STIXGeneral.ttf) normal normal regular normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'DejaVu Sans Mono' (DejaVuSansMono-BoldOblique.ttf) oblique normal bold normal&gt;) = 11.335 DEBUG findfont: score(&lt;Font 'DejaVu Sans Mono' (DejaVuSansMono-Oblique.ttf) oblique normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'STIXSizeFourSym' (STIXSizFourSymBol.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'STIXNonUnicode' (STIXNonUniIta.ttf) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'DejaVu Serif' (DejaVuSerif-Bold.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'cmsy10' (cmsy10.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'STIXNonUnicode' (STIXNonUni.ttf) normal normal regular normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'STIXSizeFourSym' (STIXSizFourSymReg.ttf) normal normal regular normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'STIXSizeThreeSym' (STIXSizThreeSymBol.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'DejaVu Serif' (DejaVuSerif-Italic.ttf) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'STIXSizeFiveSym' (STIXSizFiveSymReg.ttf) normal normal regular normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'cmss10' (cmss10.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'cmmi10' (cmmi10.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'DejaVu Sans Mono' (DejaVuSansMono.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'cmtt10' (cmtt10.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'STIXSizeTwoSym' (STIXSizTwoSymReg.ttf) normal normal regular normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'STIXNonUnicode' (STIXNonUniBol.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'DejaVu Sans Display' (DejaVuSansDisplay.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'DejaVu Serif Display' (DejaVuSerifDisplay.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'STIXSizeThreeSym' (STIXSizThreeSymReg.ttf) normal normal regular normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'DejaVu Sans' (DejaVuSans-Oblique.ttf) oblique normal 400 normal&gt;) = 1.05 DEBUG findfont: score(&lt;Font 'DejaVu Sans' (DejaVuSans-BoldOblique.ttf) oblique normal bold normal&gt;) = 1.335 DEBUG findfont: score(&lt;Font 'STIXGeneral' (STIXGeneralBolIta.ttf) italic normal bold normal&gt;) = 11.335 DEBUG findfont: score(&lt;Font 'DejaVu Sans' (DejaVuSans.ttf) normal normal 400 normal&gt;) = 0.05 DEBUG findfont: score(&lt;Font 'Franklin Gothic Book' (FRABK.TTF) normal normal book normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Microsoft Yi Baiti' (msyi.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Matura MT Script Capitals' (MATURASC.TTF) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Wide Latin' (LATINWD.TTF) normal normal 400 expanded&gt;) = 10.25 DEBUG findfont: score(&lt;Font 'Gigi' (GIGI.TTF) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Georgia' (georgiab.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Microsoft Tai Le' (taile.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Wingdings 3' (WINGDNG3.TTF) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Copperplate Gothic Bold' (COPRGTB.TTF) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Palatino Linotype' (palabi.ttf) italic normal bold normal&gt;) = 11.335 DEBUG findfont: score(&lt;Font 'Segoe UI' (segoeuii.ttf) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'Arial Rounded MT Bold' (ARLRDBD.TTF) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Verdana' (verdanai.ttf) italic normal 400 normal&gt;) = 4.6863636363636365 DEBUG findfont: score(&lt;Font 'Microsoft Himalaya' (himalaya.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Gloucester MT Extra Condensed' (GLECB.TTF) normal normal 400 condensed&gt;) = 10.25 DEBUG findfont: score(&lt;Font 'Palatino Linotype' (palab.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Playbill' (PLAYBILL.TTF) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Rage Italic' (RAGE.TTF) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'Perpetua' (PERI____.TTF) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'Constantia' (constani.ttf) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'Segoe UI Emoji' (seguiemj.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'KaiTi' (simkai.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Tw Cen MT Condensed' (TCCM____.TTF) normal normal 400 condensed&gt;) = 10.25 DEBUG findfont: score(&lt;Font 'Corbel' (corbel.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Nirmala UI' (Nirmala.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Baskerville Old Face' (BASKVILL.TTF) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Wingdings' (wingding.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Segoe UI' (segoeui.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Arial' (ariblk.ttf) normal normal black normal&gt;) = 6.888636363636364 DEBUG findfont: score(&lt;Font 'Courier New' (cour.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Courier New' (couri.ttf) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'Bookshelf Symbol 7' (BSSYM7.TTF) normal normal book normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Microsoft Uighur' (MSUIGHUB.TTF) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Lucida Fax' (LFAXDI.TTF) italic normal demibold normal&gt;) = 11.24 DEBUG findfont: score(&lt;Font 'Garamond' (GARA.TTF) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Consolas' (consolai.ttf) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'Lucida Sans Typewriter' (LTYPE.TTF) normal normal regular normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Perpetua Titling MT' (PERTIBD.TTF) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Britannic Bold' (BRITANIC.TTF) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Lucida Calligraphy' (LCALLIG.TTF) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'Lucida Bright' (LBRITE.TTF) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Ebrima' (ebrima.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Calisto MT' (CALIST.TTF) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Roboto' (Roboto-Bold.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Gadugi' (gadugi.ttf) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Colonna MT' (COLONNA.TTF) normal normal 400 normal&gt;) = 10.05 DEBUG findfont: score(&lt;Font 'Nirmala UI' (NirmalaS.ttf) normal normal light normal&gt;) = 10.24 DEBUG findfont: score(&lt;Font 'Microsoft Tai Le' (taileb.ttf) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Bodoni MT' (BOD_CBI.TTF) italic normal bold condensed&gt;) = 11.535 DEBUG findfont: score(&lt;Font 'Berlin Sans FB' (BRLNSB.TTF) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Gill Sans MT' (GILI____.TTF) italic normal 400 normal&gt;) = 11.05 DEBUG findfont: score(&lt;Font 'Rockwell' (ROCKBI.TTF) italic normal bold normal&gt;) = 11.335 DEBUG findfont: score(&lt;Font 'Gill Sans MT' (GILB____.TTF) normal normal bold normal&gt;) = 10.335 DEBUG findfont: score(&lt;Font 'Constantia' (constanb.ttf) normal normal bold normal&gt;) = 10.335 [...............] DEBUG findfont: Matching :family=sans-serif:style=normal:variant=normal:weight=normal:stretch=normal:size=10.0 to DejaVu Sans ('C:\\Users\\chris\\PycharmProjects\\DeepNN-Solver\\venv\\lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\DejaVuSans.ttf') with score of 0.050000. </code></pre>
58,393,562
2
5
null
2019-06-16 12:14:39.177 UTC
2
2022-07-29 07:30:49.433 UTC
2019-09-27 21:00:16.56 UTC
null
1,265,192
null
10,445,732
null
1
33
python|matplotlib|plot|pycharm
10,653
<p>Just as an alternative solution, you can disable the matplotlib font manager logger.</p> <pre><code>logging.getLogger('matplotlib.font_manager').disabled = True </code></pre> <p>Or you can just suppress the DEBUG messages but not the others from that logger.</p> <pre><code>logging.getLogger('matplotlib.font_manager').setLevel(logging.ERROR) </code></pre>
13,695,826
What is the /= operator in Java?
<p>The following code sample prints <code>1.5</code>.</p> <pre><code>float a = 3; float b = 2; a /= b; System.out.println(a); </code></pre> <p>I don't understand what the <code>/=</code> operator does. What is it supposed to represent?</p>
13,695,850
7
0
null
2012-12-04 03:56:13.86 UTC
1
2021-04-07 17:54:31.84 UTC
2019-09-16 13:44:26.187 UTC
null
1,898,563
null
1,018,901
null
1
9
java|assignment-operator
56,795
<p>It's a combination division-plus-assignment operator. </p> <pre><code>a /= b; </code></pre> <p>means divide <code>a</code> by <code>b</code> and put the result in <code>a</code>.</p> <p>There are similar operators for addition, subtraction, and multiplication: <code>+=</code>, <code>-=</code> and <code>*=</code>.</p> <p><code>%=</code> will do modulus.</p> <p><code>&gt;&gt;=</code> and <code>&lt;&lt;=</code> will do bit shifting.</p>
13,287,502
which java version does tomcat use
<p>I have set the <code>JAVA_HOME</code> to <code>C:\Program Files\Java\jdk1.5.0_11</code><br> I have set the <code>Classpath</code> to <code>C:\Program Files\Java\jre1.5.0_11</code></p> <p>I have set the path to </p> <p><code>C:\Ruby193\bin;C:\XEClient\bin; F:\oracle\product\10.2.0\db_2\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem; C:\Program Files\Java\jdk1.6.0_17\bin; C:\Program Files\jEdit;C:\Program Files\TortoiseSVN\bin; C:\Program Files\Microsoft SQL Server\90\Tools\binn\</code> </p> <p>Now my question is, what <code>version</code> of java does the tomcat run on?<br> The tomcat console writes the whole 'path'<br> and the <code>cmd</code> says it is java version 7 currently running in the system.<br> Someone please help me out.. I have java 5,6,7 versions installed in my system and also tomcat 5,6,7.<br> Now what is the tomcat's java version and the system's java version??? </p>
13,287,921
6
4
null
2012-11-08 10:47:21.503 UTC
1
2021-02-05 05:40:06.823 UTC
2012-11-08 10:50:48.753 UTC
null
1,168,493
null
1,107,115
null
1
15
java|tomcat
53,329
<p>You can look up the <strong>Java version Tomcat is really running with</strong> in the manager app, which is installed by default. Go to <code>http://hostname:8080/manager/html</code> (replace hostname by hostname or localhost), scroll to the bottom, there you will find "JVM Version".</p> <p><strong>Which JVM is selected</strong> depends a lot on the OS and way to install, maybe <a href="http://tomcat.apache.org/tomcat-7.0-doc/setup.html">http://tomcat.apache.org/tomcat-7.0-doc/setup.html</a> will help. </p> <p>E.g. if you are running <strong>Windows with Tomcat with the service wrapper</strong> (I would recommend this for Windows), you can <strong>set the path</strong> to the JVM directly in the tray icon -> Configure Tomcat. In the Java tab e.g. set Java Virtual Machine to "D:\java\jdk1.6.0_35\jre\bin\server\jvm.dll" (disabled "use default") or where your JVM resides -> you need to specify the complete path to the jvm.dll.</p> <p>Regarding getting to know <strong>which Java the system is running on</strong>: That's difficult to answer, there isn't really one Java version that the system is running as such. E.g. for Windows there may be one Java version set in the PATH, a potentially different one in JAVA_HOME / JRE_HOME / ..., one (or more) set in the registry, a certain version plugin active in each web browser used for applets etc. You have to check in the part you are interested in. Most good Java apps will display the version used somewhere, in logs, about dialogs or so. For Firefox you can check in the add-ons / plug-ins list. A Java exe wrapper like JSmooth can search for Java in different places and choose the most suitable, e.g. the newest, not necessarily the most "exposed".</p>
13,597,903
How to clear a JList in Java?
<p>i have a jList in gui where i can add some data with Add button. what i want to add another button called Clear which will clear all elements. i tried this:</p> <pre><code>private void jButtonClearActionPerfomed(java.awt.event.ActionEvent evt) { DefaultListModel listmodel=new DefaultListModel(); jList1 = new JList(listmodel); if(evt.getSource()==jButtonClear) JList.setListData(new String[0]; else listmodel.removeAllElements(); } </code></pre> <p>When I click on Add button this will add elements.</p> <p>When I click on Clear button this remove elements.</p> <p>But when I re-click on Add button, there is nothing in the <code>jList1</code></p>
13,598,015
4
0
null
2012-11-28 04:35:46.843 UTC
5
2020-11-19 23:06:17.237 UTC
2012-11-28 05:26:53.78 UTC
null
418,556
null
1,841,276
null
1
21
java|swing|jlist|defaultlistmodel
65,647
<p>You should not be reinitializing the entire JList widget just to remove some items from it. Instead you should be manipulating the lists model, since changes to it are 'automatically' synchronized back to the UI. Assuming that you are indeed using the <code>DefaultListModel</code>, this is sufficient to implement your 'Clear All' functionality:</p> <pre><code>private void jButtonClearActionPerfomed(java.awt.event.ActionEvent evt) { if(evt.getSource()==jButtonClear) { DefaultListModel listModel = (DefaultListModel) jList1.getModel(); listModel.removeAllElements(); } } </code></pre>
13,450,355
CSS to SASS (or LESS) conversion
<p>Can anyone recommend some CSS to less, or CSS to sass conversion tools? I have found a few .e.g. <a href="http://css2less.cc/" rel="nofollow noreferrer">http://css2less.cc/</a> and <a href="http://css2sass.herokuapp.com/" rel="nofollow noreferrer">http://css2sass.herokuapp.com/</a> but any insight into their reliability (or recommendations of other tools) would be greatly appreciated. I have a large CSS code base for a white label solution which would benefit greatly from having a CSS preprocessor in place but it would be a huge task to manually convert to sass/less.</p> <p>Thanks in advance</p> <p>EDIT: I should emphasize I'm particularly interested in experiences of using a tool (such as those listed above (in the absence of any better ones)) to convert a large CSS code base towards using a CSS preprocessor such as SASS or LESS. Or if any other ways (other than the tools listed) to achieve such a feat are pragmatic. What hurdles did you have to overcome? Is it even worth attempting? Or are such metalanguages only suited to a new project where you can start from scratch?</p>
13,453,653
5
3
null
2012-11-19 08:53:32.053 UTC
15
2017-08-25 10:46:48.64 UTC
2017-08-25 10:46:48.64 UTC
null
7,330,713
null
524,263
null
1
27
css|sass|less
37,156
<p>The good thing about SASS is that you don't need to convert CSS into SASS, since SASS is an extension of CSS.</p> <p>Simply copy and paste and you're good to go.</p> <p>If you're looking to refactor your CSS into well structured SASS files though, thats something i don't think a tool can do.</p>
13,264,726
java syntax: "synchronized (this)"
<p>can you please explain to me this piece of java code? I cannot understand this syntax.</p> <pre><code>synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (Exception e) { } } </code></pre>
13,264,751
6
0
null
2012-11-07 07:03:52.45 UTC
13
2019-02-09 13:37:42.257 UTC
2012-11-07 07:06:17.447 UTC
null
1,151,456
user822931
null
null
1
41
java|syntax|synchronized
45,231
<p>It means that this block of code is <code>synchronized</code> meaning no more than one thread will be able to access the code inside that block.</p> <p>Also <code>this</code> means you can synchronize on the current instance (obtain lock on the current instance).</p> <p>This is what I found in Kathy Sierra's java certification book.</p> <p><em>Because synchronization does hurt concurrency, you don't want to synchronize any more code than is necessary to protect your data. So if the scope of a method is more than needed, you can reduce the scope of the synchronized part to something less than a full method—to just a block.</em></p> <p>Look at the following code snippet:</p> <pre><code>public synchronized void doStuff() { System.out.println("synchronized"); } </code></pre> <p>which can be changed to this:</p> <pre><code>public void doStuff() { //do some stuff for which you do not require synchronization synchronized(this) { System.out.println("synchronized"); // perform stuff for which you require synchronization } } </code></pre> <p>In the second snippet, the synchronization lock is only applied for that block of code instead of the entire method.</p>
13,545,230
How does the try catch finally block work?
<p>In <code>C#</code>, how does a try catch finally block work?</p> <p>So if there is an exception, I know that it will jump to the catch block and then jump to the finally block. </p> <p>But what if there is no error, the catch block wont get run, but does the finally block get run then?</p>
13,545,255
6
6
null
2012-11-24 20:22:32.123 UTC
5
2022-01-29 21:01:14.717 UTC
2017-07-24 08:14:07.23 UTC
null
2,263,683
null
1,497,454
null
1
56
c#|try-catch|try-catch-finally
99,477
<p>Yes, the finally block gets run whether there is an exception or not.</p> <pre> Try [ tryStatements ] [ Exit Try ] [ Catch [ exception [ As type ] ] [ When expression ] [ catchStatements ] [ Exit Try ] ] [ Catch ... ] [ Finally [ finallyStatements ] ] --RUN ALWAYS End Try </pre> <p>See: <a href="http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx</a></p>
13,459,447
Do I need to consider disposing of any IEnumerable<T> I use?
<p>It's recently been pointed out to me that various Linq extension methods (such as <code>Where</code>, <code>Select</code>, etc) return an <code>IEnumerable&lt;T&gt;</code> that also happens to be <code>IDisposable</code>. The following evaluates to <code>True</code></p> <pre><code>new int[2] {0,1}.Select(x =&gt; x*2) is IDisposable </code></pre> <p>Do I need to dispose of the results of a <code>Where</code> expression? </p> <p>Whenever I call a method returning <code>IEnumerable&lt;T&gt;</code>, am I (potentially) accepting responsibility for calling dispose when I've finished with it? </p>
13,459,488
1
0
null
2012-11-19 17:59:23.943 UTC
11
2012-11-20 09:06:30.727 UTC
2012-11-20 09:06:30.727 UTC
null
589,558
null
738,851
null
1
79
c#|linq|ienumerable|dispose
20,294
<p>No, you don't need to worry about this.</p> <p>The fact that they return an <code>IDisposable</code> implementation is an implementation detail - it's because iterator blocks in the Microsoft implementation of the C# compiler happen to create a <em>single</em> type which implements both <code>IEnumerable&lt;T&gt;</code> and <code>IEnumerator&lt;T&gt;</code>. The latter extends <code>IDisposable</code>, which is why you're seeing it.</p> <p>Sample code to demonstrate this:</p> <pre><code>using System; using System.Collections.Generic; public class Test { static void Main() { IEnumerable&lt;int&gt; foo = Foo(); Console.WriteLine(foo is IDisposable); // Prints True } static IEnumerable&lt;int&gt; Foo() { yield break; } } </code></pre> <p>Note that you <em>do</em> need to take note of the fact that <code>IEnumerator&lt;T&gt;</code> implements <code>IDisposable</code>. So any time you iterate explicitly, you should dispose of it properly. For example, if you want to iterate over something and be sure that you'll always have <em>a</em> value, you might use something like:</p> <pre><code>using (var enumerator = enumerable.GetEnumerator()) { if (!enumerator.MoveNext()) { throw // some kind of exception; } var value = enumerator.Current; while (enumerator.MoveNext()) { // Do something with value and enumerator.Current } } </code></pre> <p>(A <code>foreach</code> loop will do this automatically, of course.)</p>
13,610,074
Is there a rule-of-thumb for how to divide a dataset into training and validation sets?
<p>Is there a rule-of-thumb for how to best divide data into training and validation sets? Is an even 50/50 split advisable? Or are there clear advantages of having more training data relative to validation data (or vice versa)? Or is this choice pretty much application dependent?</p> <p>I have been mostly using an 80% / 20% of training and validation data, respectively, but I chose this division without any principled reason. Can someone who is more experienced in machine learning advise me?</p>
13,623,707
7
3
null
2012-11-28 16:42:50.95 UTC
165
2020-12-22 11:12:54.977 UTC
null
null
null
null
896,660
null
1
248
machine-learning
232,244
<p>There are two competing concerns: with less training data, your parameter estimates have greater variance. With less testing data, your performance statistic will have greater variance. Broadly speaking you should be concerned with dividing data such that neither variance is too high, which is more to do with the absolute number of instances in each category rather than the percentage.</p> <p>If you have a total of 100 instances, you're probably stuck with cross validation as no single split is going to give you satisfactory variance in your estimates. If you have 100,000 instances, it doesn't really matter whether you choose an 80:20 split or a 90:10 split (indeed you may choose to use less training data if your method is particularly computationally intensive).</p> <p>Assuming you have enough data to do proper held-out test data (rather than cross-validation), the following is an instructive way to get a handle on variances:</p> <ol> <li>Split your data into training and testing (80/20 is indeed a good starting point)</li> <li>Split the <em>training</em> data into training and validation (again, 80/20 is a fair split).</li> <li>Subsample random selections of your training data, train the classifier with this, and record the performance on the validation set</li> <li>Try a series of runs with different amounts of training data: randomly sample 20% of it, say, 10 times and observe performance on the validation data, then do the same with 40%, 60%, 80%. You should see both greater performance with more data, but also lower variance across the different random samples</li> <li>To get a handle on variance due to the size of test data, perform the same procedure in reverse. Train on all of your training data, then randomly sample a percentage of your <em>validation</em> data a number of times, and observe performance. You should now find that the mean performance on small samples of your validation data is roughly the same as the performance on all the validation data, but the variance is much higher with smaller numbers of test samples</li> </ol>
51,858,807
React-Native Detect Screen Notch
<p>I am using nativebase.io as the UI framework for my app.</p> <h3>My issue</h3> <p>when I input a header for an IOS device, if the iPhone simulator is simulating iPhone X, (where there is a notch on the top of the screen), the Header element automatically detects this and moves the Header element lower on the screen.</p> <p>some android devices also have a similar notch at the top of the screen, but when I use a nativebase.io Header element, it doesn't detect the notch and the Header overlaps the notch.</p> <h3>My question</h3> <p>is there a way on react-native or nativebase.io to detect if the display has a notch? this way I could dynamically offset the Header. </p>
51,860,287
5
5
null
2018-08-15 12:35:26.067 UTC
7
2021-10-21 14:24:27.48 UTC
2019-04-10 06:49:27.66 UTC
null
7,440,820
null
3,104,482
null
1
35
react-native|native-base
52,199
<p>Since the problem is on android, maybe you should try looking into StatusBar.currentHeight. Since the notch generally is part of the status bar, adding a padding on top of the header the size of the status bar should probably do it.</p>
39,417,003
"long vectors not supported yet" error in Rmd but not in R Script
<p>I am operating matrices with R 3.1 and RStudio 0.99.</p> <p>I have my R Script and with cmd+enter it works without problem. </p> <p>I created an Rmd for reporting but I have this error</p> <pre><code>Error in lazyLoadDBinsertVariable(vars[i], from, datafile, ascii, compress, : long vectors not supported yet: ../../../../R-3.3.1/src/main/connections.c:5600 Calls: &lt;Anonymous&gt; ... &lt;Anonymous&gt; -&gt; &lt;Anonymous&gt; -&gt; lazyLoadDBinsertVariable Execution halted </code></pre> <p>Is there a way to bypass that error?</p> <p>This seems to be a dupicate of <a href="https://stackoverflow.com/questions/24335692/large-matrices-in-r-long-vectors-not-supported-yet">Large Matrices in R: long vectors not supported yet</a></p> <p>but the difference is that this only happens when trying to create an Rmd, not in any other case</p>
41,004,082
2
4
null
2016-09-09 17:40:02.977 UTC
8
2021-10-27 19:48:41.573 UTC
2017-08-05 02:16:47.41 UTC
null
559,676
null
3,720,258
null
1
69
r|rstudio|knitr|r-markdown
12,094
<p>I also ran into this today, and fixed it by using <code>cache.lazy = FALSE</code> in the setup chunk in my .Rmd.</p> <p>So what is inside of the first chunk in my R Markdown file looks like this:</p> <pre><code>library(knitr) knitr::opts_chunk$set(cache = TRUE, warning = FALSE, message = FALSE, cache.lazy = FALSE) </code></pre>
20,410,202
JAXB Unmarshalling not working. Expected elements are (none)
<p>I am trying to unmarshal an XML.</p> <p>This is what my XML looks like</p> <pre><code>&lt;DeviceInventory2Response xmlns="http://tempuri.org/"&gt; &lt;DeviceInventory2Result xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;Obj123 xmlns=""&gt; &lt;Id&gt;1&lt;/Id&gt; &lt;Name&gt;abc&lt;/Name&gt; &lt;/Obj123&gt; &lt;Obj456 xmlns=""&gt; . . . </code></pre> <p>I am trying to get Id and Name under Obj123. However when I run my unmarshal command I get the following error.</p> <pre><code>An Error: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://tempuri.org/", local:"DeviceInventory2Response"). Expected elements are (none) </code></pre> <p>My code looks like this in the main class:</p> <pre><code>Obj123 myObj123 = (Obj123) unmarshaller.unmarshal(inputSource); </code></pre> <p>And my class for Obj123 looks like this:</p> <pre><code>package com.myProj.pkg; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name="Obj123") public class Obj123 { private String Id; private String Name; public String getId() { return Id; } public String getName() { return Name; } } </code></pre> <p>I thought by setting my XMLRootElement that I should be able to skip the first 2 lines of my XML but that doesn't seem to be happening. Any ideas?</p> <p>Edit:</p> <p>This is how my JAXB Context is made:</p> <pre><code>JAXBContext jaxbContext = JAXBContext.newInstance(); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Obj123 obj123 = (Obj123) unmarshaller.unmarshal(xmlStreamReader); </code></pre>
20,410,866
3
3
null
2013-12-05 20:39:18.477 UTC
4
2018-12-07 05:18:55.467 UTC
2013-12-06 15:47:38.48 UTC
null
2,332,611
null
2,332,611
null
1
20
java|jaxb|unmarshalling
52,077
<p>JAXB implementations will try to match on the root element of the document (not on a child element). If you want to unmarshal to the middle of an XML document then you can parse the document with StAX advance the <code>XMLStreamReader</code> to the desired element and then unmarshal that.</p> <p><strong>For More Information</strong></p> <ul> <li><a href="http://blog.bdoughan.com/2012/08/handle-middle-of-xml-document-with-jaxb.html" rel="noreferrer">http://blog.bdoughan.com/2012/08/handle-middle-of-xml-document-with-jaxb.html</a></li> </ul> <h2>UPDATE</h2> <blockquote> <p>now I am getting the following error. An Error: javax.xml.bind.UnmarshalException - with linked exception: [javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Obj123"). Expected elements are (none)].</p> </blockquote> <p>A <code>JAXBContext</code> only knows about the classes you tell it about. Instead of:</p> <pre><code>JAXBContext jaxbContext = JAXBContext.newInstance(); </code></pre> <p>You need to do:</p> <pre><code>JAXBContext jaxbContext = JAXBContext.newInstance(Obj123.class); </code></pre>
24,316,355
Multiple controllers with AngularJS in single page app
<p>I want to know is how to use multiple controllers for a single page application. I have tried to figure it out and I've found questions very similar to mine, but there is just a ton of different answers solving a specific problem where you end up not using multiple controllers for a single page app.</p> <p>Is that because it would not be wise to use multiple controllers for a single page? Or is it just not possible?</p> <p>Let's say I already have a kick-ass image carousel controller working the main page, but then I learn how to (let's say) use modals and I need a new controller for that as well (or any other thing I need a controller). What will I do then?</p> <p>I have seen some answers to other questions where they ask about almost the same things as me and people answer "*OMG. Why would you even do that, just do this...". </p> <p>What is the best way, or how do you do it?</p> <p><strong>Edit</strong></p> <p>Many of you are answering to just declare two controllers and then use ng-controller to call it. I use this bit of code below and then call MainCtrl with ng-controller. </p> <pre><code>app.config(function($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: "templates/main.html", controller:'MainCtrl', }) .otherwise({ template: 'does not exists' }); }); </code></pre> <p>Why do I even need to set a controller here if I can just use ng-controller without it? This is what confused me. (and you can't add two controllers this way, I think...)</p>
24,316,464
7
2
null
2014-06-19 21:15:44.3 UTC
37
2018-09-18 11:39:58.897 UTC
2015-07-16 14:41:10.517 UTC
user2539369
55,155
user2539369
null
null
1
105
javascript|angularjs|controller
246,953
<p>What is the problem? To use multiple controllers, just use multiple ngController directives:</p> <pre><code>&lt;div class="widget" ng-controller="widgetController"&gt; &lt;p&gt;Stuff here&lt;/p&gt; &lt;/div&gt; &lt;div class="menu" ng-controller="menuController"&gt; &lt;p&gt;Other stuff here&lt;/p&gt; &lt;/div&gt; </code></pre> <p>You will need to have the controllers available in your application module, as usual.</p> <p>The most basic way to do it could be as simple as declaring the controller functions like this:</p> <pre><code>function widgetController($scope) { // stuff here } function menuController($scope) { // stuff here } </code></pre>
3,478,640
Pass the value of a SELECT to a Javascript function via the onchange event?
<p>I have a HTML page that contains a search box containing a number of textboxes.</p> <p>The first part of the search box is a <strong>SELECT</strong> dropdown list that contains a variety of report types. Each report type requires 1 or more of textboxes to be filled in to filter the query results. My goal is hide the textboxes that are not required by the current report type.</p> <p>How do I pass the currently selected <strong>value</strong> from the <strong>SELECT</strong> to the Javascript function via the <strong>onchange</strong> event?</p> <pre><code>&lt;select name="report_type" onchange="hide();"&gt; &lt;option value="full_history"&gt;Full History&lt;/option&gt; &lt;option value="partial_history"&gt;Partial History&lt;/option&gt; &lt;/select&gt; </code></pre>
3,478,669
2
2
null
2010-08-13 16:02:07.963 UTC
2
2017-02-06 07:20:59.1 UTC
2010-08-13 16:36:03.017 UTC
null
127,776
null
127,776
null
1
11
javascript|html|events|dom
41,725
<pre><code>&lt;select name="report_type" onchange="hide(this.value);"&gt; &lt;option value="full_history"&gt;Full History&lt;/option&gt; &lt;option value="partial_history"&gt;Partial History&lt;/option&gt; &lt;/select&gt; </code></pre> <p>When doing this the function have whatever value the select currently has.</p>
3,220,629
Make git ignore files
<p>I'm trying to make git ignore some of my files and I found one description about how you could do this</p> <blockquote> <p>From: <a href="http://github.com/guides/git-cheat-sheet" rel="noreferrer">http://github.com/guides/git-cheat-sheet</a> TO IGNORE SOME FILES</p> <p>Add a file in the root directory called .gitignore and add some files to it: (comments begin with hash) *.log db/schema.rb db/schema.sql</p> <p>Git automatically ignores empty directories. If you want to have a log/ directory, but want to ignore all the files in it, add the following lines to the root .gitignore: (lines beginning with ‘!’ are exceptions)</p> <p>log/* !.gitignore</p> <p>Then add an empty .gitignore in the empty directory:</p> <p>touch log/.gitignore</p> </blockquote> <p>So I made a file called .gitignore in my folder for my project and wrote the following in it:</p> <pre><code>phpMyAdmin/* nbproject/* inc/mysql_config.php !.gitignore </code></pre> <p>But when I commit, the files isent excluded from the commit...</p>
3,220,653
2
3
null
2010-07-10 19:53:30.447 UTC
8
2016-11-23 14:24:49.023 UTC
2013-05-15 16:30:00.463 UTC
null
322,020
null
360,186
null
1
20
git
38,462
<p>According to <a href="http://git-scm.com/docs/gitignore" rel="noreferrer"><strong>man gitignore</strong></a>:</p> <blockquote> <h3>DESCRIPTION</h3> <p>A <code>gitignore</code> file specifies intentionally untracked files that git should ignore. Note that all the <code>gitignore</code> files really concern only files that are not already tracked by git; in order to ignore uncommitted changes in already tracked files, please refer to the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-update-index.html" rel="noreferrer"><em>git update-index --assume-unchanged</em></a> documentation.</p> </blockquote> <p>So it doesn't help if you've already added them. It's mostly for preventing the addition in the first place. That way, you can ignore <code>.tmp</code> files and add a whole directory without worrying that you'll add the <code>.tmp</code> files.</p> <p>I believe you can remove them from the index with:</p> <pre><code>git rm --cached file_to_stop_tracking_but_dont_want_to_delete.txt </code></pre> <p><strong>Update:</strong></p> <p>Also, the <code>.gitignore</code> needs to be at the base directory or at least above where those directories are. Also, take the "*" out of the directories:</p> <pre><code>phpMyAdmin/ nbproject/ inc/mysql_config.php !.gitignore </code></pre> <p>And be careful of <code>phpMyAdmin/</code> vs <code>/phpMyAdmin</code> vs <code>phpMyAdmin</code>. Also from <a href="http://git-scm.com/docs/gitignore" rel="noreferrer"><strong>man gitignore</strong></a>:</p> <blockquote> <ul> <li><p>If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, <code>foo/</code> will match a directory <code>foo</code> and paths underneath it, but will not match a regular file or a symbolic link <code>foo</code> (this is consistent with the way how pathspec works in general in git).</p></li> <li><p>If the pattern does not contain a slash <code>/</code>, git treats it as a shell glob pattern and checks for a match against the pathname without leading directories.</p></li> <li><p>Otherwise, git treats the pattern as a shell glob suitable for consumption by <a href="http://www.opengroup.org/onlinepubs/000095399/functions/fnmatch.html" rel="noreferrer"><code>fnmatch(3)</code></a> with the <code>FNM_PATHNAME</code> flag: wildcards in the pattern will not match a <code>/</code> in the pathname. For example, <code>Documentation/*.html</code> matches <code>Documentation/git.html</code> but not <code>Documentation/ppc/ppc.html</code>. A leading slash matches the beginning of the pathname; for example, <code>/*.c</code> matches <code>cat-file.c</code> but not <code>mozilla-sha1/sha1.c</code>.</p></li> </ul> </blockquote>
16,455,801
Ruby on Rails - Make Slim the Default Template
<p>I am working on a Ruby on Rails project and am needing to customize default views provided by Gems.</p> <p>The requirement is to use Slim for template. I understand that ERB is the default template engine for Rails. </p> <p>As per my observation, the priority is for ERB and if not it will use Slim/Haml views.</p> <p>I am interested in knowing if it is possible to set Slim as the default instead of the ERB? </p> <p>How can this be achieved so that when I create a local version of a template in Slim it will override the template provided by the gem.</p> <p>Any clue will be appreciated.</p>
16,456,236
2
0
null
2013-05-09 06:31:35.243 UTC
4
2014-07-29 03:31:47.87 UTC
null
null
null
null
777,880
null
1
28
ruby-on-rails-3.2|slim-lang
15,476
<p>You can use "slim-rails" gem which is built for generating slim template as default.</p> <p><a href="https://github.com/slim-template/slim-rails">https://github.com/slim-template/slim-rails</a></p> <p>Just replace <code>gem 'slim'</code> by <code>gem 'slim-rails'</code> in your Gemfile.</p>
13,207,601
Compare strings in two different arraylist (JAVA)
<p>This is a pice of my code : </p> <pre><code> ArrayList&lt;String&gt; Alist= new ArrayList&lt;String&gt;(); ArrayList&lt;String&gt; Blist= new ArrayList&lt;String&gt;(); Alist.add("gsm"); Alist.add("tablet"); Alist.add("pc"); Alist.add("mouse"); Blist.add("gsm"); Blist.add("something"); Blist.add("pc"); Blist.add("something"); </code></pre> <p>so i have two array list i want to compare all items and check if they are <strong>not equal</strong> and if they are to <strong>print out only the items that are not equal</strong>.</p> <p>so i make something like this: </p> <p><a href="http://postimage.org/image/adxix2i13/" rel="nofollow">http://postimage.org/image/adxix2i13/</a> sorry for the image but i have somekind of bug when i post here a for looop.</p> <p>and the result is : </p> <pre><code>not equals..:tablet not equals..:pc not equals..:mouse not equals..:gsm not equals..:tablet not equals..:pc not equals..:mouse not equals..:gsm not equals..:tablet not equals..:pc not equals..:mouse not equals..:gsm not equals..:tablet </code></pre> <p>i want to print only the 2 that are not equal in the example they are gsm and pc</p> <pre><code>not equals..:gsm not equals..:pc </code></pre>
13,207,640
10
2
null
2012-11-03 08:57:14.99 UTC
2
2019-06-28 09:03:46.383 UTC
null
null
null
null
1,792,440
null
1
4
java|string|arraylist|compare
40,692
<p>Don't use <code>!=</code> to compare strings. Use the <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#equals%28java.lang.Object%29" rel="nofollow">equals</a> method :</p> <pre><code>if (! Blist.get(i).equals(Alist.get(j)) </code></pre> <p>But this wouldn't probably fix your algorithmic problem (which isn't clear at all).</p> <p>If what you want is know what items are the same at the same position, you could use a simple loop :</p> <pre><code>int sizeOfTheShortestList = Math.min(Alist.size(), Blist.size()); for (int i=0; i&lt;sizeOfTheShortestList; i++) { if (Blist.get(i).equals(Alist.get(i))) { System.out.println("Equals..: " + Blist.get(i)); } } </code></pre> <p>If you want to get items that are in both lists, use</p> <pre><code>for (int i = 0; i &lt; Alist.size(); i++) { if (Blist.contains(Alist.get(i))) { System.out.println("Equals..: " + Alist.get(i)); } } </code></pre>
17,386,304
Change height of footer css
<p>Problem: I don't know how to change the height of the footer when using <code>reset.css</code>, the height property for the footer div doesn't change anything.</p> <p>You can clone this locally and <a href="https://github.com/eveo/Sam" rel="nofollow">check it out here</a></p> <p>HTML</p> <pre><code>&lt;div class="wrapper"&gt; &lt;p&gt;Your website content here.&lt;/p&gt; &lt;/div&gt; &lt;div id="footer"&gt; &lt;p&gt;&amp;copy; 2013 Friend | Design and Development. All Rights Reserved.&lt;/p&gt; &lt;/div&gt; </code></pre> <p>CSS - style.css</p> <pre><code>html, body { height: 100%; font-family: 'Arial', Helvetica; } .wrapper { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -4em; } #footer { background: #444444; height: 100px; font-family: 'Open Sans', sans-serif; color: #FFFFFF; padding: 20px; } </code></pre> <p>RESET.css</p> <pre><code>/* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 License: none (public domain) */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } </code></pre>
17,386,708
3
0
null
2013-06-30 01:37:47.837 UTC
1
2013-06-30 03:04:25.25 UTC
2013-06-30 02:11:07.587 UTC
null
1,273,169
null
1,273,169
null
1
4
html|css
59,267
<p>If you match the negative bottom margin on .wrapper to the height of your footer, the entire footer should show.</p> <p>or, if you're going for a footer that floats at the bottom or the page, you can do this:</p> <pre><code>&lt;div class="wrapper"&gt; &lt;div class="content"&gt; &lt;p&gt;Your website content here.&lt;/p&gt; &lt;/div&gt; &lt;div id="footer"&gt; &lt;p&gt;&amp;copy; 2013 Friend | Design and Development. All Rights Reserved.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and in css</p> <pre><code>.wrapper { min-height: 100%; position: relative; } .content { /* padding the footer adds 40 to footer height */ padding-bottom: 140px; } #footer { position: absolute; bottom: 0; background: #444444; height: 100px; font-family: 'Open Sans', sans-serif; color: #FFFFFF; padding: 20px; } </code></pre> <p>matching height to .content padding</p> <p>( untested, i'll fiddle it if needed )</p>
24,536,533
How can I parse a JSON string that would cause illegal C# identifiers?
<p>I have been using <a href="http://james.newtonking.com/json">NewtonSoft JSON Convert</a> library to parse and convert JSON string to C# objects. But now I have came across a really awkward JSON string and I am unable to convert it into C# object because I cant make a C# class out of this JSON string.</p> <p>Here is the JSON string</p> <pre><code>{ "1": { "fajr": "04:15", "sunrise": "05:42", "zuhr": "12:30", "asr": "15:53", "maghrib": "19:18", "isha": "20:40" }, "2": { "fajr": "04:15", "sunrise": "05:42", "zuhr": "12:30", "asr": "15:53", "maghrib": "19:18", "isha": "20:41" } } </code></pre> <p>The C# class required to parse this JSON string should be like this:</p> <pre><code>public class 1 { public string fajr { get; set; } public string sunrise { get; set; } public string zuhr { get; set; } public string asr { get; set; } public string maghrib { get; set; } public string isha { get; set; } } public class 2 { public string fajr { get; set; } public string sunrise { get; set; } public string zuhr { get; set; } public string asr { get; set; } public string maghrib { get; set; } public string isha { get; set; } } </code></pre> <p>But it cant be a true C# class because we know that Class names cannot start with a number.</p> <p>It will be really great if anyone can suggest how to parse such type of json string.</p>
24,536,564
3
5
null
2014-07-02 16:35:37.53 UTC
8
2020-05-24 02:11:42.097 UTC
2014-07-02 21:15:56.223 UTC
null
1,146,608
null
1,949,475
null
1
45
c#|json|json.net
6,429
<p>You can deserialize to a dictionary.</p> <pre><code>public class Item { public string fajr { get; set; } public string sunrise { get; set; } public string zuhr { get; set; } public string asr { get; set; } public string maghrib { get; set; } public string isha { get; set; } } </code></pre> <hr> <pre><code>var dict = JsonConvert.DeserializeObject&lt;Dictionary&lt;string, Item&gt;&gt;(json); </code></pre>
21,514,387
split strings into many strings by newline?
<p>i have incoming data that needs to be split into multiple values...ie.</p> <blockquote> <p>2345\n564532\n345634\n234 234543\n1324 2435\n</p> </blockquote> <p>The length is inconsistent when i receive it, the spacing is inconsistent when it is present, and i want to analyze the last 3 digits before each \n. how do i break off the string and turn it into a new string? like i said, this round, it may have 3 \n commands, next time, it may have 10, how do i create 3 new strings, analyze them, then destroy them before the next 10 come in? </p> <pre><code>string[] result = x.Split('\r'); result = x.Split(splitAtReturn, StringSplitOptions.None); string stringToAnalyze = null; foreach (string s in result) { if (s != "\r") { stringToAnalyze += s; } else { how do i analyze the characters here? } } </code></pre>
21,514,504
4
4
null
2014-02-02 18:20:49.903 UTC
3
2015-04-08 19:14:05.543 UTC
2014-02-02 18:47:14.587 UTC
null
2,804,613
null
501,344
null
1
7
c#|string|newline|string-split
43,912
<p>You could use the <a href="http://msdn.microsoft.com/en-us/library/tabh47cf%28v=vs.110%29.aspx?cs-save-lang=1&amp;cs-lang=csharp#code-snippet-2">string.Split method</a>. In particular I suggest to use the overload that use a string array of possible separators. This because splitting on the newline character poses an unique problem. In you example all the newline chars are simply a '\n', but for some OS the newline char is '\r\n' and if you can't rule out the possibility to have the twos in the same file then</p> <pre><code>string test = "2345\n564532\n345634\n234 234543\n1324 2435\n"; string[] result = test.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries); </code></pre> <p>Instead if your are certain that the file contains only the newline separator allowed by your OS then you could use </p> <pre><code>string test = "2345\n564532\n345634\n234 234543\n1324 2435\n"; string[] result = test.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries); </code></pre> <p>The StringSplitOptions.RemoveEmptyEntries allows to capture a pair of consecutive newline or an ending newline as an empty string.</p> <p>Now you can work on the array examining the last 3 digits of every string</p> <pre><code>foreach(string s in result) { // Check to have at least 3 chars, no less // otherwise an exception will occur int maxLen = Math.Min(s.Length, 3); string lastThree = s.Substring(s.Length - maxLen, maxLen); ... work on last 3 digits } </code></pre> <p>Instead, if you want to work only using the index of the newline character without splitting the original string, you could use string.IndexOf in this way</p> <pre><code>string test = "2345\n564532\n345634\n234 234543\n1324 2435\n"; int pos = -1; while((pos = test.IndexOf('\n', pos + 1)) != -1) { if(pos &lt; test.Length) { string last3part = test.Substring(pos - 3, 3); Console.WriteLine(last3part); } } </code></pre>
21,499,843
JavaScript - Validate date input so it's only either current or the future
<p>I'm trying to validate a date input box so that it only accepts the current or future dates. So far I've been struggling to find answers which definitively does this.</p> <p>Here is the HTML for the input box, excluding the <code>&lt;form&gt;</code> tags:</p> <pre><code>&lt;p&gt; &lt;label&gt;Date:&lt;/label&gt; &lt;br&gt; &lt;input type="number" name="date" placeholder="DD/MM/YYYY" onchange="checkDate()"&gt; &lt;/p&gt; &lt;div id="datewarn"&gt;&lt;/div&gt; </code></pre> <p>Here is JavaScript code that I'm using which validates whether the input is in the format DD/MM/YYYY and that the numbers entered in are valid calender numbers, but this still accepts past dates.</p> <pre><code>function checkDate() { var valid = true; var redate = /(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d/; if (!redate.test(document.bookingsform.date.value)) { document.bookingsform.date.style.border = "1px solid red"; document.getElementById("datewarn").innerHTML = "Enter a date in the format DD/MM/YYYY."; document.bookingsform.date.title = "Please enter a date in the format DD/MM/YYYY."; document.getElementById("datewarn").style.display = "block"; valid = false; } else { document.bookingsform.date.style.border = "1px inset #EBE9ED"; document.bookingsform.date.style.borderRadius = "2px"; document.getElementById("datewarn").style.display = "none"; } } </code></pre> <p>The research that I have done suggests using the date.js library? Is this an inbuilt library or this something I have to get?</p> <p>This can only be JavaScript, no jQuery.</p> <p>EDIT: Sorry, forgot to add the RegEx variable.</p>
21,500,313
2
5
null
2014-02-01 15:20:23.98 UTC
1
2018-05-10 06:53:18.573 UTC
null
null
null
null
2,915,050
null
1
1
javascript|validation|date
56,902
<p>This is a function to tell, if the date you are entering is future date or not.</p> <p><strong>JS Function and use example:</strong></p> <pre><code>function isFutureDate(idate){ var today = new Date().getTime(), idate = idate.split("/"); idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime(); return (today - idate) &lt; 0; } // Demo example console.log(isFutureDate("02/03/3014")); // true console.log(isFutureDate("01/01/2014")); // false </code></pre> <p><strong>Here is implementation for you:</strong></p> <pre><code>function checkDate(){ var idate = document.getElementById("date"), resultDiv = document.getElementById("datewarn"), dateReg = /(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/]201[4-9]|20[2-9][0-9]/; if(!dateReg.test(idate.value)){ resultDiv.innerHTML = "Invalid date!"; resultDiv.style.color = "red"; return; } if(isFutureDate(idate.value)){ resultDiv.innerHTML = "Entered date is a future date"; resultDiv.style.color = "red"; } else { resultDiv.innerHTML = "It's a valid date"; resultDiv.style.color = "green"; } } </code></pre> <p><strong>test it with this HTML:</strong></p> <pre><code>&lt;p&gt; &lt;label&gt;Date:&lt;/label&gt; &lt;br /&gt; &lt;input type="text" name="date" id="date" placeholder="DD/MM/YYYY" onkeyup="checkDate()" /&gt; &lt;/p&gt; &lt;div id="datewarn"&gt;&lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/ashishanexpert/LaL9W/5/" rel="nofollow noreferrer"><kbd>Working Demo</kbd></a>: <a href="http://jsfiddle.net/ashishanexpert/LaL9W/5/" rel="nofollow noreferrer">http://jsfiddle.net/ashishanexpert/LaL9W/5/</a></p>
21,917,308
Why there needs to be a $ in calls like "runSomeMonad $ do ..."?
<p>Apparently the only possible interpretation of <code>runSomeMonad do ...</code> is <code>runSomeMonad (do ...)</code>. Why isn't the first variant allowed by the Haskell syntax? Is there some case where <code>foo do bar</code> could be actually ambiguous?</p>
21,921,191
1
5
null
2014-02-20 19:12:41.303 UTC
3
2014-03-04 19:37:04.763 UTC
null
null
null
null
1,333,025
null
1
32
haskell|syntax|monads|do-notation
2,023
<p>Note that you can observe this effect with not just <code>do</code>, but also <code>let</code>, <code>if</code>, <code>\</code>, <code>case</code>, the extensions <code>mdo</code> and <code>proc</code>…and the dread unary <code>-</code>. I cannot think of a case in which this is ambiguous <em>except</em> for unary <code>-</code>. Here’s how the grammar is defined in the <a href="http://www.haskell.org/onlinereport/haskell2010/haskellch3.html" rel="nofollow noreferrer">Haskell 2010 Language Report, §3: Expressions</a>.</p> <pre><code>exp → infixexp :: [context =&gt;] type | infixexp infixexp → lexp qop infixexp | - infixexp | lexp lexp → \ apat1 … apatn -&gt; exp | let decls in exp | if exp [;] then exp [;] else exp | case exp of { alts } | do { stmts } | fexp fexp → [fexp] aexp aexp → ( exp ) | … </code></pre> <p>There just happens to be no case defined in <code>fexp</code> (function application) or <code>aexp</code> (literal expression) that allows an unparenthesised <code>lexp</code> (lambda, <code>let</code>, etc.). I would consider this a bug in the grammar.</p> <p>Fixing this would also remove the need for <a href="https://stackoverflow.com/a/9469942/246886">the <code>$</code> typing hack</a>.</p>
17,560,201
Join List<string> Together with Commas Plus "and" for Last Element
<p>I know I could figure a way out but I am wondering if there is a more concise solution. There's always <code>String.Join(", ", lList)</code> and <code>lList.Aggregate((a, b) =&gt; a + ", " + b);</code> but I want to add an exception for the last one to have <code>", and "</code> as its joining string. Does <code>Aggregate()</code> have some index value somewhere I can use? Thanks.</p>
17,560,245
6
0
null
2013-07-09 23:50:23.457 UTC
3
2022-05-26 11:00:29.237 UTC
null
null
null
null
2,285,405
null
1
29
c#|list
15,433
<p>You could do this</p> <pre><code>string finalString = String.Join(", ", myList.ToArray(), 0, myList.Count - 1) + ", and " + myList.LastOrDefault(); </code></pre>
17,347,179
jQuery DataTable - Hide rows the intended way
<p>We are currently working on a web-based CRM. The project is going great except for a frustrating issue.</p> <p>we are using the <a href="http://www.datatables.net/" rel="nofollow noreferrer">DataTable jQuery plug-in</a> for almost every <em>sortable</em> tables in the application. Here is a list of active incidents.</p> <p><img src="https://i.stack.imgur.com/n0RgH.png" alt="Open incidents"></p> <p>As you can see, the third column represents the type of the incidents (ticket, change request, service request, etc.) </p> <p>Users requested a filter box placed on top of the previous table to filter the incidents types. For instance, if you choose "Ticket only", every other type will be hidden. Up until now, everything is working.</p> <p>In order to do so, every row has a CSS class that represents the incident type. </p> <ul> <li>Row #1 : class="ticket"</li> <li>Row #2 : class="changeRequest"</li> </ul> <p>When the filter box value changes, the following javascript code is executed </p> <pre><code>$('table.sortable').each(function() { for (var i = 0; i &lt; rows.length; i++) { if ($(rows[i]).hasClass(vClass)) $(rows[i]).hide(); } }); </code></pre> <p>where </p> <ul> <li>vClass = The CSS class representing the incident type </li> <li>rows = All dataTable rows, got from "$(SomeDatatable).dataTable().fnGetNodes();"</li> <li>$('table.sortable') = All dataTables</li> </ul> <p>Now, fasten your seatbelts (French liner). When you implicitly hide a row, dataTable still counts it. Here is the fabulous result.</p> <p><img src="https://i.stack.imgur.com/1eXZs.png" alt="Datatable on drugs"></p> <p>That being explained, there goes the main question : How am I supposed to tell dataTable that I want to hide rows without deleting them forever? DataTable already has a filter box but I need it to work independently along with the type filter box (not in image). </p> <p>Is there a way to add a second filter, maybe?</p>
17,347,493
3
2
null
2013-06-27 15:24:47.8 UTC
5
2017-06-20 19:57:04.59 UTC
2017-06-20 19:57:04.59 UTC
null
3,885,376
null
1,241,097
null
1
32
javascript|jquery|datatables
23,822
<p>You need to write a custom filter for that table. Example:</p> <pre><code>$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) { if ($(oSettings.nTable).hasClass('do-exclude-filtering')) { return aData[16] == '' || $('#chkShowExcluded').is(':checked'); } else return true; }); </code></pre> <p>In that example we dynamically add and remove the 'do-exclude-filtering' class to a table, and if it has the class, it checks each row to see if a given cell has a value. The logic can be anything you can dream up, just keep it fast (this is executed for every row, on every draw, for every table on the page (note it's added to a 'global' array in DT, not an individual instance)</p> <p>Return <code>true</code> to include the row, return <code>false</code> to hide the row</p> <p>Here is the datatable reference to use the afnFiltering capabilities: <a href="http://datatables.net/development/filtering">http://datatables.net/development/filtering</a></p> <p>The advantage to this instead of using <code>.fnFilter()</code> is that this works ALONG WITH, so the user can still use the filtering box in the top right (by default, I see yours is bottom right) to further filter the results you choose to show them. In other words, say you hide all 'completed' items, so the user only sees 'incomplete' items in the table. Then they can still filter the table for 'laptop' and see only the rows that are BOTH incomplete and have 'laptop' in their description</p>
17,608,979
Add just a top border to an UIView with Quartzcore/layer?
<p>Is it possible to add a border just on top of a UIView, if so, how please?</p>
17,609,496
8
5
null
2013-07-12 06:46:32.507 UTC
8
2020-11-01 16:20:18.747 UTC
null
null
null
null
2,507,331
null
1
37
ios|uiview|layer
35,125
<p>i've find solution for me, here's the tricks :</p> <pre><code>CGSize mainViewSize = self.view.bounds.size; CGFloat borderWidth = 1; UIColor *borderColor = [UIColor colorWithRed:37.0/255 green:38.0/255 blue:39.0/255 alpha:1.0]; UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, mainViewSize.width, borderWidth)]; topView.opaque = YES; topView.backgroundColor = borderColor; topView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin; [self.view addSubview:topView]; </code></pre>
17,143,985
Twitter API error 215
<p>Today, we discovered one of my clients Twitter feeds became broken.</p> <p>I have tried switching to using the new API 1.1, but get the following error:</p> <pre><code>{"errors":[{"message":"Bad Authentication data","code":215}]} </code></pre> <p>Even using their own example generates the same response:</p> <pre><code>https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&amp;count=2 </code></pre> <p>I am referencing the following documentation.</p> <pre><code>https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline </code></pre> <p>Any idea what's up with this?</p> <p>Thanks, Mikey</p>
17,145,712
2
1
null
2013-06-17 09:08:41.36 UTC
9
2020-07-30 14:11:07.753 UTC
null
null
null
null
695,749
null
1
49
json|twitter
89,180
<p>So, it seems Twitter's latest API 1.1 does <strong>not allow</strong> access without authentication - even for data that is seemingly public...like the latest 3 tweets from a timeline.</p> <p>The best article I have found on this (which gives a great solution) for read-access can be found here:</p> <p><a href="http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/">http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/</a></p> <p>I have followed the steps in the article above and can confirm it works great.</p> <p>An interesting point to note, is that now, because you have to use <em>access tokens</em> and <em>secret keys</em>; all requests must be made with a server-side script. Prior to this I was using jQuery to make an AJAX request on Twitters JSON API directly. Now, you must AJAX request a dynamic script on your own website, if you wish to go down a Javascript route.</p>
18,304,722
Python: find contour lines from matplotlib.pyplot.contour()
<p>I'm trying to find (but not draw!) contour lines for some data: </p> <pre><code>from pprint import pprint import matplotlib.pyplot z = [[0.350087, 0.0590954, 0.002165], [0.144522, 0.885409, 0.378515], [0.027956, 0.777996, 0.602663], [0.138367, 0.182499, 0.460879], [0.357434, 0.297271, 0.587715]] cn = matplotlib.pyplot.contour(z) </code></pre> <p>I know <code>cn</code> contains the contour lines I want, but I can't seem to get to them. I've tried several things: </p> <pre><code>print dir(cn) pprint(cn.collections[0]) print dir(cn.collections[0]) pprint(cn.collections[0].figure) print dir(cn.collections[0].figure) </code></pre> <p>to no avail. I know <code>cn</code> is a <code>ContourSet</code>, and <code>cn.collections</code> is an array of <code>LineCollection</code>s. I would think a <code>LineCollection</code> is an array of line segments, but I can't figure out how to extract those segments. </p> <p>My ultimate goal is to create a KML file that plots data on a world map, and the contours for that data as well. </p> <p>However, since some of my data points are close together, and others are far away, I need the actual polygons (linestrings) that make up the contours, not just a rasterized image of the contours. </p> <p>I'm somewhat surprised <code>qhull</code> doesn't do something like this. </p> <p>Using Mathematica's <code>ListContourPlot</code> and then exporting as SVG works, but I want to use something open source. </p> <p>I can't use the well-known CONREC algorithm because my data isn't on a mesh (there aren't always multiple y values for a given x value, and vice versa). </p> <p>The solution doesn't have to python, but does have to be open source and runnable on Linux. </p>
18,309,914
4
0
null
2013-08-18 23:26:19.723 UTC
19
2022-03-03 14:24:28.233 UTC
2015-04-24 21:11:07.817 UTC
null
1,461,210
user354134
17,394,346
null
1
25
python|numpy|matplotlib|spatial|contour
23,558
<p>You can get the vertices back by looping over collections and paths and using the <code>iter_segments()</code> method of <a href="http://matplotlib.org/api/path_api.html#matplotlib.path.Path"><code>matplotlib.path.Path</code></a>.</p> <p>Here's a function that returns the vertices as a set of nested lists of contour lines, contour sections and arrays of x,y vertices:</p> <pre><code>import numpy as np def get_contour_verts(cn): contours = [] # for each contour line for cc in cn.collections: paths = [] # for each separate section of the contour line for pp in cc.get_paths(): xy = [] # for each segment of that section for vv in pp.iter_segments(): xy.append(vv[0]) paths.append(np.vstack(xy)) contours.append(paths) return contours </code></pre> <hr> <h2>Edit:</h2> <p>It's also possible to compute the contours without plotting anything using the undocumented <code>matplotlib._cntr</code> C module:</p> <pre><code>from matplotlib import pyplot as plt from matplotlib import _cntr as cntr z = np.array([[0.350087, 0.0590954, 0.002165], [0.144522, 0.885409, 0.378515], [0.027956, 0.777996, 0.602663], [0.138367, 0.182499, 0.460879], [0.357434, 0.297271, 0.587715]]) x, y = np.mgrid[:z.shape[0], :z.shape[1]] c = cntr.Cntr(x, y, z) # trace a contour at z == 0.5 res = c.trace(0.5) # result is a list of arrays of vertices and path codes # (see docs for matplotlib.path.Path) nseg = len(res) // 2 segments, codes = res[:nseg], res[nseg:] fig, ax = plt.subplots(1, 1) img = ax.imshow(z.T, origin='lower') plt.colorbar(img) ax.hold(True) p = plt.Polygon(segments[0], fill=False, color='w') ax.add_artist(p) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/HVzJ3.png" alt="enter image description here"></p>
12,187,124
Writing video + generated audio to AVAssetWriterInput, audio stuttering
<p>I'm generating a video from a Unity app on iOS. I'm using iVidCap, which uses AVFoundation to do this. That side is all working fine. Essentially the video is rendered by using a texture render target and passing the frames to an Obj-C plugin.</p> <p>Now I need to add audio to the video. The audio is going to be sound effects that occur at specific times and maybe some background sound. The files being used are actually assets internal to the Unity app. I could potentially write these to phone storage and then generate an AVComposition, but my plan was to avoid this and composite the audio in floating point format buffers (obtaining audio from audio clips is in float format). I might be doing some on the fly audio effects later on.</p> <p>After several hours I managed to get audio to be recorded and play back with the video... but it stutters.</p> <p>Currently I'm just generating a square wave for the duration of each frame of video and writing it to an AVAssetWriterInput. Later, I'll generate the audio I actually want.</p> <p>If I generate one massive sample, I don't get the stuttering. If I write it in blocks (which I'd much prefer over allocating a massive array), then the blocks of audio seem to clip each other:</p> <p><img src="https://i.stack.imgur.com/Ajahl.png" alt="Glitch" /></p> <p>I can't seem to figure out why this is. I am pretty sure I am getting the timestamp for the audio buffers correct, but maybe I'm doing this whole part incorrectly. Or do I need some flags to get the video to sync to the audio? I cant see that this is the problem, since I can see the problem in a wave editor after extracting the audio data to a wav.</p> <p>Relevant code for writing audio:</p> <pre class="lang-objectivec prettyprint-override"><code>- (id)init { self = [super init]; if (self) { // [snip] rateDenominator = 44100; rateMultiplier = rateDenominator / frameRate; sample_position_ = 0; audio_fmt_desc_ = nil; int nchannels = 2; AudioStreamBasicDescription audioFormat; bzero(&amp;audioFormat, sizeof(audioFormat)); audioFormat.mSampleRate = 44100; audioFormat.mFormatID = kAudioFormatLinearPCM; audioFormat.mFramesPerPacket = 1; audioFormat.mChannelsPerFrame = nchannels; int bytes_per_sample = sizeof(float); audioFormat.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsAlignedHigh; audioFormat.mBitsPerChannel = bytes_per_sample * 8; audioFormat.mBytesPerPacket = bytes_per_sample * nchannels; audioFormat.mBytesPerFrame = bytes_per_sample * nchannels; CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &amp;audioFormat, 0, NULL, 0, NULL, NULL, &amp;audio_fmt_desc_ ); } return self; } - (BOOL)beginRecordingSession { NSError* error = nil; isAborted = false; abortCode = No_Abort; // Allocate the video writer object. videoWriter = [[AVAssetWriter alloc] initWithURL:[self getVideoFileURLAndRemoveExisting: recordingPath] fileType:AVFileTypeMPEG4 error:&amp;error]; if (error) { NSLog(@&quot;Start recording error: %@&quot;, error); } // Configure video compression settings. NSDictionary* videoCompressionProps = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithDouble:1024.0 * 1024.0], AVVideoAverageBitRateKey, [NSNumber numberWithInt:10],AVVideoMaxKeyFrameIntervalKey, nil]; // Configure video settings. NSDictionary* videoSettings = [NSDictionary dictionaryWithObjectsAndKeys: AVVideoCodecH264, AVVideoCodecKey, [NSNumber numberWithInt:frameSize.width], AVVideoWidthKey, [NSNumber numberWithInt:frameSize.height], AVVideoHeightKey, videoCompressionProps, AVVideoCompressionPropertiesKey, nil]; // Create the video writer that is used to append video frames to the output video // stream being written by videoWriter. videoWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings] retain]; //NSParameterAssert(videoWriterInput); videoWriterInput.expectsMediaDataInRealTime = YES; // Configure settings for the pixel buffer adaptor. NSDictionary* bufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil]; // Create the pixel buffer adaptor, used to convert the incoming video frames and // append them to videoWriterInput. avAdaptor = [[AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput sourcePixelBufferAttributes:bufferAttributes] retain]; [videoWriter addInput:videoWriterInput]; // &lt;pb&gt; Added audio input. sample_position_ = 0; AudioChannelLayout acl; bzero( &amp;acl, sizeof(acl)); acl.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo; NSDictionary* audioOutputSettings = nil; audioOutputSettings = [NSDictionary dictionaryWithObjectsAndKeys: [ NSNumber numberWithInt: kAudioFormatMPEG4AAC ], AVFormatIDKey, [ NSNumber numberWithInt: 2 ], AVNumberOfChannelsKey, [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey, [ NSNumber numberWithInt: 64000 ], AVEncoderBitRateKey, [ NSData dataWithBytes: &amp;acl length: sizeof( acl ) ], AVChannelLayoutKey, nil]; audioWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType: AVMediaTypeAudio outputSettings: audioOutputSettings ] retain]; //audioWriterInput.expectsMediaDataInRealTime = YES; audioWriterInput.expectsMediaDataInRealTime = NO; // seems to work slightly better [videoWriter addInput:audioWriterInput]; rateDenominator = 44100; rateMultiplier = rateDenominator / frameRate; // Add our video input stream source to the video writer and start it. [videoWriter startWriting]; [videoWriter startSessionAtSourceTime:CMTimeMake(0, rateDenominator)]; isRecording = true; return YES; } - (int) writeAudioBuffer:(float *)samples sampleCount:(size_t)n channelCount:(size_t)nchans { if (![self waitForAudioWriterReadiness]) { NSLog(@&quot;WARNING: writeAudioBuffer dropped frame after wait limit reached.&quot;); return 0; } //NSLog(@&quot;writeAudioBuffer&quot;); OSStatus status; CMBlockBufferRef bbuf = NULL; CMSampleBufferRef sbuf = NULL; size_t buflen = n * nchans * sizeof(float); // Create sample buffer for adding to the audio input. status = CMBlockBufferCreateWithMemoryBlock( kCFAllocatorDefault, samples, buflen, kCFAllocatorNull, NULL, 0, buflen, 0, &amp;bbuf); if (status != noErr) { NSLog(@&quot;CMBlockBufferCreateWithMemoryBlock error&quot;); return -1; } CMTime timestamp = CMTimeMake(sample_position_, 44100); sample_position_ += n; status = CMAudioSampleBufferCreateWithPacketDescriptions(kCFAllocatorDefault, bbuf, TRUE, 0, NULL, audio_fmt_desc_, 1, timestamp, NULL, &amp;sbuf); if (status != noErr) { NSLog(@&quot;CMSampleBufferCreate error&quot;); return -1; } BOOL r = [audioWriterInput appendSampleBuffer:sbuf]; if (!r) { NSLog(@&quot;appendSampleBuffer error&quot;); } CFRelease(bbuf); CFRelease(sbuf); return 0; } </code></pre> <p>Any ideas on what's going on?</p> <p>Should I be creating/appending samples in a different way?</p> <p>Is it something to do with the AAC compression? It doesn't work if I try to use uncompressed audio (it throws).</p> <p>As far as I can tell, I'm calculating the PTS correctly. Why is this even required for the audio channel? Shouldn't the video be synced to the audio clock?</p> <hr/> <h3>UPDATE</h3> <p>I've tried providing the audio in fixed blocks of 1024 samples, since this is the size of the DCT used by the AAC compressor. Doesn't make any difference.</p> <p>I've tried pushing all the blocks in one go before writing any video. Doesn't work.</p> <p>I've tried using CMSampleBufferCreate for the remaining blocks and CMAudioSampleBufferCreateWithPacketDescriptions for the first block only. No change.</p> <p>And I've tried combinations of these. Still not right.</p> <hr/> <h3>SOLUTION</h3> <p>It appears that:</p> <pre><code>audioWriterInput.expectsMediaDataInRealTime = YES; </code></pre> <p>is essential otherwise it messes with its mind. Perhaps this is because the video was set up with this flag. Additionally, <code>CMBlockBufferCreateWithMemoryBlock</code> does NOT copy sample data, even if you pass the flag <code>kCMBlockBufferAlwaysCopyDataFlag</code> to it.</p> <p>So, a buffer can be created with this and then copied using <code>CMBlockBufferCreateContiguous</code> to ensure that it you get a block buffer with a copy of the audio data. Otherwise it will reference the memory you passed in originally and things will get messed up.</p>
12,211,927
2
0
null
2012-08-29 21:59:59.807 UTC
8
2020-11-03 05:19:32.21 UTC
2020-11-03 05:19:32.21 UTC
null
814,730
null
853,665
null
1
4
iphone|objective-c|ios|avfoundation|avassetwriter
7,208
<p>It looks ok, although I would use <code>CMBlockBufferCreateWithMemoryBlock</code> because it copies the samples. Is your code ok with not knowing when audioWriterInput has finished with them?</p> <p>Shouldn't <code>kAudioFormatFlagIsAlignedHigh</code> be <code>kAudioFormatFlagIsPacked</code>?</p>
23,272,181
There seems to be a contradiction in §12.3.2/1 in the C++11 Standard
<p>C++11 Standard §12.3.2/1 (emphasis mine):</p> <blockquote> <p>A <strong>member function</strong> of a class X having no parameters with a name of the form</p> <p><em>conversion-function-id</em>: </p> <blockquote> <p>operator <em>conversion-type-id</em></p> </blockquote> <p><em>conversion-type-id</em>: </p> <blockquote> <p><em>type-specifier-seq</em> conversion-declarator </p> </blockquote> <p><em>conversion-declarator</em>: </p> <blockquote> <p><em>ptr-operator conversion-declarator</em> </p> </blockquote> <p>specifies a conversion from X to the type specified by the <em>conversion-type-id</em>. Such functions are called conversion functions. No return type can be specified. <strong>If a conversion function is a member function</strong>, the type of the conversion function (8.3.5) is “function taking no parameter returning <em>conversion-type-id</em>”.</p> </blockquote> <p>Is a conversion function always a member function, or there are cases where this is not true?</p>
23,273,284
2
8
null
2014-04-24 14:41:47.243 UTC
2
2018-02-03 15:19:17.843 UTC
null
null
null
null
1,162,978
null
1
32
c++|c++11|language-lawyer
1,805
<p>The clause "If a conversion function is a member function," was added to the working draft in <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf" rel="nofollow noreferrer">N2798</a> as part of the Concepts wording per <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2773.pdf" rel="nofollow noreferrer">N2773 Proposed Wording for Concepts</a>. N2798 12.3.2/1 reads (I'll use <strong>bold</strong> to show additions, and <strike>strikeout</strike> to show removals):</p> <blockquote> <p><sup>1</sup> A member function of a class <code>X</code> <strong>having no parameters, or an associated function of a concept whose sole parameter is of type <code>X</code>,</strong> with a name of the form</p> <p><em>conversion-function-id:</em></p> <blockquote> <p><code>operator</code> <em>conversion-type-id</em></p> </blockquote> <p><em>conversion-type-id:</em></p> <blockquote> <p><em>type-specifier-seq <strong>attribute-specifier<sub>opt</sub></strong> conversion-declarator<sub>opt</sub></em></p> </blockquote> <p><em>conversion-declarator:</em></p> <blockquote> <p><em>ptr-operator conversion-declarator<sub>opt</sub></em></p> </blockquote> <p>specifies a conversion from <code>X</code> to the type specified by the <em>conversion-type-id</em>. Such <strike>member</strike> functions are called conversion functions. <strike>Classes, enumerations, and <em>typedef-names</em> shall not be declared in the <em>type-specifier-seq</em>. Neither parameter types nor</strike> <strong>No</strong> return type can be specified. <strong>If a conversion function is a member function, t</strong><strike>T</strike>he type of <strike>a</strike> <strong>the</strong> conversion function (8.3.5) is “function taking no parameter returning <em>conversion-type-id</em>”<strong>; if a conversion function is an associated function, the type of the conversion function is “function taking a parameter of type <code>X</code> returning <em>conversion-type-id</em>”</strong>. A conversion function is never used to convert ...</p> </blockquote> <p>The Concepts wording was removed in draft <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2960.pdf" rel="nofollow noreferrer">N2960</a>. The "If a conversion function is a member function," should have also been removed at that time since it is now vestigal. Pertinent portion of N2960 §12.3.2/1:</p> <blockquote> <p><sup>1</sup> A member function of a class <code>X</code> having no parameters, <strike>or an associated function of a concept whose sole parameter is of type X,</strike> with a name of the form</p> <p><em>conversion-function-id:</em></p> <blockquote> <p><code>operator</code> <em>conversion-type-id</em></p> </blockquote> <p><em>conversion-type-id:</em></p> <blockquote> <p><em>type-specifier-seq attribute-specifier<sub>opt</sub> conversion-declarator<sub>opt</sub></em></p> </blockquote> <p><em>conversion-declarator:</em></p> <blockquote> <p><em>ptr-operator conversion-declarator<sub>opt</sub></em></p> </blockquote> <p>specifies a conversion from <code>X</code> to the type specified by the <em>conversion-type-id</em>. Such functions are called conversion functions. No return type can be specified. If a conversion function is a member function, the type of the conversion function (8.3.5) is “function taking no parameter returning <em>conversion-type-id</em>”<strike>; if a conversion function is an associated function, the type of the conversion function is “function taking a parameter of type <code>X</code> returning <em>conversion-type-id</em>”</strike>. ...</p> </blockquote> <p><strong>2018-02-03 Update: This has been fixed in C++17</strong></p> <p>CWG corrected this wording as a drive-by while fixing <a href="http://wg21.link/cwg1990" rel="nofollow noreferrer">CWG issue 1990</a>. </p>
31,683,075
How to do a deep comparison between 2 objects with lodash?
<p>I have 2 nested objects which are different and I need to know if they have a difference in one of their nested properties.</p> <pre class="lang-js prettyprint-override"><code>var a = {}; var b = {}; a.prop1 = 2; a.prop2 = { prop3: 2 }; b.prop1 = 2; b.prop2 = { prop3: 3 }; </code></pre> <p>The object could be much more complex with more nested properties. But this one is a good example. I have the option to use recursive functions or something with lodash...</p>
31,683,111
24
7
null
2015-07-28 17:17:56.817 UTC
60
2022-07-26 19:14:02.327 UTC
2022-07-26 19:14:02.327 UTC
null
6,243,352
null
2,414,919
null
1
456
javascript|lodash|javascript-objects
528,225
<p>An easy and elegant solution is to use <a href="https://lodash.com/docs/4.17.4#isEqual" rel="noreferrer"><code>_.isEqual</code></a>, which performs a deep comparison:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var a = {}; var b = {}; a.prop1 = 2; a.prop2 = { prop3: 2 }; b.prop1 = 2; b.prop2 = { prop3: 3 }; console.log(_.isEqual(a, b)); // returns false if different</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>However, this solution doesn't show which property is different.</p>
5,346,839
Modelling indefinitely-recurring tasks in a schedule (calendar-like rails app)
<p>This has been quite a stumbling block. Warning: the following is not a question, rather explanation of what I came up with. My question is — do you have a better way to do this? Is there some common technique for this that I'm not familiar with? Seems like this is a trivial problem.</p> <p>So you have Task model. You can create tasks, complete them, destroy them. Then you have recurring tasks. It's just like regular task, but it has a recurrence rule attached to it. However, tasks can recur indefinitely — you can go a year ahead in the schedule, and you should see the task show up.</p> <p>So when a user creates a recurring task, you don't want to build thousands of tasks for hundred years into the future, and save them to database, right? So I started thinking — how do you create them?</p> <p>One way would be to create them as you view your schedule. So, when the user is moving a month ahead, any recurring tasks will be created. Of course that means that you can't simply work with database records of tasks any longer. Every SELECT operation on tasks you ever do has to be in the context of a particular date range, in order to trigger recurring tasks in that date range to persist. This is a maintenance and performance burden, but doable.</p> <p>Alright, but how about the original task? Every recurrent task gets associated with the recurrence rule that created it, and every recurrence rule needs to know the original task that started the recurrence. The latter is important, because you need to clone the original task into new dates as the user browses their schedule. I guess doable too.</p> <p>But what happens if the original task is updated? It means that now as we browse the schedule, we will be creating recurring tasks cloned off of the modified task. That's undesirable. All the implicitly persisted recurring tasks should show up the way the original task looked like when recurrence was added. So we need to store a copy of the original task separately, and clone from that, in order for recurrence to work.</p> <p>However, when the user navigates the tasks in the schedule, how do we know if at a particular point a new recurrence task needs to be created? We ask recurrence rule: "hey, should I persist a task for this day?" and it says yes or no. If there is already a task for this recurrence for this day, we don't create one. All nice, except a user shall also be able to simply delete one of the recurring tasks that has been automatically persisted. In that case following our logic, the system will re-create the task that has been deleted. Not good. So it means we need to keep storing the task, but mark it as deleted task for this recurrence. Meh.</p> <p>As I said in the beginning, I want to know if somebody else tackled this problem and can provide architectural advice here. Does it have to be this messy? Is there anything more elegant I'm missing?</p> <p><strong>Update</strong>: Since this question is hard to answer perfectly, I will approve the most helpful insight into design/architecture, which has the best helpfulness/trade-offs ratio for this type of problem. It does not have to encompass all the details.</p>
13,205,953
3
0
null
2011-03-18 00:18:19.987 UTC
9
2012-11-03 04:30:33.497 UTC
2011-03-18 01:46:02.92 UTC
null
155,351
null
155,351
null
1
13
ruby-on-rails|ruby|database-design|architecture
3,871
<p>I know this is an old question but I'm just starting to look into this for my own application and I found this paper by Martin Fowler illuminating: <a href="http://martinfowler.com/apsupp/recurring.pdf">Recurring Events for Calendars</a></p> <p>The main takeaway for me was using what he calls "temporal expressions" to figure out if a booking falls on a certain date range instead of trying to insert an infinite number of events (or in your case tasks) into the database.</p> <p>Practically, for your use case, this might mean that you store the Task with a "temporal expression" property called <code>schedule</code>. The <a href="https://github.com/seejohnrun/ice_cube">ice_cube recurrence gem</a> has the ability to serialize itself into an active record property <a href="https://github.com/seejohnrun/ice_cube/wiki/IceCube-and-Rails">like so</a>:</p> <pre><code>class Task &lt; ActiveRecord::Base include IceCube serialize :schedule, Hash def schedule=(new_schedule) write_attribute(:schedule, new_schedule.to_hash) end def schedule Schedule.from_hash(read_attribute(:schedule)) end end </code></pre> <p>Ice cube seems really flexible and even allows you to specify exceptions to the recurrence rules. (Say you want to delete just one occurrence of the task, but not all of them.)</p> <p>The problem is that you can't really query the database for a task that falls in a specific range of dates, because you've only stored the rule for making tasks, not the tasks themselves. For my case, I'm thinking about adding a property like "next_recurrence_date" which will be used to do some basic sorting/filtering. You could even use that to throw a task on a queue to have something done on the next recurring date. (Like check if that date has passed and then regenerate it. You could even store an "archived" version of the task once its next recurring date passes.)</p> <p>This fixes your issue with "what if the task is updated" since tasks aren't ever persisted until they're in the past.</p> <p>Anyway, I hope that is helpful to someone trying to think this through for their own app.</p>
5,296,183
Twitter: Hash tag search query
<p>I am trying to search twitter tweets by a given hashtag. I am trying to get the correct http query, but I have no idea which one. I've tried a few but i can't find the correct one.</p> <p>I should use the <a href="http://api.twitter.com/1/" rel="noreferrer">http://api.twitter.com/1/</a>... link.</p> <p>I already have a search http query by a given name which works correctly</p> <pre><code>http://api.twitter.com/1/statuses/user_timeline.json?screen_name=prayforjapan </code></pre> <p>Now I would like to search by a given hashtag (for example #prayforjapan)</p> <p>I tried using a few, but can't find the correct one as I said before. Here's one I tried:</p> <pre><code>http://api.twitter.com/1/statuses/public_timeline.json?include_entities=true&amp;hashtag=prayforjapan" </code></pre> <p>Does anyone know which one I should use?</p> <p>Thanks!</p>
5,296,199
3
1
null
2011-03-14 08:15:19.793 UTC
11
2018-03-10 18:43:51.75 UTC
null
null
null
null
651,353
null
1
17
search|twitter|hash|hashtag
38,482
<p>You can simply fetch <code>http://search.twitter.com/search.json?q=%23test</code> to get a list of tweets containing <code>#test</code> in JSON, where <code>%23test</code> is <code>#test</code> URL encoded.</p>
5,051,529
HMAC vs simple MD5 Hash
<p>Can anyone point out what the advantage of using <code>HMАC</code> is?</p> <p>For example, if I have a text <code>T</code> and a key <code>K</code>, I can use either <code>HMAC-MD5</code> algorithm or <code>Md5(T + K)</code> to get a signature. </p>
5,051,589
3
2
null
2011-02-19 15:05:49.293 UTC
10
2015-09-05 16:55:25.587 UTC
2015-09-05 16:55:25.587 UTC
null
4,132,844
null
496,949
null
1
48
security|md5|hmac
30,157
<p>The <a href="http://en.wikipedia.org/wiki/HMAC#Design_principles" rel="noreferrer">Wikipedia article on HMAC</a> gives a good explanation of this.</p> <p>In the <a href="http://en.wikipedia.org/wiki/HMAC#Security" rel="noreferrer">Security</a> section of the same article it goes on to say:</p> <blockquote> <p>HMACs are substantially less affected by collisions than their underlying hashing algorithms alone.</p> </blockquote> <p>So adding an HMAC to an MD5 hash would make it substantially more difficult to break via a rainbow table.</p>
5,087,681
YouTube Vimeo Video ID from Embed Code or From URL with PHP Regular Expression RegEx
<p>I want to get Video ID for YouTube or Vimeo via its Embed code or from URL, Any solution to do this with PHP ?</p>
5,254,735
4
0
null
2011-02-23 06:21:48.627 UTC
10
2021-01-22 13:55:14.917 UTC
null
null
null
null
401,048
null
1
9
php|regex|youtube|vimeo
16,550
<p>You could use <a href="http://php.net/manual/en/function.preg-match.php" rel="noreferrer">preg_match</a> to get the IDs. I will cover the expressions themselves later in this answer, but here is the basic idea of how to use preg_match:</p> <pre><code>preg_match('expression(video_id)', "http://www.your.url.here", $matches); $video_id = $matches[1]; </code></pre> <hr> <p>Here is a breakdown of the expressions for each type of possible input you asked about. I included a link for each showing some test cases and the results.</p> <ol> <li><p>For <strong>YouTube URLs</strong> such as <code>http://www.youtube.com/watch?v=89OpN_277yY</code>, you could use <a href="http://rubular.com/r/UkdKjNY1fp" rel="noreferrer">this</a> expression:</p> <pre><code>v=(.{11}) </code></pre></li> <li><p><strong>YouTube embed codes</strong> can either look like this (some extraneous stuff clipped):</p> <pre><code>&lt;object width="640" height="390"&gt; &lt;param name="movie" value="http://www.youtube.com/v/89OpN_277yY?fs=... ... &lt;/object&gt; </code></pre> <p>Or like this:</p> <pre><code>&lt;iframe ... src="http://www.youtube.com/embed/89OpN_277yY" ... &lt;/iframe&gt; </code></pre> <p>So an expression to get the ID from either style would be <a href="http://rubular.com/r/oDA5CL9HIS" rel="noreferrer">this</a>:</p> <pre><code>\/v\/(.{11})|\/embed\/(.{11}) </code></pre></li> <li><p><strong>Vimeo URLs</strong> look like <code>http://vimeo.com/&lt;integer&gt;</code>, as far as I can tell. The lowest I found was simply <code>http://vimeo.com/2</code>, and I don't know if there's an upper limit, but I'll assume for now that it's limited to 10 digits. Hopefully someone can correct me if they are aware of the details. <a href="http://rubular.com/r/zlNyWzuNmP" rel="noreferrer">This</a> expression could be used:</p> <pre><code>vimeo\.com\/([0-9]{1,10}) </code></pre></li> <li><p><strong>Vimeo embed</strong> code takes this form:</p> <pre><code>&lt;iframe src="http://player.vimeo.com/video/&lt;integer&gt;" width="400" ... </code></pre> <p>So you could use <a href="http://rubular.com/r/csRdUcWfiQ" rel="noreferrer">this</a> expression:</p> <pre><code>player\.vimeo\.com\/video\/([0-9]{1,10}) </code></pre> <p>Alternately, if the length of the numbers may eventually exceed 10, you could use:</p> <pre><code>player\.vimeo\.com\/video/([0-9]*)" </code></pre> <p>Bear in mind that the <code>"</code> will need to be escaped with a <code>\</code> if you are enclosing the expression in double quotes.</p></li> </ol> <hr> <p><strong>In summary</strong>, I'm not sure how you wanted to implement this, but you could either combine all expressions with <code>|</code>, or you could match each one separately. Add a comment to this answer if you want me to provide further details on how to combine the expressions.</p>
43,316,307
Can't choose .NET 4.7
<p>I am trying to start a new project using .NET 4.7. I have Creators Update installed as well as the latest version of Visual Studio 2017. When I start a project and device to choose a .NET version, the latest .NET framework version I have is 4.6.2. When I go to download a new .NET framework, it only lists 4.6.2 as the latest via MS that you can download. It says that .NET 4.7 is included in VS 2017. What am I missing? </p>
43,316,357
5
6
null
2017-04-10 06:31:54.707 UTC
10
2021-07-30 16:32:47.47 UTC
2018-03-06 00:13:21.15 UTC
null
397,817
null
3,930,378
null
1
102
visual-studio-2017|.net-4.7
55,913
<p>You need to go to Visual Studio Installer and install an optional component ".NET Framework 4.7 Development Tools".</p>
9,201,166
Iterative DFS vs Recursive DFS and different elements order
<p>I have written a recursive DFS algorithm to traverse a graph:</p> <pre><code>void Graph&lt;E, N&gt;::DFS(Node n) { std::cout &lt;&lt; ReadNode(n) &lt;&lt; " "; MarkVisited(n); NodeList adjnodes = Adjacent(n); NodeList::position pos = adjnodes.FirstPosition(); while(!adjnodes.End(pos)) { Node adj = adjnodes.ReadList(pos); if(!IsMarked(adj)) DFS(adj); pos = adjnodes.NextPosition(pos); } } </code></pre> <p>Then I have written an iterative DFS algorithm using a stack:</p> <pre><code>template &lt;typename E, typename N&gt; void Graph&lt;E, N&gt;::IterativeDFS(Node n) { Stack&lt;Node&gt; stack; stack.Push(n); while(!stack.IsEmpty()) { Node u = stack.Read(); stack.Pop(); if(!IsMarked(u)) { std::cout &lt;&lt; ReadNode(u) &lt;&lt; " "; MarkVisited(u); NodeList adjnodes = Adjacent(u); NodeList::position pos = adjnodes.FirstPosition(); while(!adjnodes.End(pos)) { stack.Push(adjnodes.ReadList(pos)); pos = adjnodes.NextPosition(pos); } } } </code></pre> <p>My problem is that in a graph in which, for example, I enter the three nodes 'a', 'b', 'c' with arcs ('a', 'b') and ('a', 'c') my output is:</p> <p>'a', 'b', 'c' with the recursive DFS version, and:</p> <p>'a', 'c', 'b' with the iterative DFS one.</p> <p>How could I get the same order? Am I doing something wrong?</p> <p>Thank you!</p>
9,201,268
4
3
null
2012-02-08 20:48:34.737 UTC
43
2020-09-07 00:16:57.66 UTC
2012-04-11 00:24:10.867 UTC
null
58,074
null
1,056,777
null
1
61
c++|algorithm|graph|depth-first-search|traversal
59,690
<p><strong>Both are valid</strong> DFS algorithms. A DFS does not specify which node you see first. It is not important because the order between edges is not defined [remember: edges are a set usually]. The difference is due to the way you handle each node's children.</p> <p>In the <strong>iterative approach: You first insert all the elements</strong> into the stack - and then handle the head of the stack [which is the last node inserted] - thus the <strong>first node you handle is the last child</strong>.</p> <p>In the <strong>recursive approach</strong>: You handle each node when you see it. Thus the <strong>first node you handle is the first child</strong>.</p> <p>To make the iterative DFS yield the same result as the recursive one - you need to <strong>add elements to the stack in reverse order</strong> [for each node, insert its last child first and its first child last]</p>
9,564,420
The source was not found, but some or all event logs could not be searched
<p>I am getting the following exception. I have given full control to Asp.net account on Eventlogs in Registry edit.</p> <blockquote> <p>[SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.]</p> <pre><code>System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate) +664 System.Diagnostics.EventLog.SourceExists(String source, String machineName, Boolean wantToCreate) +109 System.Diagnostics.EventLog.SourceExists(String source) +14 Microsoft.ApplicationBlocks.ExceptionManagement.DefaultPublisher.VerifyValidSource() +41 </code></pre> </blockquote> <p>I guess this is due to some configuration issue on server?</p>
9,567,355
11
3
null
2012-03-05 09:38:46.893 UTC
16
2022-05-14 16:17:19.993 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
197,878
null
1
133
c#|.net|windows-7|event-log|securityexception
177,069
<p><code>EventLog.SourceExists</code> enumerates through the subkeys of <code>HKLM\SYSTEM\CurrentControlSet\services\eventlog</code> to see if it contains a subkey with the specified name. If the user account under which the code is running does not have read access to a subkey that it attempts to access (in your case, the <code>Security</code> subkey) before finding the target source, you will see an exception like the one you have described.</p> <p>The usual approach for handling such issues is to <a href="https://stackoverflow.com/a/7848414/298281">register event log sources</a> at installation time (under an administrator account), then assume that they exist at runtime, allowing any resulting exception to be treated as unexpected if a target event log source does not actually exist at runtime.</p>
18,238,477
Cross-Platform C++ code and single header - multiple implementations
<p>I have heard that a way to write Cross Platform c++ code is to define classes as follows (for example, a Window class):</p> <pre><code>window.h window_win32.cpp window_linux.cpp window_osx.cpp </code></pre> <p>and then choose the implementation file accordingly. But what if i have members of that class that are relative to the os? Like a <code>HWND</code> member for the Win32 implementation. I can't put it in the <code>window.h</code> or when i'd try to compile it on, say, Linux, it'd generate a compiler error.</p> <p>Do i need to <code>#ifdef</code> it? I've already asked a similar question but this one is more focused on this particular problem.</p>
18,239,377
5
3
null
2013-08-14 17:33:56.673 UTC
13
2017-01-24 17:07:23.49 UTC
2013-08-14 17:42:34.133 UTC
null
2,613,971
null
1,639,642
null
1
22
c++|cross-platform|header-files
10,265
<p>There is more ways to solve this problem - each has it's pros and cons.</p> <p>1.) Use macros #ifdef, #endif</p> <pre><code>// Note: not sure if "WINDOWS" or "WIN32" or something else is defined on Windows #ifdef WINDOWS #include &lt;window.h&gt; #else // etc. #endif class MyClass { public: // Public interface... private: #ifdef WINDOWS HWND m_myHandle; #else // etc. #endif }; </code></pre> <p>Pros:</p> <ul> <li>Maximal speed of program.</li> </ul> <p>Cons:</p> <ul> <li>Worse readibility. With many platforms it can get really messy.</li> <li>Including platform specific includes might break something. windows.h defines many macros with normal names.</li> </ul> <p>2.) As was there already written, you might use polymorphism:</p> <pre><code>// IMyClass.h for user of your class: class IMyClass { public: virtual ~IMyClass() {} virtual void doSomething() = 0; }; // MyClassWindows.h is implementation for one platform #include &lt;windows.h&gt; #include "IMyClass.h" class MyClassWindows : public IMyClass { public: MyClassWindows(); virtual void doSomething(); private: HWND m_myHandle; }; // MyClassWindows.cpp implements methods for MyClassWindows </code></pre> <p>Pros:</p> <ul> <li>Much, much more cleaner code.</li> </ul> <p>Cons:</p> <ul> <li>User cannot create instances of your class directly (especially not on stack).</li> <li>You must provide special function for creation: for example declare IMyClass* createMyClass(); and define it in MyClassWindows.cpp and other platform specific files. In that case (well, in fact in this whole polymorphism case) you should also define function which destroys the instances - in order to keep idiom "whoever created it should also destroy".</li> <li>Little slowdown because of virtual methods (in these days practically completely insignificant except very, very special cases).</li> <li>Note: the allocation can be problem on platforms with limited memory because of problems with RAM fragmentation. In that case, it can be solved by using some kind of memory pool for your objects.</li> </ul> <p>3.) PIMPL idiom.</p> <pre><code>// MyClass.h class MyClass { public: MyClass(); void doSomething(); private: struct MyClassImplementation; MyClassImplementation *m_impl; } // MyClassWindows.h #include &lt;windows.h&gt; #include "MyClass.h" struct MyClassImplementation { HWND m_myHandle; void doSomething(); } </code></pre> <p>In this case, MyClassImplementation keeps all needed (at least platform specific) data and implements what is needed (again, platform specific). In MyClass.cpp you include the platform specific implementation (methods can be inline), in constructor (or later if you want to - just be careful) you allocate the implementation and in destructor you will destroy it.</p> <p>Pros:</p> <ul> <li>User can create instances of your class (including on stack) (no worrying about un/deleted poiners).</li> <li>You do not need to include platform specific headers in MyClass.h.</li> <li>You can simply add reference counter and implement data sharing and/or copy-on-write which can easily allow to use your class as return value even if it keeps big amount of data.</li> </ul> <p>Cons:</p> <ul> <li>You must allocate implementation object. Object pool can help.</li> <li>When calling a methods, two are called instead and one pointer dereferencing. Still, today shouldn't be any problem.</li> </ul> <p>4.) Define a neutral type, which is big enough to keep your data. For example long long int.</p> <pre><code>// MyClass.h class MyClass { public: MyClass(); void doSomething(); private: typedef unsigned long long int MyData; MyData m_data; }; </code></pre> <p>In implementation (e.g. MyClassWindows.cpp) you always need to cast (reinterpret casting) between MyClass::MyData and actual data stored.</p> <p>Pros:</p> <ul> <li>As fast as first way but you avoid macros.</li> <li>Avoiding allocation if not needed.</li> <li>Avoiding multiple method calls.</li> <li>Avoiding including platform specific headers in MyClass.h.</li> </ul> <p>Cons:</p> <ul> <li>You must be absolutely 110% sure that size of MyClass::MyData is always at least same as data stored.</li> <li>If different platform stores differently sized data, you are waisting with space (if you use a few items, it's ok, but with millions of them...) unless you use macros. In this case, it won't be so messy.</li> <li>It's low level work with data - unsafe, not OOP. But fast.</li> </ul> <hr> <p>So use the one which is best fitting to your problem... and your personality :3 because with today's power are all four more or less relatively equal in terms of speed and space.</p>
18,709,422
Where are the default packages in Sublime Text 3 on Ubuntu?
<p>I'm migrating from Sublime Text 2 to 3. In Sublime Text 2, I changed a lot of the default settings of the editor -- such as the tab bar height, sidebar color, etc. -- by modifying the <code>Default.sublime-theme</code> file in <code>sublime-text-2/Packages/Theme - Default</code>. I was also able to modify the colors of the default color schemes in a similar fashion. I've been trying to figure out how to do this for Sublime Text 3, but can't seem to find these files. <code>~/.config/sublime-text-3</code> only seems to contain overrides for user settings, not the default settings.</p> <p><a href="http://www.sublimetext.com/forum/viewtopic.php?f=2&amp;t=10933" rel="noreferrer">This link</a> on the Sublime Text forums seems to give the location for Windows and Mac, but not for Ubuntu. I've searched a bit to no avail. Does anyone have suggestions?</p> <p>Thank you!</p>
18,709,785
5
0
null
2013-09-10 01:24:39.123 UTC
6
2019-12-11 03:34:02.54 UTC
null
null
null
null
887,587
null
1
28
sublimetext3
58,937
<p>To amplify on @skuroda's answer - ST3 contains all of its data that, in ST2, was stored in <code>Packages/PackageName</code>, in <code>PackageName.sublime-package</code> files that are basically just zip files, or &quot;Resources&quot; as they're now known. Using <code>PackageResourceViewer</code>, you can easily edit the individual files contained within the resource, then save it back again. When saved, the proper directory structure under <code>Packages/PackageName</code> will be created, allowing you to edit the file directly next time. The way file precedence works in Sublime, any file that exists in <code>~/.config/sublime-text-3/Packages/PackageName/</code> will override any file of the same name stored in <code>PackageName.sublime-package</code>.</p> <p>However, since you don't want these files to be accidentally overwritten, I would suggest creating <code>~/config/sublime-text-3/Packages/User/Themes/</code> and <code>User/Color Schemes</code> directories and storing your customized files there instead. The <code>User/</code> directory is protected from overwrites during upgrades, etc., and unless you're planning on creating a customized theme or color scheme for redistribution through Package Control, it's best practice to keep your files in there.</p> <hr /> <h3><em><strong>EDIT</strong></em></h3> <p>I just realized you hadn't gotten an answer to your original question - where are the files stored? If you installed the <code>.deb</code> file from sublimetext.com, all the <code>.sublime-package</code> files are in <code>/opt/sublime_text/Packages</code>.</p>
59,674,903
Trying to access array offset on value of type bool in PHP 7.4
<p>I just upgraded my server's PHP version to PHP 7.4.1 and now getting this error:</p> <blockquote> <p>Notice: Trying to access array offset on value of type bool in</p> </blockquote> <pre><code>public static function read($id) { $Row = MySQL::query(&quot;SELECT `Data` FROM `cb_sessions` WHERE `SessionID` = '$id'&quot;, TRUE); # http://php.net/manual/en/function.session-start.php#120589 //check to see if $session_data is null before returning (CRITICAL) if(is_null($Row['Data'])) { $session_data = ''; } else { $session_data = $Row['Data']; } return $session_data; } </code></pre> <p>What is the fix for PHP 7.4 ?</p>
59,687,793
2
7
null
2020-01-10 02:48:12.503 UTC
5
2021-08-26 23:53:57.753 UTC
2021-01-22 15:06:45.41 UTC
null
1,839,439
null
126,833
null
1
41
php|php-7.4
214,094
<p>Easy with PHP <a href="https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce" rel="noreferrer"><code>??</code> null coalescing operator</a></p> <pre><code>return $Row['Data'] ?? 'default value'; </code></pre> <p>Or you can use as such</p> <pre><code>$Row['Data'] ??= 'default value'; return $Row['Data']; </code></pre>
15,387,808
MySQL Join two tables count and sum from second table
<p>I have tow tables:</p> <p>dealers with some fields and primary key id</p> <p>and inquiries with following fields id dealer_id costs</p> <p>There are several items in inquiries for every dealer and i have to count them and sum the costs. Now I have only the count with this statement:</p> <pre><code>SELECT a.*, Count(b.id) as counttotal FROM dealers a LEFT JOIN inquiries b on a.id=b.dealer_id GROUP BY a.id ORDER BY name ASC </code></pre> <p>but i have no idea how to sum the costs of table b for each dealer. Can anybody help? Thanks in advance</p>
15,387,854
6
2
null
2013-03-13 14:15:28.377 UTC
5
2016-05-03 04:40:33.517 UTC
2013-03-13 15:23:26.613 UTC
null
2,053,648
null
2,053,648
null
1
12
sql|join|count|sum
39,791
<p>You could use two sub-queries:</p> <pre><code>SELECT a.* , (SELECT Count(b.id) FROM inquiries I1 WHERE I1.dealer_id = a.id) as counttotal , (SELECT SUM(b.cost) FROM inquiries I2 WHERE I2.dealer_id = a.id) as turnover FROM dealers a ORDER BY name ASC </code></pre> <p>Or</p> <pre><code>SELECT a.* , COALESCE(T.counttotal, 0) as counttotal -- use coalesce or equiv. to turn NULLs to 0 , COALESCE(T.turnover, 0) as turnover -- use coalesce or equiv. to turn NULLs to 0 FROM dealers a LEFT OUTER JOIN (SELECT a.id, Count(b.id) as counttotal, SUM(b.cost) as turnover FROM dealers a1 INNER JOIN inquiries b ON a1.id = b.dealer_id GROUP BY a.id) T ON a.id = T.id ORDER BY a.name </code></pre>
15,437,218
What the difference between loadComplete and gridComplete events?
<p>This question originated after I looked on <a href="https://stackoverflow.com/a/4943722/1818608">this</a> answer of <a href="https://stackoverflow.com/users/315935/oleg">Oleg</a> and demo-grids in it.</p> <p><code>gridComplete</code>:</p> <blockquote> <p>This fires after all the data is loaded into the grid and all other processes are complete. Also the event fires independent from the datatype parameter and after sorting paging and etc.</p> </blockquote> <p><code>loadComplete</code>:</p> <blockquote> <p>This event is executed immediately after every server request. data Data from the response depending on datatype grid parameter</p> </blockquote> <p>From that docs I understood that <code>gridComplete</code> fires at the end of drawing grid, and <code>loadComplete</code> fires after jqGrid completes communication with backend.</p> <p>And so I wonder - why in demos, <code>loadComplete</code> used for change color of cells and not <code>gridComplete</code>?</p>
15,439,276
2
1
null
2013-03-15 16:15:27.507 UTC
10
2015-11-07 21:50:33.63 UTC
2017-05-23 12:10:34.62 UTC
null
-1
null
1,818,608
null
1
16
javascript|datagrid|jqgrid
30,400
<p>I think that this question is asked by many users of jqGrid. So it's interesting to know the answer.</p> <p>I personally prefer to use <code>loadComplete</code>. If you examine code from all my examples which I posted, you will find <code>gridComplete</code> only when the Original Poster posted it in the question and I would have modified a little code. I prefer to use <code>loadComplete</code> because of some advantages of <code>loadComplete</code> and disadvantages of <code>gridComplete</code>.</p> <p>Here are advantages of <code>loadComplete</code>:</p> <ul> <li>It's the last callback which will be called if <em>the whole grid body</em> will be reloaded. For example after loading the page on the grid from the server. It's important to understand, that if the user changes sorting of some column or sets filter or chooses another page of the grid; the grid body will be reloaded.</li> <li><code>loadComplete</code> has parameter <code>data</code> which represent full page of local data or full data loaded from the server.</li> </ul> <p>On the other side <code>gridComplete</code> will be called (in the current version of jqGrid 4.4.4) from internal <code>updatepager</code> (see <a href="https://github.com/tonytomov/jqGrid/blob/v4.4.4/js/grid.base.js#L1736" rel="noreferrer">here</a>), which <strong>will be called from <code>delRowData</code> (see <a href="https://github.com/tonytomov/jqGrid/blob/v4.4.4/js/grid.base.js#L2861" rel="noreferrer">here</a>), <code>addRowData</code> (see <a href="https://github.com/tonytomov/jqGrid/blob/v4.4.4/js/grid.base.js#L3057" rel="noreferrer">here</a>) and <code>clearGridData</code> (see <a href="https://github.com/tonytomov/jqGrid/blob/v4.4.4/js/grid.base.js#L3468" rel="noreferrer">here</a>) methods; in addition</strong> to <code>addXmlData</code> (see <a href="https://github.com/tonytomov/jqGrid/blob/v4.4.4/js/grid.base.js#L1289" rel="noreferrer">here</a>) and <code>addJSONData</code> (see <a href="https://github.com/tonytomov/jqGrid/blob/v4.4.4/js/grid.base.js#L1471" rel="noreferrer">here</a>). It's not what one mostly want.</p> <p>Another disadvantage of <code>gridComplete</code> one can see if one examines the code of <code>addXmlData</code> (see <a href="https://github.com/tonytomov/jqGrid/blob/v4.4.4/js/grid.base.js#L1289" rel="noreferrer">here</a>) and <code>addJSONData</code> (see <a href="https://github.com/tonytomov/jqGrid/blob/v4.4.4/js/grid.base.js#L1471" rel="noreferrer">here</a>) <em>from where</em> <code>updatepager</code> is called and so <code>gridComplete</code> will be called. If one uses <code>loadonce: true</code> and the internal parameters <code>data</code> and <code>_index</code> will be filled with full data returned from the server. One can see when using <code>loadonce: true</code>; the callback <strong><code>gridComplete</code> will be called after the first page of data are loaded from the sever</strong>. At this moment <code>data</code> and <code>_index</code> contains only the data for the page. On the other side <strong><code>loadComplete</code> will be called later after all data returned from the server are processed and saved locally</strong> in <code>data</code> and <code>_index</code>.</p> <p>If you load the data from the server and if you don't use <code>loadonce: true</code> option, <code>clearGridData</code>, <code>addRowData</code> and <code>delRowData</code> then you could use <code>gridComplete</code> instead of <code>loadComplete</code>.</p>
14,978,629
How to make past date unselectable in fullcalendar?
<p>Problem is, how to disable selectable on PAST DATES in fullcalendar's month/week view.</p> <p>I want to user not allowed to click/select the on past dates.</p> <p><img src="https://i.stack.imgur.com/5yaf3.jpg" alt="enter image description here"></p> <p><strong>Here is some googled code snippet I am trying to implement on event rendering:</strong> </p> <pre><code>selectable: true, selectHelper: false, select: function(start, end, allDay) { var appdate = jQuery.datepicker.formatDate('&lt;?php echo $DPFormat; ?&gt;', new Date(start)); jQuery('#appdate').val(appdate); jQuery('#AppFirstModal').show(); }, eventRender: function(event, element, view) { var view = 'month' ; if(event.start.getMonth() !== view.start.getMonth()) { return false; } }, </code></pre> <p>But its not working though.</p> <p>I tried bellow CSS too and this help me to hide past date text only, but selectable is still working on pastdate box.</p> <pre><code>.fc-other-month .fc-day-number { display:none; } </code></pre> <p>I am really stuck with this problem. Please someone help me out. Thanks...</p>
15,014,079
17
0
null
2013-02-20 11:23:30.84 UTC
10
2022-07-10 21:36:18.937 UTC
2013-02-21 07:15:10.243 UTC
null
1,063,545
null
1,063,545
null
1
29
jquery|date|fullcalendar
71,758
<p>I have done this in my fullcalendar and it's working perfectly.</p> <p>you can add this code in your select function.</p> <pre><code> select: function(start, end, allDay) { var check = $.fullCalendar.formatDate(start,'yyyy-MM-dd'); var today = $.fullCalendar.formatDate(new Date(),'yyyy-MM-dd'); if(check &lt; today) { // Previous Day. show message if you want otherwise do nothing. // So it will be unselectable } else { // Its a right date // Do something } }, </code></pre> <p>I hope it will help you.</p>
15,167,069
PowerShell: Create Local User Account
<p>I need to create a new local user account, and then add them to the local <strong>Administrators</strong> group. Can this be done in PowerShell? </p> <p>EDIT:</p> <pre><code># Create new local Admin user for script purposes $Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer" $LocalAdmin = $Computer.Create("User", "LocalAdmin") $LocalAdmin.SetPassword("Password01") $LocalAdmin.SetInfo() $LocalAdmin.FullName = "Local Admin by Powershell" $LocalAdmin.SetInfo() $LocalAdmin.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD $LocalAdmin.SetInfo() </code></pre> <p>I have this, but was wondering if there is anything more PowerShell-esque.</p>
16,650,148
6
4
null
2013-03-01 21:20:47.64 UTC
16
2022-05-12 10:35:39.29 UTC
2014-01-20 13:33:32.977 UTC
user189198
null
null
1,048,116
null
1
57
powershell|powershell-2.0
192,431
<p>Another alternative is the old school <a href="https://technet.microsoft.com/en-us/library/cc771865.aspx" rel="noreferrer">NET USER</a> commands:</p> <p><code>NET USER username "password" /ADD</code></p> <p>OK - you can't set all the options but it's a lot less convoluted for simple user creation &amp; easy to script up in Powershell.</p> <p><code>NET LOCALGROUP "group" "user" /add</code> to set group membership. </p>
38,334,652
Sum all the digits of a number Javascript
<p>I am newbie.</p> <p>I want to make small app which will calculate the sum of all the digits of a number.</p> <p>For example, if I have the number 2568, the app will calculate 2+5+6+8 which is equal with 21. Finally, it will calculate the sum of 21's digits and the final result will be 3 .</p> <p>Please help me</p>
38,336,308
7
4
null
2016-07-12 16:40:37.703 UTC
10
2021-08-26 07:19:41.887 UTC
null
null
null
null
5,889,056
null
1
22
javascript|numbers|sum|digits
113,780
<p>Basically you have two methods to get the sum of all parts of an integer number.</p> <ul> <li><p><strong>With numerical operations</strong></p> <p>Take the number and build the remainder of ten and add that. Then take the integer part of the division of the number by 10. Proceed.</p> </li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var value = 2568, sum = 0; while (value) { sum += value % 10; value = Math.floor(value / 10); } console.log(sum);</code></pre> </div> </div> </p> <ul> <li><p><strong>Use string operations</strong></p> <p>Convert the number to string, split the string and get an array with all digits and perform a reduce for every part and return the sum.</p> </li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var value = 2568, sum = value .toString() .split('') .map(Number) .reduce(function (a, b) { return a + b; }, 0); console.log(sum);</code></pre> </div> </div> </p> <hr /> <p>For returning the value, you need to addres the <code>value</code> property.</p> <pre><code>rezultat.value = sum; // ^^^^^^ </code></pre> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function sumDigits() { var value = document.getElementById("thenumber").value, sum = 0; while (value) { sum += value % 10; value = Math.floor(value / 10); } var rezultat = document.getElementById("result"); rezultat.value = sum; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="text" placeholder="number" id="thenumber"/&gt;&lt;br/&gt;&lt;br/&gt; &lt;button onclick="sumDigits()"&gt;Calculate&lt;/button&gt;&lt;br/&gt;&lt;br/&gt; &lt;input type="text" readonly="true" placeholder="the result" id="result"/&gt;</code></pre> </div> </div> </p>
23,481,262
Using boost property tree to read int array
<p>I have some JSON with a handful of integer array variables, like so:</p> <pre><code>{"a": [8, 6, 2], "b": [2, 2, 1]} </code></pre> <p>I would like to use boost property_tree, for instance:</p> <pre><code>std::stringstream ss; boost::property_tree::ptree pt; ss &lt;&lt; "{\"a\": [8, 6, 2], \"b\": [2, 2, 1]}"; boost::property_tree::read_json(ss, pt); std::vector&lt;int&gt; a = pt.get&lt;std::vector&lt;int&gt; &gt;("a"); </code></pre> <p>This doesn't work, nor does any variation on an int pointer that I've tried. How may I read an array from a property tree?</p>
23,482,976
2
4
null
2014-05-05 20:29:21.457 UTC
7
2015-02-28 07:21:24.017 UTC
2014-05-05 20:44:29.26 UTC
null
1,451,714
null
2,859,006
null
1
32
c++|json|boost|boost-propertytree
32,123
<p>JSON support, is spotty with boost property tree.</p> <blockquote> <p>The property tree dataset is not typed, and does not support arrays as such. Thus, the following JSON / property tree mapping is used: </p> <ul> <li>JSON objects are mapped to nodes. Each property is a child node. </li> <li>JSON arrays are mapped to nodes. Each element is a child node with an empty name. If a node has both named and unnamed child nodes, it cannot be mapped to a JSON representation. </li> <li>JSON values are mapped to nodes containing the value. However, all type information is lost; numbers, as well as the literals "null", "true" and "false" are simply mapped to their string form. </li> <li>Property tree nodes containing both child nodes and data cannot be mapped.</li> </ul> </blockquote> <p>(from the <a href="http://www.boost.org/doc/libs/1_55_0/doc/html/boost_propertytree/parsers.html#boost_propertytree.parsers.json_parser">documentation</a>)</p> <p>You can iterate the array with a helper function.</p> <pre><code>#include &lt;boost/property_tree/ptree.hpp&gt; #include &lt;boost/property_tree/json_parser.hpp&gt; using boost::property_tree::ptree; template &lt;typename T&gt; std::vector&lt;T&gt; as_vector(ptree const&amp; pt, ptree::key_type const&amp; key) { std::vector&lt;T&gt; r; for (auto&amp; item : pt.get_child(key)) r.push_back(item.second.get_value&lt;T&gt;()); return r; } int main() { std::stringstream ss("{\"a\": [8, 6, 2], \"b\": [2, 2, 1]}"); ptree pt; read_json(ss, pt); for (auto i : as_vector&lt;int&gt;(pt, "a")) std::cout &lt;&lt; i &lt;&lt; ' '; std::cout &lt;&lt; '\n'; for (auto i : as_vector&lt;int&gt;(pt, "b")) std::cout &lt;&lt; i &lt;&lt; ' '; } </code></pre> <p>See it <strong><a href="http://coliru.stacked-crooked.com/a/566631a144f8c5ff">Live On Coliru</a></strong>. Output:</p> <pre><code>8 6 2 2 2 1 </code></pre>
4,947,561
Can I "combine" 2 regex with a logic or?
<p>I need to validate Textbox input as credit card number. I already have regex for different credit cards:</p> <ul> <li>Visa: <code>^4[0-9]{12}(?:[0-9]{3})?$</code></li> <li>Mastercard: <code>^([51|52|53|54|55]{2})([0-9]{14})$</code></li> <li>American Express: <code>^3[47][0-9]{13}$</code></li> </ul> <p>and many others. </p> <p>The problem is, I want to validate using different regex based on different users. For example: For user1, Visa and Mastercard are available, while for user2, Visa and American Express are available. So I would like to generate a final regex string dynamically, combining one or more regex string above, like:</p> <pre><code>user1Regex = Visa regex + "||" + Mastercard regex user2Regex = Visa regex + "||" + American Express regex </code></pre> <p>Is there a way to do that? Thanks,</p>
4,947,608
4
0
null
2011-02-09 16:21:26.2 UTC
8
2018-06-01 09:22:18.447 UTC
2011-02-09 16:22:46.577 UTC
null
142,162
null
277,368
null
1
17
regex
46,685
<p>You did not state your language but for whatever reason I suspect it's JavaScript. Just do:</p> <pre><code>var user1Regex = new RegExp('(' + Visaregex + ")|(" + Mastercardregex + ')'); // or if es6: let user1Regex = new RegExp(`(${Visaregex})|(${Mastercardregex})`); </code></pre> <p>You can also use <code>(?:)</code> for speedier execution (non-capturing grouping) but I have omitted that for readability.</p>
5,473,001
ItemsControl with multiple DataTemplates for a viewmodel
<p>is it possible to bind an itemscontrol with canvas as template to multiple DataTemplates?</p> <p>I have 2 collections and depending on the type I would like to display a different control on my canvas.</p> <p>I am not sure but I could think about a Viewmodel which has 2 ObservableCollections. For example if I would have "Shapes" and "connections" and I would like to display them both on the canvas? In case of a diagraming scenario...</p> <p>I would like to do this in the mvvm manner and I am not sure if the multiple DataTemplate approach is correct but this came to my mind. But I am still having problems to get the binding straight in my head. If I set the DataContext to the ViewModel for me it seems not possible to bind 2 collections to the items control... =( I am also open for other ideas, too....</p> <p>Is this possible? And if so, how would the binding look like an</p>
5,473,443
4
3
null
2011-03-29 13:08:33.133 UTC
11
2017-06-07 09:00:33.717 UTC
2015-03-04 21:42:16.877 UTC
null
148,544
null
84,750
null
1
28
wpf|silverlight|data-binding|mvvm|viewmodel
34,820
<p>You can create multiple <code>ObservableCollections</code> and then bind your <code>ItemsSource</code> to a <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.compositecollection.aspx" rel="noreferrer"><code>CompositeCollection</code></a> which joins those collections.</p> <p>Then in your XAML you can create different <code>DataTemplates</code> for the respective types using the <code>DataType</code> property which like styles gets automatically applied if it is placed in the resources. (You can also create the composite in XAML which is shown on MSDN, if the <code>CollectionContainers</code> should be bound that is <a href="https://stackoverflow.com/a/6446923/546730">a bit more difficult</a> though)</p> <p>Example code:</p> <pre class="lang-cs prettyprint-override"><code>ObservableCollection&lt;Employee&gt; data1 = new ObservableCollection&lt;Employee&gt;(new Employee[] { new Employee("Hans", "Programmer"), new Employee("Elister", "Programmer"), new Employee("Steve", "GUI Designer"), new Employee("Stefan", "GUI Designer"), new Employee("Joe", "Coffee Getter"), new Employee("Julien", "Programmer"), }); ObservableCollection&lt;Machine&gt; data2 = new ObservableCollection&lt;Machine&gt;(new Machine[] { new Machine("E12", "GreedCorp"), new Machine("E11", "GreedCorp"), new Machine("F1-MII", "CommerceComp"), new Machine("F2-E5", "CommerceComp") }); CompositeCollection coll = new CompositeCollection(); coll.Add(new CollectionContainer() { Collection = data1 }); coll.Add(new CollectionContainer() { Collection = data2 }); Data = coll; </code></pre> <pre><code>&lt;ItemsControl ItemsSource="{Binding Data}"&gt; &lt;ItemsControl.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;VirtualizingStackPanel/&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ItemsControl.ItemsPanel&gt; &lt;ItemsControl.Resources&gt; &lt;DataTemplate DataType="{x:Type local:Employee}"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBlock Text="{Binding Name}"/&gt; &lt;TextBlock Text=" ("/&gt; &lt;TextBlock Text="{Binding Occupation}"/&gt; &lt;TextBlock Text=")"/&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;DataTemplate DataType="{x:Type local:Machine}"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBlock Text="{Binding Model}"/&gt; &lt;TextBlock Text=" - "/&gt; &lt;TextBlock Text="{Binding Manufacturer}"/&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.Resources&gt; &lt;/ItemsControl&gt; </code></pre> <p>Here i use a different panel but it should be the same for a canvas.</p>
5,188,737
Creating a link to logout for JSP
<p>when a user logins to my application, he submits a form to be processed through the Servlet. The servlet creates a session for the user. How would I create a link so the user can logout? I cannot seem to directly link to a Servlet. How would I delete the session and link back to the homepage?</p> <p>Here is a way that I could do it, but it doesn't seem "right". I could link back to the index.jsp?logout=true. My index.jsp will see if logout is true and delete the sessions.</p> <p>Is there another way to do it?</p>
5,188,772
5
0
null
2011-03-04 01:38:11.637 UTC
null
2017-04-01 17:37:07.913 UTC
2013-10-14 08:46:57.137 UTC
null
1,021,725
null
441,659
null
1
5
java|jsp|authentication|servlets|forms-authentication
39,117
<p>Write a servlet mapped to <code>/logout</code> which then executes something like this in <code>doGet</code>:</p> <pre><code>HttpSession session = request.getSession(false); if(session != null) session.invalidate(); request.getRequestDispatcher("/index.jsp").forward(request,response); </code></pre> <p>It wont matter if the user has a session or not, they will ultimately be redirected to <code>index.jsp</code>.</p>
4,868,815
Google AJAX API - How do I get more than 4 Results?
<p>Im using the google APIs ajax below to get images for particular search terms. This is being done in a <strong>WinForms</strong> app.</p> <p>The below link seems to work, but it only returns 4 results (via JSON)</p> <p>Anyone know how to coax more out of it?</p> <p><a href="http://ajax.googleapis.com/ajax/services/search/images?v=1.0&amp;q=Apple+Cake">http://ajax.googleapis.com/ajax/services/search/images?v=1.0&amp;q=Apple+Cake</a></p> <p>Obviously there has to be another parameter to request more or page through the results, but I can't seem to figure it out? Anyone know?</p>
4,868,897
7
2
null
2011-02-01 22:42:35.373 UTC
12
2015-11-23 11:56:50.44 UTC
2011-02-01 22:44:48.1 UTC
null
21,234
null
452,047
null
1
23
image|json|google-api
36,987
<p>I believe the only way to do that is to make multiple calls to the webservice specifying the 'start' parameter.</p> <pre><code>http://ajax.googleapis.com/ajax/services/search/images?v=1.0&amp;q=Apple+Cake&amp;start=4 </code></pre> <p>The <code>start</code> parameter is the 0-based index into the search results. So in this example, it would return images 4..7.</p> <p>You can also add the parameter <code>rsz=[1-8]</code>. The default value is 4. That's why you're getting 4 results per request. Here's a link:<br> <a href="http://code.google.com/apis/imagesearch/v1/jsondevguide.html#basic_query" rel="nofollow noreferrer">http://code.google.com/apis/imagesearch/v1/jsondevguide.html#basic_query</a></p>
5,424,968
Dictionary.FirstOrDefault() how to determine if a result was found
<p>I have (or wanted to have) some code like this:</p> <pre><code>IDictionary&lt;string,int&gt; dict = new Dictionary&lt;string,int&gt;(); // ... Add some stuff to the dictionary. // Try to find an entry by value (if multiple, don't care which one). var entry = dict.FirstOrDefault(e =&gt; e.Value == 1); if ( entry != null ) { // ^^^ above gives a compile error: // Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair&lt;string,int&gt;' and '&lt;null&gt;' } </code></pre> <p>I also tried changing the offending line like this:</p> <pre><code>if ( entry != default(KeyValuePair&lt;string,int&gt;) ) </code></pre> <p>But that also gives a compile error:</p> <pre><code>Operator '!=' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair&lt;string,int&gt;' and 'System.Collections.Generic.KeyValuePair&lt;string,int&gt;' </code></pre> <p>What gives here? </p>
5,425,052
8
0
null
2011-03-24 20:16:05.43 UTC
6
2021-11-30 17:53:40.883 UTC
2015-07-06 14:36:56.013 UTC
null
15,541
null
65,070
null
1
72
c#|.net|linq
70,708
<p>Jon's answer will work with <code>Dictionary&lt;string, int&gt;</code>, as that can't have a null key value in the dictionary. It wouldn't work with <code>Dictionary&lt;int, string&gt;</code>, however, as that doesn't <em>represent</em> a null key value... the "failure" mode would end up with a key of 0.</p> <p>Two options:</p> <p>Write a <code>TryFirstOrDefault</code> method, like this:</p> <pre><code>public static bool TryFirstOrDefault&lt;T&gt;(this IEnumerable&lt;T&gt; source, out T value) { value = default(T); using (var iterator = source.GetEnumerator()) { if (iterator.MoveNext()) { value = iterator.Current; return true; } return false; } } </code></pre> <p>Alternatively, project to a nullable type:</p> <pre><code>var entry = dict.Where(e =&gt; e.Value == 1) .Select(e =&gt; (KeyValuePair&lt;string,int&gt;?) e) .FirstOrDefault(); if (entry != null) { // Use entry.Value, which is the KeyValuePair&lt;string,int&gt; } </code></pre>
5,460,129
How to create a drop shadow only on one side of an element?
<p>Is there a way to drop the shadow only on the bottom?. I have a menu with 2 images next to each other. I don't want a right shadow because it overlaps the right image. I don't like to use images for this so is there a way to drop it only on the bottom like: </p> <p><code>box-shadow-bottom: 10px #FFF;</code> or similar?</p> <pre><code>-moz-box-shadow: 0px 3px 3px #000; -webkit-box-shadow: 0px 3px 3px #000; box-shadow-bottom: 5px #000; /* For IE 8 */ -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=180, Color='#000000')"; /* For IE 5.5 - 7 */ filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=180, Color='#000000'); </code></pre>
5,460,239
17
4
null
2011-03-28 14:03:28.797 UTC
60
2022-09-23 14:07:33.953 UTC
2019-12-20 16:03:40.873 UTC
null
7,910,454
null
671,623
null
1
268
css
435,615
<h2>UPDATE 4</h2> <p>Same as update 3 but with modern css (=fewer rules) so that no special positioning on the pseudo element is required.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#box { background-color: #3D6AA2; width: 160px; height: 90px; position: absolute; top: calc(10% - 10px); left: calc(50% - 80px); } .box-shadow:after { content:""; position:absolute; width:100%; bottom:1px; z-index:-1; transform:scale(.9); box-shadow: 0px 0px 8px 2px #000000; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="box" class="box-shadow"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <h2>UPDATE 3</h2> <p>All my previous answers have been using extra markup to get create this effect, which is not necessarily needed. I think this is a <strong>much</strong> cleaner solution... the only trick is playing around with the values to get the right positioning of the shadow as well as the right strength/opacity of the shadow. Here's a new fiddle, using <a href="https://developer.mozilla.org/en-US/docs/CSS/Pseudo-elements" rel="noreferrer">pseudo-elements</a>:</p> <p><a href="http://jsfiddle.net/UnsungHero97/ARRRZ/2/" rel="noreferrer">http://jsfiddle.net/UnsungHero97/ARRRZ/2/</a></p> <p><strong>HTML</strong></p> <pre><code>&lt;div id=&quot;box&quot; class=&quot;box-shadow&quot;&gt;&lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>#box { background-color: #3D6AA2; width: 160px; height: 90px; margin-top: -45px; margin-left: -80px; position: absolute; top: 50%; left: 50%; } .box-shadow:after { content: &quot;&quot;; width: 150px; height: 1px; margin-top: 88px; margin-left: -75px; display: block; position: absolute; left: 50%; z-index: -1; -webkit-box-shadow: 0px 0px 8px 2px #000000; -moz-box-shadow: 0px 0px 8px 2px #000000; box-shadow: 0px 0px 8px 2px #000000; } </code></pre> <h2>UPDATE 2</h2> <p>Apparently, you can do this with just an extra parameter to the box-shadow CSS as everyone else just pointed out. Here's the demo:</p> <p><a href="http://jsfiddle.net/K88H9/821/" rel="noreferrer">http://jsfiddle.net/K88H9/821/</a></p> <p><strong>CSS</strong></p> <pre><code>-webkit-box-shadow: 0 4px 4px -2px #000000; -moz-box-shadow: 0 4px 4px -2px #000000;     box-shadow: 0 4px 4px -2px #000000; </code></pre> <p>This would be a better solution. The extra parameter that is added is described as:</p> <blockquote> <p>The fourth length is a spread distance. Positive values cause the shadow shape to expand in all directions by the specified radius. Negative values cause the shadow shape to contract.</p> </blockquote> <h2>UPDATE</h2> <p>Check out the demo at jsFiddle: <a href="http://jsfiddle.net/K88H9/4/" rel="noreferrer">http://jsfiddle.net/K88H9/4/</a></p> <p>What I did was to create a &quot;shadow element&quot; that would hide behind the actual element that you would want to have a shadow. I made the width of the &quot;shadow element&quot; to be exactly less wide than the actual element by 2 times the shadow you specify; then I aligned it properly.</p> <p><strong>HTML</strong></p> <pre><code>&lt;div id=&quot;wrapper&quot;&gt; &lt;div id=&quot;element&quot;&gt;&lt;/div&gt; &lt;div id=&quot;shadow&quot;&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>#wrapper { width: 84px; position: relative; } #element { background-color: #3D668F; height: 54px; width: 100%; position: relative; z-index: 10; } #shadow { background-color: #3D668F; height: 8px; width: 80px; margin-left: -40px; position: absolute; bottom: 0px; left: 50%; z-index: 5; -webkit-box-shadow: 0px 2px 4px #000000; -moz-box-shadow: 0px 2px 4px #000000; box-shadow: 0px 2px 4px #000000; } </code></pre> <h2>Original Answer</h2> <p>Yes, you can do this with the same syntax you have provided. The first value controls the horizontal positioning and the second value controls the vertical positioning. So just set the first value to <code>0px</code> and the second to whatever offset you'd like as follows:</p> <pre><code>-webkit-box-shadow: 0px 5px #000000; -moz-box-shadow: 0px 5px #000000; box-shadow: 0px 5px #000000; </code></pre> <p>For more info on box shadows, check out these:</p> <ul> <li><a href="http://www.css3.info/preview/box-shadow/" rel="noreferrer">http://www.css3.info/preview/box-shadow/</a></li> <li><a href="https://developer.mozilla.org/en/css/-moz-box-shadow#Browser_compatibility" rel="noreferrer">https://developer.mozilla.org/en/css/-moz-box-shadow#Browser_compatibility</a></li> <li><a href="http://www.w3.org/TR/css3-background/#the-box-shadow" rel="noreferrer">http://www.w3.org/TR/css3-background/#the-box-shadow</a></li> </ul> <p>I hope this helps.</p>
5,123,675
Find out if ListView is scrolled to the bottom?
<p>Can I find out if my ListView is scrolled to the bottom? By that I mean that the last item is fully visible.</p>
5,123,903
24
0
null
2011-02-25 23:05:07.453 UTC
39
2020-04-14 14:51:17.443 UTC
null
null
null
null
243,225
null
1
106
android|listview
84,134
<p><strong>Edited</strong>:</p> <p>Since I have been investigating in this particular subject in one of my applications, I can write an extended answer for future readers of this question.</p> <p>Implement an <code>OnScrollListener</code>, set your <code>ListView</code>'s <code>onScrollListener</code> and then you should be able to handle things correctly. </p> <p>For example:</p> <pre><code>private int preLast; // Initialization stuff. yourListView.setOnScrollListener(this); // ... ... ... @Override public void onScroll(AbsListView lw, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) { switch(lw.getId()) { case R.id.your_list_id: // Make your calculation stuff here. You have all your // needed info from the parameters of this function. // Sample calculation to determine if the last // item is fully visible. final int lastItem = firstVisibleItem + visibleItemCount; if(lastItem == totalItemCount) { if(preLast!=lastItem) { //to avoid multiple calls for last item Log.d("Last", "Last"); preLast = lastItem; } } } } </code></pre>
29,465,943
Get enum values as List of String in Java 8
<p>Is there any Java 8 method or easy way, which returns Enum values as a List of String, like:</p> <pre><code>List&lt;String&gt; sEnum = getEnumValuesAsString(); </code></pre>
29,465,971
3
5
null
2015-04-06 05:43:33.073 UTC
18
2022-09-09 00:26:03.96 UTC
2015-04-06 05:54:59.11 UTC
null
2,891,664
null
2,534,236
null
1
95
java|enums|java-8
178,069
<p>You can do (pre-Java 8):</p> <pre><code>List&lt;Enum&gt; enumValues = Arrays.asList(Enum.values()); </code></pre> <p>or </p> <pre><code>List&lt;Enum&gt; enumValues = new ArrayList&lt;Enum&gt;(EnumSet.allOf(Enum.class)); </code></pre> <p>Using Java 8 features, you can map each constant to its name:</p> <pre><code>List&lt;String&gt; enumNames = Stream.of(Enum.values()) .map(Enum::name) .collect(Collectors.toList()); </code></pre>
12,395,639
Mac OS Mountain Lion - Apache running but localhost not working
<p>I loaded Apache Web server on Mac OS Mountain Lion with the command</p> <pre><code>sudo apachectl start </code></pre> <p>However, when I try to open localhost in Firefox, I get the message</p> <blockquote> <p>Not Found: The requested URL / was not found on this server. Apache/2.2.21 (Unix) DAV/2 Server at localhost Port 80</p> </blockquote> <p>I edited both httpd.conf and httpd.conf.default to change</p> <pre><code>#ServerName www.website.com </code></pre> <p>to</p> <pre><code>ServerName localhost </code></pre> <p>It still doesn't work. Any suggestions?</p>
12,395,973
3
3
null
2012-09-12 20:19:54.54 UTC
null
2012-10-19 06:41:25.343 UTC
2012-10-19 06:41:25.343 UTC
null
904,365
null
845,349
null
1
9
macos|apache|unix|localhost|osx-mountain-lion
44,551
<p>You should check the permissions on the folder specified as the "DocumentRoot" in your "httpd.conf", and allow at least read access for the Apache user (which should by "_www" by default).<br> Otherwise you could do a "sudo chmod 755" on the "DocumentRoot" folder.<br> By the way, you should only modify the "httpd.conf" file, since the "httpd.conf.default" is a default configuration that you can use if you want to restore the Apache original configuration, by simply overwriting the "httpd.conf" file with the "httpd.conf.default" file.<br> I suppose that you've not enabled name-based virtual hosts, since when you enable name-based virtual hosts, the document root in the main config is ignored; instead, the root for the matching hostname will be used, and if none match it will default to the first virtual host.<br> Finally, when you have problems, the first thing to check is always the Apache error log file.<br> The location of the the error log can be found by looking at the "ErrorLog" directive in the Apache configuration file.</p>
12,060,250
Ignore SSL Certificate Errors with Java
<p>Apache Http Client. You can see the relevant code <a href="https://gist.github.com/3417669" rel="noreferrer">here</a>:</p> <pre><code>String url = "https://path/to/url/service"; HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); // Test whether to ignore cert errors if (ignoreCertErrors){ TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager(){ public X509Certificate[] getAcceptedIssuers(){ return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } catch (Exception e){ e.printStackTrace(); } } try { // Execute the method (Post) and set the results to the responseBodyAsString() int statusCode = client.executeMethod(method); resultsBody = method.getResponseBodyAsString(); } catch (HttpException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } finally { method.releaseConnection(); } </code></pre> <p>This is the method everyone says to use to ignore SSL Certificate Errors (only setting this up for staging, it won't be used in production). However, I am still getting the following exception/stacktrace:</p> <pre><code>javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building unable to find valid certification path to requested target </code></pre> <p>Any tips would be great. If I am doing the TrustManager wrong, or if I should be executing the HTTP Post method differently, either way.</p> <p>Thanks!</p>
12,060,890
4
4
null
2012-08-21 17:46:38.18 UTC
9
2017-09-28 12:49:33.927 UTC
2014-03-24 09:37:41.407 UTC
null
608,639
null
528,576
null
1
10
java|jakarta-ee|ssl|ssl-certificate
114,536
<p>First, don't <em>ignore</em> certificate errors. Deal with them instead. Ignoring certificate errors opens the connection to potential MITM attacks. It's like turning off the buzzer in your smoke alarm because sometimes it makes a noise...</p> <p>Sure, it's tempting to say it's only for test code, it won't end up in production, but we all know what happens when the deadline approaches: the code doesn't show any error when it's being tested -> we can ship it as it is. You should set up a test CA instead if you need. It's not very hard to make, and the overall process is certainly no harder than introducing custom code for development and removing it in production.</p> <p>You're visibly using Apache Http Client:</p> <pre><code>HttpClient client = new HttpClient(); int statusCode = client.executeMethod(method); </code></pre> <p>Yet, you're initialising the <code>javax.net.ssl.HttpsURLConnection</code> with the <code>SSLContext</code> you've created:</p> <pre><code>HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); </code></pre> <p>This is completely independent of the Apache Http Client settings.</p> <p>Instead, you should set up the <code>SSLContext</code> for the Apache Http Client library, as described in <a href="https://stackoverflow.com/a/10406233/372643">this answer</a>. If you're using Apache Http Client 3.x, you need to set up your own <code>SecureProtocolSocketFactory</code> to use that <code>SSLContext</code> (see examples <a href="http://code.google.com/p/jsslutils/wiki/ApacheHttpClientUsage" rel="nofollow noreferrer">here</a>). It's worth upgrading to Apache Http Client 4.x though, which has direct support for <code>SSLContext</code>.</p> <p>You can also use <a href="https://stackoverflow.com/a/1828832/372643">Pascal's answer</a> to import the certificate correctly. Again, if you follow the accepted answer (by Kevin) to that question, you will indeed ignore the error but this will make the connection vulnerable to MITM attacks.</p>
12,102,598
Trigger event with infoWindow or InfoBox on click Google Map API V3
<p>I want to know how to trigger an event when I click on an infoWindow using Google Maps API v3. In this example, when I click on a marker, an info window shows up with a unique message, based on which marker I clicked. I want to also be able to click the info window and have an alert show up that says</p> <blockquote> <p>"You clicked on the infowindow for (<strong>__<em>fill in blank location</em>_</strong>)</p> </blockquote> <p>I found some examples using Google Maps API v2 and jQuery, but not with just plain old Google Maps API v3. </p> <pre class="lang-js prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;jQuery mobile with Google maps - Google maps jQuery plugin&lt;/title&gt; &lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" /&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&amp;sensor=false&amp;language=en"&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; var cityList = [ ['Chicago', 41.850033, -87.6500523, 1], ['Illinois', 40.797177,-89.406738, 2] ]; var demoCenter = new google.maps.LatLng(41,-87); var map; function initialize() { map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 7, center: demoCenter, mapTypeId: google.maps.MapTypeId.ROADMAP }); addMarkers(); } function addMarkers() { var marker, i; var infowindow = new google.maps.InfoWindow(); for (i = 0; i &lt; cityList.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(cityList[i][1], cityList[i][2]), map: map, title: cityList[i][0] }); google.maps.event.addListener(marker, 'click', (function(marker, i) { var contentString = '&lt;div id="infoWindow"&gt;' +'&lt;div id="bodyContent"&gt;' +'&lt;p&gt;' + "This location is:&lt;br&gt;" + marker.title +'&lt;/p&gt;' +'&lt;/div&gt;' + '&lt;/div&gt;'; return function() { infowindow.setContent(contentString); infowindow.open(map, marker); google.maps.event.addListener(infowindow, 'click', (function(i){ alert("You clicked on the infowindow for" + cityList[i][0]); })); } })(marker, i)); } } &lt;/script&gt; &lt;/head&gt; &lt;body onload="initialize()"&gt; &lt;div id="basic-map" data-role="page"&gt; &lt;div data-role="header"&gt; &lt;h1&gt;&lt;a data-ajax="false" href="/"&gt;jQuery mobile with Google maps v3&lt;/a&gt; examples&lt;/h1&gt; &lt;a data-rel="back"&gt;Back&lt;/a&gt; &lt;/div&gt; &lt;div data-role="content"&gt; &lt;div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;"&gt; &lt;div id="map_canvas" style="height:350px;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Update</strong> I ended up figuring this out for InfoBox as well, which is included below in my answer.</p>
12,105,459
6
1
null
2012-08-24 02:52:00.243 UTC
6
2021-06-19 07:44:17.767 UTC
2012-10-26 17:10:41.39 UTC
null
1,239,064
null
1,239,064
null
1
14
google-maps-api-3|infowindow|infobox
57,962
<p>Ok I figured this out for <code>infoWindow</code>, but then I also figured it out for <code>InfoBox</code> since it is prettier and more customizable. I'm new to JavaScript and these closures can be very tricky. </p> <p><strong>For <code>infoWindow</code></strong></p> <pre class="lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;jQuery mobile with Google maps - Google maps jQuery plugin&lt;/title&gt; &lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" /&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&amp;sensor=false&amp;language=en"&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; var cityList = [ ['Chicago', 41.850033, -87.6500523, 1], ['Illinois', 40.797177,-89.406738, 2] ]; var demoCenter = new google.maps.LatLng(41,-87); var map; function initialize() { map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 7, center: demoCenter, mapTypeId: google.maps.MapTypeId.ROADMAP }); addMarkers(); } var boxText1 = document.createElement("div"); boxText1.id = "boxText1"; boxText1.className = "labelText1"; boxText1.innerHTML = "title1";//this is created earlier var boxList = []; function addMarkers() { var marker, i; var infowindow = new google.maps.InfoWindow({ disableAutoPan: true ,isHidden:false ,pixelOffset: new google.maps.Size(-10, -10) ,closeBoxURL: "" ,pane: "mapPane" ,enableEventPropagation: true }); for (var i = 0; i &lt; cityList.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(cityList[i][1], cityList[i][2]), map: map, id: i, title: cityList[i][0] }); var boxText = document.createElement("div"); boxText.id = i; boxText.className = "labelText" + i; boxText.innerHTML = cityList[i][0]; boxList.push(boxText); google.maps.event.addListener(marker, 'click', (function(marker, i) { var contentString = '&lt;div id="infoWindow"&gt;' +'&lt;div id="bodyContent"&gt;' +'&lt;p&gt;' + "This location is:&lt;br&gt;" + marker.title +'&lt;/p&gt;' +'&lt;/div&gt;' + '&lt;/div&gt;'; return function() { infowindow.setContent(boxList[this.id]); infowindow.open(map, marker); } })(marker, i)); //end add marker listener google.maps.event.addDomListener(boxList[i],'click',(function(marker, i) { return function() { alert('clicked ' + cityList[i][0]) } })(marker, i)); } //endfor }//end function &lt;/script&gt; &lt;/head&gt; &lt;body onload="initialize()"&gt; &lt;div id="basic-map" data-role="page"&gt; &lt;div data-role="header"&gt; &lt;h1&gt;&lt;a data-ajax="false" href="/"&gt;jQuery mobile with Google maps v3&lt;/a&gt; examples&lt;/h1&gt; &lt;a data-rel="back"&gt;Back&lt;/a&gt; &lt;/div&gt; &lt;div data-role="content"&gt; &lt;div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;"&gt; &lt;div id="map_canvas" style="height:350px;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>For <code>InfoBox</code></strong></p> <pre class="lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;jQuery mobile with Google maps - Google maps jQuery plugin&lt;/title&gt; &lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" /&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&amp;sensor=false&amp;language=en"&gt; &lt;/script&gt; &lt;script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"&gt; &lt;/script&gt; &lt;script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js"&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; var cityList = [ ['Chicago', 41.850033, -87.6500523, 1], ['Illinois', 40.797177,-89.406738, 2] ]; var demoCenter = new google.maps.LatLng(41,-87); var boxList =[]; function initialize() { map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 7, center: demoCenter, mapTypeId: google.maps.MapTypeId.ROADMAP }); addMarkers(); } function addMarkers(){ for (var i = 0; i &lt; cityList.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(cityList[i][1], cityList[i][2]), map: map, id: i, title: cityList[i][0] }); var boxText = document.createElement("div"); boxText.id = i; boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;"; boxText.innerHTML = "InfoBox for " + cityList[i][0]; var myOptions = { content: boxText ,disableAutoPan: false ,maxWidth: 0 ,pixelOffset: new google.maps.Size(-140, 0) ,zIndex: null ,boxStyle: { background: "url('tipbox.gif') no-repeat" ,opacity: 0.75 ,width: "280px" } ,closeBoxMargin: "10px 2px 2px 2px" ,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif" ,infoBoxClearance: new google.maps.Size(1, 1) ,isHidden: false ,pane: "floatPane" ,enableEventPropagation: false }; var ib = new InfoBox(myOptions); boxList.push(ib); google.maps.event.addListener(marker,'click',(function(marker, i) { return function() { boxList[i].open(map, this); } })(marker, i)); google.maps.event.addDomListener(boxList[i].content_,'click',(function(marker, i) { return function() { alert('clicked ' + cityList[i][0]) } })(marker, i)); } //endfor } //end function &lt;/script&gt; &lt;/head&gt; &lt;body onload="initialize()"&gt; &lt;div id="basic-map" data-role="page"&gt; &lt;div data-role="header"&gt; &lt;h1&gt;&lt;a data-ajax="false" href="/"&gt;jQuery mobile with Google maps v3&lt;/a&gt; examples&lt;/h1&gt; &lt;a data-rel="back"&gt;Back&lt;/a&gt; &lt;/div&gt; &lt;div data-role="content"&gt; &lt;div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;"&gt; &lt;div id="map_canvas" style="height:350px;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
12,552,210
Play 2.0+Java vs. Play 2.0+Scala?
<p>I am thinking about migrating to play 2.0 after play 1.2. One thing that bothers me is that people say Scala is more "preferred" for a play 2.0 application. I know the differences over 1.2 and 2.0, but I'm unsure if there are differences between Play 2.0 with Java and Play 2.0 with Scala</p> <p>So there are questions in my mind: </p> <ul> <li>Is there anything that I cannot do with java over scala in a Play 2.0 application?</li> <li>What advantages do I have if I start to learn and use scala in a play 2.0 application?</li> </ul>
12,553,141
4
0
null
2012-09-23 12:04:44.523 UTC
11
2017-08-25 08:27:16.43 UTC
2012-09-23 12:07:54.793 UTC
null
298,389
null
570,005
null
1
36
java|scala|playframework-2.0
12,697
<p>I just finished a prototype using Play 2.0 with Java and now am considering to learn Scala just so I can switch to it for further development.</p> <p>It's not just the usual <em>Java vs. Scala</em> discussion - the problem as I see it with the Play framework is that it forces Scala idioms onto Java. An example from the documentation about <a href="https://www.playframework.com/documentation/2.0.3/JavaWS#composing-results" rel="nofollow noreferrer">calling multiple web services</a>:</p> <pre><code>public static Result feedComments(String feedUrl) { return async( WS.url(feedUrl).get().flatMap( new Function&lt;WS.Response, Promise&lt;Result&gt;&gt;() { public Promise&lt;Result&gt; apply(WS.Response response) { return WS.url(response.asJson().findPath("commentsUrl").get().map( new Function&lt;WS.Response, Result&gt;() { public Result apply(WS.Response response) { return ok("Number of comments: " + response.asJson().findPath("count")); } } ); } } ) ); } </code></pre> <p>It works but doesn't look like conventional Java. Those parentheses look really scary. Even Eclipse gets confused and never knows what generics I need or want to use - I always have to choose them manually.</p> <p>Also note that in the documentation they made this look pretty by removing <code>@Override</code> annotations, using just two spaces for indentation and overall choosing a very simple example without validation or error recovery so they don't use too many lines. I'm not even sure you could configure a code formatter to output it like this without messing up other code completely. </p> <p>In practice I ended up with an unreadable block of a horrible Java-Scala-abomination just for getting some data from another service.</p> <p>Unfortunately I can't find any example of combining responses in Scala. At least calling single <a href="http://www.playframework.org/documentation/2.0.3/ScalaWS" rel="nofollow noreferrer">web services in Scala</a> looks much shorter and easier to read.</p>
19,228,839
why I can't get value of label with jQuery and JavaScript?
<p>I have a usual label</p> <pre><code>&lt;label class=&quot;mytxt&quot; style=&quot;color: #662819;&quot; id =&quot;telefon&quot;&gt;&lt;/label&gt; </code></pre> <p>I am <strong>setting</strong> a value like this:</p> <pre><code>document.getElementById('telefon').innerHTML = userDetails.phone; </code></pre> <p>after a label has some value like <code>&quot;123&quot;</code>.</p> <p>In a <strong>pagesource</strong>, I have a label without setted value inside &quot;&gt;&lt;&quot; but I see as output it alright:</p> <pre><code>pagesource: &lt;label class=&quot;mytxt&quot; style=&quot;color: #662819;&quot; id =&quot;telefon&quot;&gt;&lt;/label&gt; </code></pre> <p>My problem is when I like to <strong>GET</strong> a value. I tried <em>standards</em> like:</p> <pre><code>value = $(&quot;#telefon&quot;).val(); document.getElementById('telefon').value </code></pre> <p>Nothing works, value is always &quot;not defined&quot;. Why is this so, even if I see it in the browser?</p>
19,228,872
2
6
null
2013-10-07 15:34:13.243 UTC
9
2021-04-02 10:24:06.903 UTC
2021-04-02 10:24:06.903 UTC
null
9,193,372
null
291,120
null
1
31
javascript|jquery|get|label
131,910
<p>You need <code>text()</code> or <code>html()</code> for label not <code>val()</code> The function should not be called for label instead it is used to get values of input like text or checkbox etc.</p> <p>Change</p> <pre><code>value = $("#telefon").val(); </code></pre> <p>To</p> <pre><code>value = $("#telefon").text(); </code></pre>
43,069,780
How to create virtual env with python3
<p>I am using <strong>python 2.7</strong> + <strong>virtualenv version 1.10.1</strong> for running myproject projects. Due to some other projects requirement I have to work with other version of python(<strong>Python 3.5</strong>) and <strong>Django 1.9</strong>. For this I have installed python in my user directory. Also I have dowloaded and installed virtualenv( <strong>version - 15.1.0</strong>) into my user directory. But whenever I am trying to create virtual env I am getting the below error</p> <pre><code>python virtualenv/virtualenv.py myproject </code></pre> <hr> <pre><code>Using base prefix '/home/myuser/python3' New python executable in /home/mount/myuser/project_python3/myproject/bin/python ERROR: The executable /home/mount/myuser/project_python3/myproject/bin/python is not functioning ERROR: It thinks sys.prefix is '/home/myuser/python3' (should be '/home/mount/myuser/project_python3/myproject') ERROR: virtualenv is not compatible with this system or executable </code></pre> <p>Can anybody tell what I am doing wrong with this </p>
43,070,301
9
10
null
2017-03-28 12:36:59.07 UTC
11
2021-11-15 14:01:23.273 UTC
null
null
null
null
699,010
null
1
39
python|django|python-3.x|virtualenv
62,872
<p>In Python 3.6+, the pyvenv module is deprecated. Use the following one-liner instead:</p> <pre><code>python3 -m venv &lt;myenvname&gt; </code></pre> <p>This is the <a href="https://docs.python.org/3/library/venv.html" rel="noreferrer">recommended way</a> to create virtual environments by the Python community.</p>