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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16,780,510 | 'module' object is not callable - calling method in another file | <p>I have a fair background in java, trying to learn python. I'm running into a problem understanding how to access methods from other classes when they're in different files. I keep getting module object is not callable.</p>
<p>I made a simple function to find the largest and smallest integer in a list in one file, and want to access those functions in another class in another file.</p>
<p>Any help is appreciated, thanks.</p>
<pre><code>class findTheRange():
def findLargest(self, _list):
candidate = _list[0]
for i in _list:
if i > candidate:
candidate = i
return candidate
def findSmallest(self, _list):
candidate = _list[0]
for i in _list:
if i < candidate:
candidate = i
return candidate
</code></pre>
<hr>
<pre><code> import random
import findTheRange
class Driver():
numberOne = random.randint(0, 100)
numberTwo = random.randint(0,100)
numberThree = random.randint(0,100)
numberFour = random.randint(0,100)
numberFive = random.randint(0,100)
randomList = [numberOne, numberTwo, numberThree, numberFour, numberFive]
operator = findTheRange()
largestInList = findTheRange.findLargest(operator, randomList)
smallestInList = findTheRange.findSmallest(operator, randomList)
print(largestInList, 'is the largest number in the list', smallestInList, 'is the smallest number in the list' )
</code></pre> | 16,780,543 | 2 | 4 | null | 2013-05-27 21:02:47.263 UTC | 9 | 2019-01-21 22:23:12.143 UTC | 2017-10-04 22:02:36.677 UTC | null | 5,780,109 | null | 2,426,318 | null | 1 | 45 | python|import|module | 170,349 | <p>The problem is in the <code>import</code> line. You are importing a <em>module</em>, not a class. Assuming your file is named <code>other_file.py</code> (unlike java, again, there is no such rule as "one class, one file"):</p>
<pre><code>from other_file import findTheRange
</code></pre>
<p>if your file is named findTheRange too, following java's convenions, then you should write</p>
<pre><code>from findTheRange import findTheRange
</code></pre>
<p>you can also import it just like you did with <code>random</code>:</p>
<pre><code>import findTheRange
operator = findTheRange.findTheRange()
</code></pre>
<hr>
<p>Some other comments:</p>
<p>a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)</p>
<p>b) You can build the list directly:</p>
<pre><code> randomList = [random.randint(0, 100) for i in range(5)]
</code></pre>
<p>c) You can call methods in the same way you do in java:</p>
<pre><code>largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)
</code></pre>
<p>d) You can use built in function, and the huge python library:</p>
<pre><code>largestInList = max(randomList)
smallestInList = min(randomList)
</code></pre>
<p>e) If you still want to use a class, and you don't need <code>self</code>, you can use <code>@staticmethod</code>:</p>
<pre><code>class findTheRange():
@staticmethod
def findLargest(_list):
#stuff...
</code></pre> |
25,494,849 | Case-sensitive where statement in laravel | <p>How can I do a case-sensitive string match with laravel?</p>
<hr>
<p><code>SELECT * FROM `invites` WHERE `token`='OGwie2e2985tOEGewgu23hUFs'</code></p>
<p>Can be done as </p>
<p><code>Invite::where('token',$token)->first()</code></p>
<hr>
<p>If I want a case-sensitive match I need to use a statement like this (or similar, as far as I know):</p>
<p><code>SELECT * FROM `invites` WHERE BINARY `token`='OGwie2e2985tOEGewgu23hUFs'</code></p>
<p>My best guess would be:</p>
<p><code>Invite::whereRaw("BINARY `token`='{$token}'")->first()</code></p>
<p>but then my input is not going through a prepared statement, right?</p> | 25,494,937 | 3 | 6 | null | 2014-08-25 21:45:26.173 UTC | 8 | 2021-03-24 17:13:32.763 UTC | null | null | null | null | 439,898 | null | 1 | 23 | php|mysql|laravel-4|eloquent|case-sensitive | 24,103 | <p>You'll need to use DB::raw(), perhaps something like</p>
<pre><code>Invite::where(DB::raw('BINARY `token`'), $token)->first();
</code></pre>
<p>or alternatively:</p>
<pre><code>Invite::whereRaw("BINARY `token`= ?",[$token])->first()
</code></pre> |
51,066,434 | Firebase Cloud Functions: Difference between onRequest and onCall | <p>Going through the docs, I encountered:</p>
<blockquote>
<p>...you can call functions directly with an HTTP request or a <a href="https://firebase.google.com/docs/functions/callable" rel="noreferrer">call from the client</a>.</p>
<p>~ <a href="https://firebase.google.com/docs/functions/#lifecycle_of_a_background_function" rel="noreferrer">source</a></p>
</blockquote>
<p>there <em>(link in the quote)</em> is a mention about <code>functions.https.onCall</code>.</p>
<p>But in the tutorial <a href="https://firebase.google.com/docs/functions/get-started" rel="noreferrer">here</a>, another function <code>functions.https.onRequest</code> is used, so which one should I use and why? What is the difference/similarity between them?</p>
<p>Documentation for <code>functions.https</code> is <a href="https://firebase.google.com/docs/reference/functions/functions.https#.onCall" rel="noreferrer">here</a>.</p> | 51,477,892 | 2 | 7 | null | 2018-06-27 15:22:47.373 UTC | 16 | 2022-04-08 01:19:30.783 UTC | 2020-11-26 14:47:58.71 UTC | null | 2,037,924 | null | 985,454 | null | 1 | 130 | javascript|firebase|google-cloud-functions | 41,218 | <p>The <a href="https://firebase.google.com/docs/functions/callable" rel="noreferrer">official documentation</a> for those is really helpful, but from the view of an amateur, the described differences were confusing at first.</p>
<ul>
<li><p><strong>Both types</strong>, when deployed, are assigned with a unique HTTPS endpoint URL and can be accessed directly using an https client.</p>
</li>
<li><p>However, there is one important difference in the way how they are <strong><em>supposed</em> to be called</strong>.</p>
<ul>
<li><code>onCall</code>: from the client's <code>firebase.functions()</code></li>
<li><code>onRequest</code>: via standard https client (e.g. <code>fetch()</code> API in JS)</li>
</ul>
</li>
</ul>
<h1>onCall</h1>
<ul>
<li><p>Can be invoked (and this is also the main purpose) directly from the client app.</p>
<pre><code> functions.httpsCallable('getUser')({uid})
.then(r => console.log(r.data.email))
</code></pre>
</li>
<li><p>It is implemented with user-provided <code>data</code> and <em>automagic</em> <code>context</code>.</p>
<pre><code> export const getUser = functions.https.onCall((data, context) => {
if (!context.auth) return {status: 'error', code: 401, message: 'Not signed in'}
return new Promise((resolve, reject) => {
// find a user by data.uid and return the result
resolve(user)
})
})
</code></pre>
</li>
<li><p>The <code>context</code> automagically <a href="https://firebase.google.com/docs/reference/functions/providers_https_.callablecontext.html" rel="noreferrer">contains metadata</a> about the request such as <code>uid</code> and <code>token</code>.</p>
</li>
<li><p>Input <code>data</code> and <code>response</code> objects are automatically (de)serialized.</p>
</li>
</ul>
<h1>onRequest</h1>
<ul>
<li><p><a href="https://firebase.google.com/docs/reference/functions/providers_https_#onrequest" rel="noreferrer">Firebase onRequest Docs</a></p>
</li>
<li><p>Serves mostly as an Express API endpoint.</p>
</li>
<li><p>It is implemented with express <code>Request</code> and <code>Response</code> objects.</p>
<pre><code> export const getUser = functions.https.onRequest((req, res) => {
// verify user from req.headers.authorization etc.
res.status(401).send('Authentication required.')
// if authorized
res.setHeader('Content-Type', 'application/json')
res.send(JSON.stringify(user))
})
</code></pre>
</li>
<li><p>Depends on user-provided authorization headers.</p>
</li>
<li><p>You are responsible for input and response data.</p>
</li>
</ul>
<p>Read more here <a href="https://stackoverflow.com/a/49476648/985454">Is the new Firebase Cloud Functions https.onCall trigger better?</a></p> |
4,380,861 | Built in capistrano variables | <p>Does anybody know a listing of all build-in Capistrano variables, like current_path and etc.?</p> | 4,380,894 | 2 | 0 | null | 2010-12-07 19:41:54.943 UTC | 10 | 2018-02-16 23:57:27.097 UTC | 2014-10-31 04:20:09.233 UTC | null | 474,597 | null | 534,151 | null | 1 | 16 | ruby-on-rails|ruby|capistrano | 9,614 | <p>You can find all of them at:</p>
<p><a href="https://github.com/capistrano/capistrano/blob/legacy-v2/lib/capistrano/recipes/deploy.rb" rel="noreferrer">https://github.com/capistrano/capistrano/blob/legacy-v2/lib/capistrano/recipes/deploy.rb</a></p>
<p><strong>Update</strong>: v3 no longer has the same configuration options as v2. I linked the v2 config options above, but the v3 has the following:</p>
<p><img src="https://i.stack.imgur.com/eMBeq.png" alt="Capistrano configuration variables"></p>
<p>Here are the legacy ones, preserved in this post:</p>
<pre><code># =========================================================================
# These variables MUST be set in the client capfiles. If they are not set,
# the deploy will fail with an error.
# =========================================================================
_cset(:application) { abort "Please specify the name of your application, set :application, 'foo'" }
_cset(:repository) { abort "Please specify the repository that houses your application's code, set :repository, 'foo'" }
# =========================================================================
# These variables may be set in the client capfile if their default values
# are not sufficient.
# =========================================================================
_cset(:scm) { scm_default }
_cset :deploy_via, :checkout
_cset(:deploy_to) { "/u/apps/#{application}" }
_cset(:revision) { source.head }
_cset :rails_env, "production"
_cset :rake, "rake"
# =========================================================================
# These variables should NOT be changed unless you are very confident in
# what you are doing. Make sure you understand all the implications of your
# changes if you do decide to muck with these!
# =========================================================================
_cset(:source) { Capistrano::Deploy::SCM.new(scm, self) }
_cset(:real_revision) { source.local.query_revision(revision) { |cmd| with_env("LC_ALL", "C") { run_locally(cmd) } } }
_cset(:strategy) { Capistrano::Deploy::Strategy.new(deploy_via, self) }
# If overriding release name, please also select an appropriate setting for :releases below.
_cset(:release_name) { set :deploy_timestamped, true; Time.now.utc.strftime("%Y%m%d%H%M%S") }
_cset :version_dir, "releases"
_cset :shared_dir, "shared"
_cset :shared_children, %w(public/system log tmp/pids)
_cset :current_dir, "current"
_cset(:releases_path) { File.join(deploy_to, version_dir) }
_cset(:shared_path) { File.join(deploy_to, shared_dir) }
_cset(:current_path) { File.join(deploy_to, current_dir) }
_cset(:release_path) { File.join(releases_path, release_name) }
_cset(:releases) { capture("#{try_sudo} ls -x #{releases_path}", :except => { :no_release => true }).split.sort }
_cset(:current_release) { releases.length > 0 ? File.join(releases_path, releases.last) : nil }
_cset(:previous_release) { releases.length > 1 ? File.join(releases_path, releases[-2]) : nil }
_cset(:current_revision) { capture("#{try_sudo} cat #{current_path}/REVISION", :except => { :no_release => true }).chomp }
_cset(:latest_revision) { capture("#{try_sudo} cat #{current_release}/REVISION", :except => { :no_release => true }).chomp }
_cset(:previous_revision) { capture("#{try_sudo} cat #{previous_release}/REVISION", :except => { :no_release => true }).chomp if previous_release }
_cset(:run_method) { fetch(:use_sudo, true) ? :sudo : :run }
# some tasks, like symlink, need to always point at the latest release, but
# they can also (occassionally) be called standalone. In the standalone case,
# the timestamped release_path will be inaccurate, since the directory won't
# actually exist. This variable lets tasks like symlink work either in the
# standalone case, or during deployment.
_cset(:latest_release) { exists?(:deploy_timestamped) ? release_path : current_release }
_cset :maintenance_basename, "maintenance"
_cset(:maintenance_template_path) { File.join(File.dirname(__FILE__), "templates", "maintenance.rhtml") }
</code></pre> |
4,445,713 | Django testing tips | <p>In the spirit of this <a href="https://stackoverflow.com/questions/550632/favorite-django-tips-features">question</a>, I would like to know if anyone has any tips on creating a useful and "complete" test suite (can a test suite ever be "complete"?) for a Django webapp.</p>
<p><strong>My situation:</strong> I've knocked out a prototype and am now working on adding some regression testing. I personally use <a href="http://bitbucket.org/kmike/django-webtest/src" rel="nofollow noreferrer">django-webtest</a> for most of my tests with some URL testing using the <a href="http://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client" rel="nofollow noreferrer">Django test client</a>.</p>
<p>II do not feel comfortable with my test suite at all. I am far from a testing pro so trying to improve on that end. Any tips---whether applicable in my situation or not---would be greatly appreciated.</p> | 4,466,174 | 2 | 1 | null | 2010-12-15 00:38:19.603 UTC | 15 | 2011-01-13 16:39:46.56 UTC | 2017-05-23 11:45:38.01 UTC | null | -1 | null | 441,923 | null | 1 | 17 | python|django|unit-testing|testing|django-testing | 2,728 | <p>I would recommend reading <a href="https://www.packtpub.com/django-1-1-testing-and-debugging/book"><em>Django 1.1 Testing and Debugging</em> by Karen M. Tracey</a>. The first five chapters cover testing in Django. Specifically, you should look at Chapter 5 which discusses integrating other test tools. Below is an excerpt of what Chapter 5 covers:</p>
<blockquote>
<p>In this chapter, we:</p>
<ul>
<li>Learned what hooks Django provides for adding test functions</li>
<li>Saw an example of how these hooks can be used, specifically in the case of adding code coverage reporting</li>
<li>Also explored an example where using these hooks was not necessary—when integrating the use of the <code>twill</code> test tool into our Django test cases</li>
</ul>
</blockquote>
<p>Here are links to some of the tools that Karen Tracey discusses in chapter 5 of her book:</p>
<ul>
<li><a href="http://nedbatchelder.com/code/coverage/">Ned Batchelder's <code>coverage</code> module</a></li>
<li><a href="http://twill.idyll.org/">Twill</a></li>
</ul>
<h3>Lettuce</h3>
<p>You may also want to check out <a href="http://lettuce.it/">Lettuce</a>. From the website:</p>
<blockquote>
<p>Lettuce is a very simple BDD tool based on the Cucumber.</p>
</blockquote>
<p>The Lettuce documentation also has a section on <a href="http://lettuce.it/recipes/django-lxml.html#recipes-django-lxml">integrating Lettuce with Django</a>.</p> |
4,133,889 | NuGet (NuPack) intellisense (Visual Studio Package Manager Console) | <p>My intellisense for NuGet doesn't show up. Or maybe there is some kind of shortcut for it ? </p> | 4,134,189 | 2 | 5 | null | 2010-11-09 12:59:45.523 UTC | 4 | 2015-10-14 08:03:38.763 UTC | 2012-12-06 17:29:25.683 UTC | null | 195,755 | null | 420,555 | null | 1 | 32 | .net|visual-studio|nuget | 9,823 | <p>I don't think the intellisense is what you expect, as in a dropdown with a list of available options. </p>
<p><a href="http://nuget.codeplex.com/wikipage?title=Getting%20Started" rel="noreferrer">From this page</a>, it appears you have to hit <kbd>tab</kbd> in order to get command completion.</p> |
41,469,055 | Sublime Text 3 white boxes around lines | <p><a href="https://i.stack.imgur.com/kVmuo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kVmuo.png" alt="enter image description here"></a></p>
<p>Note: Just started programming in Python using Sublime Text 3. I am not sure why I am getting the white dots/mark on every line, see image below. I would like learn the following.</p>
<ol>
<li>Is it because of an error?</li>
<li>Is it because of a package or command?</li>
<li>I tried CTRL+Space,CTRL+G and CTRL+K and I still get the white marks, shall I be concerned? </li>
</ol> | 41,709,777 | 8 | 7 | null | 2017-01-04 16:43:46.237 UTC | 10 | 2022-07-19 20:40:04.977 UTC | 2017-01-04 17:36:43.887 UTC | null | 1,426,065 | null | 6,067,330 | null | 1 | 40 | sublimetext3|sublimetext | 21,695 | <p>You probably installed Anaconda package. If so, you need to go to Preferences → Package Settings → Anaconda → Settings-User. Then paste the following code and save. Those boxes should be gone.</p>
<pre><code>{
"anaconda_linting": false,
}
</code></pre> |
9,701,456 | Multidimensional Array Of Signals in VHDL | <p>I have a signal in VHDL declared like this : </p>
<pre><code>signal Temp_Key : std_logic_vector(79 downto 0);
</code></pre>
<p>This <code>Temp_Key</code> is passed through a <code>for</code> loop 31 times and it is modified. I want to store all the 31 different <code>Temp_Keys</code> in an array. </p>
<p>Is it possible to use multi-dimensional arrays in VHDL to store 80 bit signals ? </p> | 9,702,456 | 3 | 0 | null | 2012-03-14 11:54:16.347 UTC | 6 | 2017-07-28 07:29:00.393 UTC | 2012-03-15 11:16:40.323 UTC | null | 106,092 | null | 929,935 | null | 1 | 11 | arrays|vhdl | 54,869 | <p>Yes, first you need to declare a type:</p>
<pre><code>type YOUR_ARRAY_TYPE is array (0 to 30) of std_logic_vector(79 downto 0);
</code></pre>
<p>Note you can also declare the type to be of undefined length - so you can specify how many 80 bit words it has when you declare your signal. And with VHDL 2008, you can also leave the size of the slv unspecified, also to be declared when you create your signal. For example:</p>
<pre><code>type slv_array is array (natural range <>) of std_logic_vector;
</code></pre>
<p>and then use it</p>
<pre><code>signal MY_SIGNAL : YOUR_ARRAY_TYPE;
...
MY_SIGNAL(0) <= data;
...
MY_SIGNAL(1) <= data;
</code></pre>
<p>See <a href="http://www.seas.upenn.edu/~ese171/vhdl/vhdl_primer.html#_Toc526061356">here</a> for a reference.</p> |
9,912,578 | How to save an XML file to disk with python? | <p>I have some python code to generate some XML text with xml.dom.minidom . Right now, I run it from the terminal and it outputs me a structured XML as a result. I would like it also to generate an XML file and save it to my disk. How could that be done?</p>
<p>This is what I have:</p>
<pre><code>import xml
from xml.dom.minidom import Document
import copy
class dict2xml(object):
doc = Document()
def __init__(self, structure):
if len(structure) == 1:
rootName = str(structure.keys()[0])
self.root = self.doc.createElement(rootName)
self.doc.appendChild(self.root)
self.build(self.root, structure[rootName])
def build(self, father, structure):
if type(structure) == dict:
for k in structure:
tag = self.doc.createElement(k)
father.appendChild(tag)
self.build(tag, structure[k])
elif type(structure) == list:
grandFather = father.parentNode
tagName = father.tagName
# grandFather.removeChild(father)
for l in structure:
tag = self.doc.createElement(tagName.rstrip('s'))
self.build(tag, l)
father.appendChild(tag)
else:
data = str(structure)
tag = self.doc.createTextNode(data)
father.appendChild(tag)
def display(self):
print self.doc.toprettyxml(indent=" ")
</code></pre>
<p>This just generates the XML. How could I also have it saved as a file to my desktop?</p> | 9,912,724 | 2 | 0 | null | 2012-03-28 17:21:18.72 UTC | 5 | 2017-09-14 09:36:48.893 UTC | 2012-03-30 05:59:40.45 UTC | null | 1,191,425 | null | 1,222,373 | null | 1 | 14 | python|xml|file | 60,354 | <p>You probably want to use <code>Node.writexml()</code> on the root node of your XML DOM tree. This will write your root element and all child elements to an XML file, doing all the becessary indenting etc. along the way.</p>
<p><a href="http://docs.python.org/library/xml.dom.minidom.html" rel="noreferrer">See the documentation for <code>xml.dom.minidom</code>:</a></p>
<blockquote>
<p><code>Node.writexml(writer[, indent=""[, addindent=""[, newl=""]]])</code></p>
<p>Write XML to the writer object. The writer should have a <code>write()</code>
method which matches that of the file object interface. The <code>indent</code>
parameter is the indentation of the current node. The <code>addindent</code>
parameter is the incremental indentation to use for subnodes of the
current one. The <code>newl</code> parameter specifies the string to use to
terminate newlines.</p>
<p>For the Document node, an additional keyword argument encoding can be
used to specify the encoding field of the XML header.</p>
<p>Changed in version 2.1: The optional keyword parameters indent,
addindent, and newl were added to support pretty output.</p>
<p>Changed in version 2.3: For the Document node, an additional keyword
argument encoding can be used to specify the encoding field of the XML
header.</p>
</blockquote>
<p>Usage will be somewhat like:</p>
<pre><code>file_handle = open("filename.xml","wb")
Your_Root_Node.writexml(file_handle)
file_handle.close()
</code></pre> |
10,022,796 | Why am I getting this error Premature end of file? | <p>I am trying to parse an <code>XML response</code>, but I am failing miserably. I thought initially
that the <code>xml</code> was just not being returned in the response, so I crafted up the code below with a direct link to my <code>xml</code> file online. I am able to print the <code>XML</code> to screen with no problems. However when I call my parse method I get <strong>Premature end of file.</strong> </p>
<p>It works if I pass the URL directly: </p>
<ul>
<li>builder.parse("");</li>
</ul>
<p>but fails when I passed an InputStream: </p>
<ul>
<li><p>builder.parse(connection.getInputStream());</p>
<pre><code> try {
URL url = new URL(xml);
URLConnection uc = url.openConnection();
HttpURLConnection connection = (HttpURLConnection )uc;
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream instream;
InputSource source;
//get XML from InputStream
if(connection.getResponseCode()>= 200){
connection.connect();
instream = connection.getInputStream();
parseDoc(instream);
}
else{
instream = connection.getErrorStream();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
static void parseDoc(InputStream instream) throws ParserConfigurationException,
SAXException, IOException{
BufferedReader buff_read = new BufferedReader(new InputStreamReader(instream,"UTF-8"));
String inputLine = null;
while((inputLine = buff_read.readLine())!= null){
System.out.println(inputLine);
}
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
factory.isIgnoringElementContentWhitespace();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(instream);
}
</code></pre></li>
</ul>
<p>The errors I am getting:</p>
<pre><code> [Fatal Error] :1:1: Premature end of file.
org.xml.sax.SAXParseException: Premature end of file.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at com.ameba.api.network.MainApp.parseDoc(MainApp.java:78)
at com.ameba.api.network.MainApp.main(MainApp.java:41)
</code></pre> | 10,023,157 | 8 | 3 | null | 2012-04-05 04:43:54.127 UTC | 4 | 2022-07-29 11:09:20.447 UTC | 2020-03-06 13:53:20.113 UTC | null | 547,071 | null | 1,243,905 | null | 1 | 30 | java|xml|httpurlconnection | 267,521 | <p>When you do this,</p>
<pre><code>while((inputLine = buff_read.readLine())!= null){
System.out.println(inputLine);
}
</code></pre>
<p>You consume everything in instream, so instream is empty. Now when try to do this,</p>
<pre><code>Document doc = builder.parse(instream);
</code></pre>
<p>The parsing will fail, because you have passed it an empty stream.</p> |
27,978,078 | How to separate initial data load from incremental children with Firebase? | <p>I have an application where new children get added to Firebase every 5 seconds or so. I have thousands of children.</p>
<p>On application load, I'd like to process the initial thousands differently from the subsequent children that trickle in every 5 seconds.</p>
<p>You might suggest I use value, process everything, and then use children_added. But I believe if the processing takes too long I have the potential to miss a point. </p>
<p>Is there a way to do this in Firebase that guarantees I don't miss a point?</p> | 27,995,609 | 4 | 6 | null | 2015-01-16 05:55:47.443 UTC | 11 | 2020-08-18 08:49:57.27 UTC | 2017-01-20 02:26:37.253 UTC | null | 4,872,155 | null | 1,193,105 | null | 1 | 37 | firebase|firebase-realtime-database | 14,373 | <p>Since <code>child_added</code> events for the initial, pre-loaded data will fire <em>before</em> the <code>value</code> event fires on the parent, you can use the <code>value</code> event as a sort of "initial data loaded" notification. Here is some code I slightly modified from <a href="https://stackoverflow.com/questions/19883736/how-to-discard-initial-data-in-a-firebase-db">another similar StackOverflow question</a>.</p>
<pre><code>var initialDataLoaded = false;
var ref = new Firebase('https://<your-Firebase>.firebaseio.com');
ref.on('child_added', function(snapshot) {
if (initialDataLoaded) {
var msg = snapshot.val().msg;
// do something here
} else {
// we are ignoring this child since it is pre-existing data
}
});
ref.once('value', function(snapshot) {
initialDataLoaded = true;
});
</code></pre>
<p>Thankfully, Firebase will smartly cache this data, meaning that creating both a <code>child_added</code> and a <code>value</code> listener will only download the data one time. Adding new Firebase listeners for data which has already crossed the wire is extremely cheap and you should feel comfortable doing things like that regularly.</p>
<p>If you are worried about downloading all that initial data when you don't actually need it, I would follow @FrankvanPuffelen's suggestions in the comments to use a timestamped query. This works really well and is optimized using Firebase queries.</p> |
7,795,054 | H.264 codec explained | <p>I am making a app which supports video calls and I am looking for a tutorial/doc explaining the structure of the h.264 codec. I want to be able to package the stream, wrap it in datagrams, send and unpack on the receiving side.</p>
<p>Any suggestions/reading materials?</p> | 7,797,141 | 3 | 0 | null | 2011-10-17 14:13:15.5 UTC | 9 | 2018-01-29 09:31:59.49 UTC | null | null | null | null | 537,936 | null | 1 | 11 | algorithm|video|video-streaming|video-processing|h.264 | 18,640 | <p>What do you mean by structure? If you are talking about the bitstream syntax, you can download the <a href="http://www.itu.int/rec/T-REC-H.264/en" rel="nofollow noreferrer">H.264 standard</a> for free. There are also many books/papers about H.264 such as the one by <a href="http://www.vcodex.com/h264.html" rel="nofollow noreferrer">Iain Richardson</a>.</p>
<p>If you are more interested in the network transport of H.264 over IP, why don't you use the <a href="https://www.rfc-editor.org/rfc/rfc3550" rel="nofollow noreferrer">RTP</a> standard and associated <a href="https://www.rfc-editor.org/rfc/rfc3984" rel="nofollow noreferrer">payload format</a>?</p> |
8,245,687 | Numpy Root-Mean-Squared (RMS) smoothing of a signal | <p>I have a signal of electromyographical data that I am supposed (scientific papers' explicit recommendation) to smooth using RMS.</p>
<p>I have the following working code, producing the desired output, but it is way slower than I think it's possible.</p>
<pre><code>#!/usr/bin/python
import numpy
def rms(interval, halfwindow):
""" performs the moving-window smoothing of a signal using RMS """
n = len(interval)
rms_signal = numpy.zeros(n)
for i in range(n):
small_index = max(0, i - halfwindow) # intended to avoid boundary effect
big_index = min(n, i + halfwindow) # intended to avoid boundary effect
window_samples = interval[small_index:big_index]
# here is the RMS of the window, being attributed to rms_signal 'i'th sample:
rms_signal[i] = sqrt(sum([s**2 for s in window_samples])/len(window_samples))
return rms_signal
</code></pre>
<p>I have seen some <code>deque</code> and <code>itertools</code> suggestions regarding optimization of moving window loops, and also <code>convolve</code> from numpy, but I couldn't figure it out how to accomplish what I want using them.</p>
<p>Also, I do not care to avoid boundary problems anymore, because I end up having large arrays and relatively small sliding windows.</p>
<p>Thanks for reading</p> | 8,260,297 | 3 | 3 | null | 2011-11-23 16:29:00.897 UTC | 8 | 2019-07-16 05:34:03.317 UTC | 2011-11-23 21:58:50.243 UTC | null | 401,828 | null | 401,828 | null | 1 | 14 | numpy|iteration|scipy|smoothing|moving-average | 23,646 | <p>It <strong>is</strong> possible to use convolution to perform the operation you are referring to. I did it a few times for processing EEG signals as well.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def window_rms(a, window_size):
a2 = np.power(a,2)
window = np.ones(window_size)/float(window_size)
return np.sqrt(np.convolve(a2, window, 'valid'))
</code></pre>
<p>Breaking it down, the <code>np.power(a, 2)</code> part makes a new array with the same dimension as <code>a</code>, but where each value is squared. <code>np.ones(window_size)/float(window_size)</code> produces an array or length <code>window_size</code> where each element is <code>1/window_size</code>. So the convolution effectively produces a new array where each element <code>i</code> is equal to </p>
<pre><code>(a[i]^2 + a[i+1]^2 + … + a[i+window_size]^2)/window_size
</code></pre>
<p>which is the RMS value of the array elements within the moving window. It should perform really well this way.</p>
<p>Note, though, that <code>np.power(a, 2)</code> produces a <strong>new</strong> array of same dimension. If <code>a</code> is <strong>really</strong> large, I mean sufficiently large that it cannot fit twice in memory, you might need a strategy where each element are modified in place. Also, the <code>'valid'</code> argument specifies to discard border effects, resulting in a smaller array produced by <code>np.convolve()</code>. You could keep it all by specifying <code>'same'</code> instead (see <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html">documentation</a>).</p> |
7,904,756 | Class not found loading JDBC org.postgresql.Driver | <p>I'm working on a web project and I recently installed postgres 9.1.1</p>
<p>The postgresql server is up and running. I can connect via psql as usual and everything is loaded and properly saved from a dump of the db I made from 8.5.</p>
<p>So I also downloaded the JDBC4 driver for 9.1 postgres version here:
<a href="http://jdbc.postgresql.org/download/postgresql-jdbc-9.1-901.src.tar.gz" rel="noreferrer">http://jdbc.postgresql.org/download/postgresql-jdbc-9.1-901.src.tar.gz</a></p>
<p>I added it to the java build path using the project properties via eclipse.</p>
<p>This is the code I use to provide db connection to other classes (i.e. it's a singleton, I get a new connection only if the existing is either closed or null, from one object at a time only)</p>
<pre><code>public abstract class DBConnection {
private static Connection connection = null;
public static void connect() {
try {
if (connection == null) {
String host = "127.0.0.1";
String database = "xxxxx";
String username = "xxxxx";
String password = "xxxxx";
String url = "jdbc:postgresql://" + host + "/" + database;
String driverJDBC = "org.postgresql.Driver";
Class.forName(driverJDBC);
connection = DriverManager.getConnection(url, username,
password); //line firing the class not found exception
} else if (connection.isClosed()) {
connection = null;
connect();
}
} catch (SQLException e) {
e.printStackTrace(System.err);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public static void disconnect() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
public static Connection getConnection() {
try {
if (connection != null && !connection.isClosed()) {
return connection;
} else {
connect();
return connection;
}
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE,
null, e);
return null;
}
}
@Override
public void finalize() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
Logger.getLogger(DBConnection.class.getName()).log(
Level.SEVERE, null, e);
}
}
}
}
</code></pre>
<p>As I wrote in the title when I run the project and a class asks for a connection to this class I always get a Class Not Found Exception, Since it apparently can't load the org.postgresql.Driver.class The driver is located in a subfolder of the project ~/lib/org.postgresql-9.1-901.jdbc4.jar and as I said added to the build path via eclipse project properties.</p>
<p>I'm also providing a sample query to let see the usual behavior of my classes to access the DBConnection:</p>
<pre><code>public static final User validateUserCredentials(String id, String pswd) {
Connection connection = DBConnection.getConnection();
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE, (connection!=null)?"connection not null":"connection null");
Statement stmt = null;
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, "validating credentials for user: username : " + id + " password : " + pswd);
String sql = "Select * from fuser where id = '" + id + "'";
ResultSet resultset = null;
try {
stmt = connection.createStatement();
resultset = stmt.executeQuery(sql);
Logger.getLogger(Credentials.class.getName())
.log(Level.SEVERE, sql);
resultset.next();
String password = resultset.getString("pswd");
if (pswd.equals(password))
return new User(id, pswd);
} catch (SQLException ex) {
Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
if (stmt != null)
stmt = null;
if (resultset != null)
resultset = null;
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
connection = null;
}
}
return null;
}
</code></pre> | 7,905,397 | 3 | 5 | null | 2011-10-26 15:11:21.56 UTC | 4 | 2017-03-03 18:33:30.69 UTC | 2011-10-26 15:43:32.39 UTC | null | 201,058 | null | 201,058 | null | 1 | 19 | java|postgresql|jdbc | 96,136 | <blockquote>
<p><em>I'm working on a <strong>web project</strong> and I recently installed postgres 9.1.1</em></p>
<p>...</p>
<p><em>I added it to the java build path <strong>using the project properties</strong> via eclipse.</em></p>
</blockquote>
<p>That's the wrong way. That JAR has to be dropped straight in <code>/WEB-INF/lib</code> folder of the web project without fiddling with the <em>Build Path</em> in the project's properties. That folder is standard part of webapp's runtime classpath.</p>
<hr />
<p><strong>Unrelated</strong> to the concrete problem: you've a major design flaw in your <code>DBConnection</code> class. You've declared <code>Connection</code> as <code>static</code> which essentially makes your connection <strong>not threadsafe</strong>. Use a connection pool and never assign the <code>Connection</code> (nor <code>Statement</code> nor <code>ResultSet</code>) as a class/instance variable. They should be created and closed in the very same <code>try-finally</code> block as where you're executing the query. Further you've there also a SQL injection hole. Use <code>PreparedStatement</code> instead of concatenating user-controlled variables in the SQL string.</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/2313197/jdbc-mysql-connection-pooling-practices/2313262#2313262">JDBC MySql connection pooling practices to avoid exhausted connection pool</a></li>
<li><a href="https://stackoverflow.com/questions/4491596/get-database-connection-from-a-connection-pool/4492111#4492111">Get database connection from a connection pool</a></li>
<li><a href="https://stackoverflow.com/questions/7592056/am-i-using-jdbc-connection-pooling/7592081#7592081">Am I Using JDBC Connection Pooling?</a></li>
</ul> |
11,813,800 | jQuery object get value by key | <p>How would you get the value of <code>assocIMG</code> by key matching the key eg</p>
<p>if I have a var <code>11786</code> I want it to return <code>media/catalog/product/8795139_633.jpg</code></p>
<pre><code>var spConfig = {
"attributes": {
"125": {
"id": "125",
"code": "pos_colours",
"label": "Colour",
"options": [{
"id": "236",
"label": "Dazzling Blue",
"price": "0",
"oldPrice": "0",
"products": ["11148"]
}, {
"id": "305",
"label": "Vintage Brown",
"price": "0",
"oldPrice": "0",
"products": ["11786", "11787", "11788", "11789", "11790", "11791", "11792", "11793"]
}]
}
}
};
var assocIMG = // Added - Removed { here, causes issues with other scripts when not working with a configurable product.
{
11786: 'media/catalog/product/8795139_633.jpg',
11787: 'media/catalog/product/8795139_633.jpg',
}
</code></pre>
<p>Above is the objects I am working with and below is my current jQuery. Help would be greatly appreciated.</p>
<pre><code>$('#attribute125').change(function() {
var image = $(this).val();
$.each(spConfig.attributes, function() {
prods = $(this.options).filter( function() { return this.id == image; } )[0].products[0];
alert(prods);
});
});
</code></pre> | 11,813,961 | 3 | 1 | null | 2012-08-05 03:48:26.447 UTC | 4 | 2012-08-05 04:38:01.723 UTC | 2012-08-05 04:21:12.987 UTC | null | 1,216,976 | null | 1,095,118 | null | 1 | 7 | javascript|jquery | 51,070 | <p>You can use <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Member_Operators#Bracket_notation" rel="noreferrer">bracket notation</a> to get object members by their keys. You have the variable <code>prods</code> containing a string (<code>"11786"</code>), and the object <code>assocIMG</code> with various keys. Then just use</p>
<pre><code>assocIMG[prods]
</code></pre>
<p>to get the property value <code>'media/catalog/product/8795139_633.jpg'</code> which is associated with that key. </p>
<p>Note that you should always use strings as keys in your object literal, IE does not support numbers there:</p>
<pre><code>var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg'
};
</code></pre>
<hr>
<p>Another improvement to your script would be not to loop through the <code>spConfig.attributes</code> each time, and potentially execute your action multiple times if an image is contained in more than one attribute. Instead, build a hash object out of it, where you can just look up the respective product id.</p>
<pre><code>var productById = {};
$.each(spConfig.attributes, function() {
$.each(this.options, function() {
var id = this.id;
productsById[i] = this.products[0];
});
});
$('#attribute').change(function() {
var id = this.value;
var prod = productById[id];
var image = assocIMG[prod];
$("#product_img").attr("src", image);
});
</code></pre> |
11,852,645 | How to create an object inside another class with a constructor? | <p>So I was working on my code, which is designed in a modular way. Now, one of my classes; called <code>Splash</code> has to create a object of another class which is called <code>Emitter</code>. Normally you would just create the object and be done with it, but that doesn't work here, as the <code>Emitter</code> class has a custom constructor. But when I try to create an object, it doesn't work.</p>
<p>As an example;</p>
<p><code>Emitter</code> has a constructor like so: <code>Emitter::Emitter(int x, int y, int amount);</code> and needs to be created so it can be accessed in the <code>Splash</code> class.</p>
<p>I tried to do this, but it didn't work:</p>
<pre><code>class Splash{
private:
Emitter ps(100, 200, 400, "firstimage.png", "secondimage.png"); // Try to create object, doesn't work.
public:
// Other splash class functions.
}
</code></pre>
<p>I also tried this, which didn't work either:</p>
<pre><code>class Splash{
private:
Emitter ps; // Try to create object, doesn't work.
public:
Splash() : ps(100, 200, 400, "firstimage.png", "secondimage.png")
{};
}
</code></pre>
<p><strong>Edit:</strong> I know the second way is supposed to work, however it doesn't. If I remove the <code>Emitter</code> Section, the code works. but when I do it the second way, no window opens, no application is executed.</p>
<p>So how can I create my <code>Emitter</code> object for use in <code>Splash</code>?</p>
<p><strong>Edit:</strong></p>
<p>Here is my code for the emitter class and header:
<code>Header</code></p>
<pre><code>// Particle engine for the project
#ifndef _PARTICLE_H_
#define _PARTICLE_H_
#include <vector>
#include <string>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "image.h"
extern SDL_Surface* gameScreen;
class Particle{
private: // Particle settings
int x, y;
int lifetime;
private: // Particle surface that shall be applied
SDL_Surface* particleScreen;
public: // Constructor and destructor
Particle(int xA, int yA, string particleSprite);
~Particle(){};
public: // Various functions
void show();
bool isDead();
};
class Emitter{
private: // Emitter settings
int x, y;
int xVel, yVel;
private: // The particles for a dot
vector<Particle> particles;
SDL_Surface* emitterScreen;
string particleImg;
public: // Constructor and destructor
Emitter(int amount, int x, int y, string particleImage, string emitterImage);
~Emitter();
public: // Helper functions
void move();
void show();
void showParticles();
};
#endif
</code></pre>
<p>and here is the emitter functions:</p>
<pre><code>#include "particle.h"
// The particle class stuff
Particle::Particle(int xA, int yA, string particleSprite){
// Draw the particle in a random location about the emitter within 25 pixels
x = xA - 5 + (rand() % 25);
y = yA - 5 + (rand() % 25);
lifetime = rand() % 6;
particleScreen = Image::loadImage(particleSprite);
}
void Particle::show(){
// Apply surface and age particle
Image::applySurface(x, y, particleScreen, gameScreen);
++lifetime;
}
bool Particle::isDead(){
if(lifetime > 11)
return true;
return false;
}
// The emitter class stuff
Emitter::Emitter(int amount, int x, int y, string particleImage, string emitterImage){
// Seed the time for random emitter
srand(SDL_GetTicks());
// Set up the variables and create the particles
x = y = xVel = yVel = 0;
particles.resize(amount, Particle(x, y, particleImage));
emitterScreen = Image::loadImage(emitterImage);
particleImg = particleImage;
}
Emitter::~Emitter(){
particles.clear();
}
void Emitter::move(){
}
void Emitter::show(){
// Show the dot image.
Image::applySurface(x, y, emitterScreen, gameScreen);
}
void Emitter::showParticles(){
// Go through all the particles
for(vector<Particle>::size_type i = 0; i != particles.size(); i++){
if(particles[i].isDead() == true){
particles.erase(particles.begin() + i);
particles.insert(particles.begin() + i, Particle(x, y, particleImg));
}
}
// And show all the particles
for(vector<Particle>::size_type i = 0; i != particles.size(); i++){
particles[i].show();
}
}
</code></pre>
<p>Also here is the <a href="http://pastebin.com/5VaYsLUd" rel="noreferrer">Splash Class</a> and the <a href="http://pastebin.com/ks1Bpr07" rel="noreferrer">Splash Header</a>.</p> | 11,852,806 | 2 | 11 | null | 2012-08-07 19:21:07.283 UTC | 5 | 2012-08-07 20:25:17.69 UTC | 2012-08-07 20:18:34.853 UTC | null | 997,196 | null | 997,196 | null | 1 | 7 | c++|class|object|constructor | 61,946 | <p>The second option should work, and I would start looking at compilation errors to see why it doesn't. In fact, please post any compilation errors you have related to this code. </p>
<p>In the meantime, you can do something like this:</p>
<pre><code>class Splash{
private:
Emitter* ps;
public:
Splash() { ps = new Emitter(100,200,400); }
Splash(const Splash& copy_from_me) { //you are now responsible for this }
Splash & operator= (const Splash & other) { //you are now responsible for this}
~Splash() { delete ps; }
};
</code></pre> |
12,006,223 | How to close socket | <p>Run c++ on Ubuntu.
I open socket in this way:</p>
<pre><code>socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW))
</code></pre>
<p>What do i need to do in the end of the use?
Some socket will be used as long as the program run , do i need to check them from a while? to see if socket still exist?</p> | 12,006,269 | 2 | 5 | null | 2012-08-17 12:52:04.963 UTC | 1 | 2012-08-17 12:59:06.937 UTC | null | null | null | null | 809,152 | null | 1 | 11 | c++|sockets | 59,315 | <p>The socket exists until you call <code>close</code> on its file descriptor. Since you have a raw IP socket, there's no notion of "being alive". Just close it when you're done using it.</p> |
11,673,445 | Backbone Marionette - Add a visual effect when switching view | <p>Is there a convenient way to add an effect when I leave a page (close a view/layout) and open a new one in the same region ? (something like a fade effect)</p> | 11,680,644 | 5 | 0 | null | 2012-07-26 16:05:32.513 UTC | 13 | 2015-03-12 11:14:45.057 UTC | null | null | null | null | 1,538,195 | null | 1 | 14 | backbone.js|marionette | 10,026 | <p>Marionette regions have a method called <code>open</code> that by default just replace the HTML of the old view with the new view. You can override this method to do any animation you like. From the <a href="https://github.com/derickbailey/backbone.marionette/blob/master/docs/marionette.region.md">region documentation</a>:</p>
<h2>Set How View's <code>el</code> Is Attached</h2>
<p>If you need to change how the view is attached to the DOM when
showing a view via a region, override the <code>open</code> method of the
region. This method receives one parameter - the view to show.</p>
<p>The default implementation of <code>open</code> is:</p>
<pre><code>Marionette.Region.prototype.open = function(view){
this.$el.html(view.el);
}
</code></pre>
<p>This will replace the contents of the region with the view's
<code>el</code> / content. You can change to this be anything you wish,
though, facilitating transition effects and more.</p>
<pre><code>Marionette.Region.prototype.open = function(view){
this.$el.hide();
this.$el.html(view.el);
this.$el.slideDown("fast");
}
</code></pre>
<p>This example will cause a view to slide down from the top
of the region, instead of just appearing in place.</p> |
11,809,666 | Rename files using regular expression in linux | <p>I have a set of files named like:</p>
<pre class="lang-none prettyprint-override"><code>Friends - 6x03 - Tow Ross' Denial.srt
Friends - 6x20 - Tow Mac and C.H.E.E.S.E..srt
Friends - 6x05 - Tow Joey's Porshe.srt
</code></pre>
<p>and I want to rename them like the following</p>
<pre class="lang-none prettyprint-override"><code>S06E03.srt
S06E20.srt
S06E05.srt
</code></pre>
<p>what should I do to make the job done in linux terminal?
I have installed rename but U get errors using the following:</p>
<pre><code>rename -n 's/(\w+) - (\d{1})x(\d{2})*$/S0$2E$3\.srt/' *.srt
</code></pre> | 11,809,805 | 8 | 1 | null | 2012-08-04 15:13:29.073 UTC | 25 | 2022-05-25 05:26:52.26 UTC | 2016-06-10 09:56:29.047 UTC | null | 1,331,399 | null | 585,874 | null | 1 | 87 | regex|terminal|rename | 105,839 | <p>You forgot a dot in front of the asterisk:</p>
<pre><code>rename -n 's/(\w+) - (\d{1})x(\d{2}).*$/S0$2E$3\.srt/' *.srt
</code></pre>
<p>On OpenSUSE, RedHat, Gentoo you have to use Perl version of <code>rename</code>. <a href="https://stackoverflow.com/a/32862278/1392034">This answer</a> shows how to obtain it. On Arch, the package is called <code>perl-rename</code>.</p> |
3,598,785 | Where to put Global variables in Rails 3 | <p>I used to put Global variables in environment.rb with my Rails 2.3.8 application such as:</p>
<pre><code>MAX_ALLOWD_ITEMS = 6
</code></pre>
<p>It doesn't seem to work in Rails 3. I tried putting it in application.rb and that didn't help.</p>
<p>What do you suggest?</p> | 3,600,860 | 5 | 1 | null | 2010-08-30 08:04:06.92 UTC | 11 | 2014-07-15 09:52:53.097 UTC | null | null | null | null | 99,694 | null | 1 | 25 | ruby-on-rails|ruby-on-rails-3|global-variables | 38,660 | <p>If you have already tried restarting your server as Ryan suggested, try putting it in your <code>application.rb</code> like this:</p>
<pre><code>module MyAppName
class Application < Rails::Application
YOUR_GLOBAL_VAR = "test"
end
end
</code></pre>
<p>Then you can call it with the namespace in your controllers, views or wherever..</p>
<pre><code>MyAppName::Application::YOUR_GLOBAL_VAR
</code></pre>
<p>Another alternative would be using something like <a href="http://github.com/binarylogic/settingslogic" rel="noreferrer">settingslogic</a>. With settingslogic, you just create a yml config file and a model (Settings.rb) that points to the config file. Then you can access these settings anywhere in your rails app with:</p>
<pre><code>Settings.my_setting
</code></pre> |
3,440,363 | Perl: Use s/ (replace) and return new string | <p>In Perl, the operator <code>s/</code> is used to replace parts of a string. Now <code>s/</code> will alter its parameter (the string) in place. I would however like to replace parts of a string befor printing it, as in</p>
<pre><code>print "bla: ", replace("a","b",$myvar),"\n";
</code></pre>
<p>Is there such <code>replace</code> function in Perl, or some other way to do it? <code>s/</code> will not work directly in this case, and I'd like to avoid using a helper variable. Is there some way to do this in-line?</p> | 3,440,474 | 5 | 0 | null | 2010-08-09 13:17:50.68 UTC | 4 | 2020-03-23 16:17:22.81 UTC | null | null | null | null | 43,681 | null | 1 | 37 | regex|perl|replace | 140,559 | <pre><code>require 5.013002; # or better: use Syntax::Construct qw(/r);
print "bla: ", $myvar =~ s/a/b/r, "\n";
</code></pre>
<p>See <a href="https://perldoc.pl/5.14.0/perl5132delta#Non-destructive-substitution" rel="noreferrer">perl5132delta</a>:</p>
<blockquote>
<p>The substitution operator now supports a <code>/r</code> option that copies the input variable, carries out the substitution on the copy and returns the result. The original remains unmodified.</p>
</blockquote>
<pre><code>my $old = 'cat';
my $new = $old =~ s/cat/dog/r;
# $old is 'cat' and $new is 'dog'
</code></pre> |
3,326,641 | OpenGL without X.org in linux | <p>I'd like to open an OpenGL context without X in Linux. Is there any way at all to do it?</p>
<p>I know it's possible for integrated Intel graphics card hardware, though most people have Nvidia cards in their system. I'd like to get a solution that works with Nvidia cards.</p>
<p>If there's no other way than through integrated Intel hardware, I guess it'd be okay to know how it's done with those.</p>
<p>X11 protocol itself is too large and complex. Mouse/Keyboard/Tablet input multiplexing it provides is too watered-down for modern programs. I think it's the worst roadblock that prevents Linux desktop from improving, which is why I look for alternatives.</p> | 3,331,769 | 5 | 18 | null | 2010-07-24 19:53:48.98 UTC | 21 | 2019-09-30 23:05:35.707 UTC | 2019-09-08 01:08:48.39 UTC | null | 78,720 | null | 21,711 | null | 1 | 42 | linux|opengl|x11|nvidia | 29,366 | <p>Update (Sep. 17, 2017):</p>
<p>NVIDIA recently published an article <a href="https://devblogs.nvidia.com/parallelforall/linking-opengl-server-side-rendering/" rel="noreferrer">detailing how to use OpenGL on headless systems</a>, which is a very similar use case as the question describes.</p>
<p>In summary:</p>
<ul>
<li>Link to <code>libOpenGL.so</code> and <code>libEGL.so</code> instead of <code>libGL.so</code>. (Your linker options should therefore be <code>-lOpenGL -lEGL</code></li>
<li>Call <code>eglGetDisplay</code>, then <code>eglInitialize</code> to initialize EGL.</li>
<li>Call <code>eglChooseConfig</code> with the config attribute <code>EGL_SURFACE_TYPE</code> followed with <code>EGL_PBUFFER_BIT</code>.</li>
<li>Call <code>eglCreatePbufferSurface</code>, then <code>eglBindApi(EGL_OPENGL_API);</code>, then <code>eglCreateContext</code> and <code>eglMakeCurrent</code>.</li>
</ul>
<p>From that point on, do your OpenGL rendering as usual, and you can blit your pixel buffer surface wherever you like. <a href="https://devblogs.nvidia.com/parallelforall/egl-eye-opengl-visualization-without-x-server/" rel="noreferrer">This supplementary article from NVIDIA</a> includes a basic example and an example for multiple GPUs. The PBuffer surface can also be replaced with a window surface or pixmap surface, according to the application needs.</p>
<p>I regret not doing more research on this on my previous edit, but oh well. Better answers are better answers.</p>
<hr>
<p>Since my answer in 2010, there have been a number of major shakeups in the Linux graphics space. So, an updated answer:</p>
<p>Today, nouveau and the other DRI drivers have matured to the point where OpenGL software is stable and performs reasonably well in general. With the introduction of the EGL API in Mesa, it's now possible to write OpenGL and OpenGL ES applications on even Linux desktops.</p>
<p>You can write your application to target EGL, and it can be run without the presence of a window manager or even a compositor. To do so, you would call <code>eglGetDisplay</code>, <code>eglInitialize</code>, and ultimately <code>eglCreateContext</code> and <code>eglMakeCurrent</code>, instead of the usual glx calls to do the same.</p>
<p>I do not know the specific code path for working without a display server, but EGL accepts both X11 displays and Wayland displays, and I do know it is possible for EGL to operate without one. You can create GL ES 1.1, ES 2.0, ES 3.0 (if you have Mesa 9.1 or later), and OpenGL 3.1 (Mesa 9.0 or later) contexts. Mesa has not (as of Sep. 2013) yet implemented OpenGL 3.2 Core.</p>
<p>Notably, on the Raspberry Pi and on Android, EGL and GL ES 2.0 (1.1 on Android < 3.0) are supported by default. On the Raspberry Pi, I don't think Wayland yet works (as of Sep. 2013), but you do get EGL without a display server using the included binary drivers. Your EGL code should also be portable (with minimal modification) to iOS, if that interests you.</p>
<hr>
<p><strong>Below is the outdated, previously accepted post:</strong></p>
<blockquote>
<p>I'd like to open an OpenGL context without X in linux. Is there any way at all to do it?</p>
</blockquote>
<p>I believe Mesa provides a framebuffer target. If it provides any hardware acceleration at all, it will only be with hardware for which there are open source drivers that have been adapted to support such a use.</p>
<p>Gallium3D is also immature, and support for this isn't even on the roadmap, as far as I know.</p>
<blockquote>
<p>I'd like to get a solution that works with nvidia cards.</p>
</blockquote>
<p>There isn't one. Period.</p>
<p>NVIDIA only provides an X driver, and the Nouveau project is still immature, and doesn't support the kind of use that you're looking for, as they are currently focused only on the X11 driver.</p> |
3,991,478 | Building a 32-bit float out of its 4 composite bytes | <p>I'm trying to build a 32-bit float out of its 4 composite bytes. Is there a better (or more portable) way to do this than with the following method?</p>
<pre><code>#include <iostream>
typedef unsigned char uchar;
float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3)
{
float output;
*((uchar*)(&output) + 3) = b0;
*((uchar*)(&output) + 2) = b1;
*((uchar*)(&output) + 1) = b2;
*((uchar*)(&output) + 0) = b3;
return output;
}
int main()
{
std::cout << bytesToFloat(0x3e, 0xaa, 0xaa, 0xab) << std::endl; // 1.0 / 3.0
std::cout << bytesToFloat(0x7f, 0x7f, 0xff, 0xff) << std::endl; // 3.4028234 × 10^38 (max single precision)
return 0;
}
</code></pre> | 3,991,555 | 6 | 1 | null | 2010-10-21 20:09:27.783 UTC | 12 | 2020-07-04 02:23:32.9 UTC | 2018-08-03 02:20:45.113 UTC | null | 995,714 | null | 344,190 | null | 1 | 37 | c++|floating-point|endianness|portability|single-precision | 65,468 | <p>You could use a <code>memcpy</code> (<a href="http://www.ideone.com/BwGyc" rel="noreferrer">Result</a>)</p>
<pre><code>float f;
uchar b[] = {b3, b2, b1, b0};
memcpy(&f, &b, sizeof(f));
return f;
</code></pre>
<p>or a union* (<a href="http://www.ideone.com/ZGKEf" rel="noreferrer">Result</a>)</p>
<pre><code>union {
float f;
uchar b[4];
} u;
u.b[3] = b0;
u.b[2] = b1;
u.b[1] = b2;
u.b[0] = b3;
return u.f;
</code></pre>
<p>But this is no more portable than your code, since there is no guarantee that the platform is little-endian or the <code>float</code> is using IEEE binary32 or even <code>sizeof(float) == 4</code>. </p>
<p>(Note*: As explained by <a href="https://stackoverflow.com/questions/3991478/building-a-32bit-float-out-of-its-4-composite-bytes-c/3991612#3991612">@James</a>, it is technically not allowed in the standard (C++ §[class.union]/1) to access the union member <code>u.f</code>.)</p> |
3,803,349 | Is it possible to declare an array as constant | <p>We can define a constant like</p>
<pre><code>define("aconstant','avalue');
</code></pre>
<p>Can't we define array in this fashion like below ?</p>
<pre><code>define("months",array("January", "February", ---);
</code></pre> | 3,803,372 | 7 | 2 | null | 2010-09-27 11:28:18.847 UTC | 4 | 2015-10-23 02:50:33.137 UTC | 2014-09-26 10:56:39.637 UTC | null | 1,723,893 | null | 452,432 | null | 1 | 56 | php | 58,174 | <p><strong>UPDATE:</strong> this is possible in PHP 7 (<a href="http://php.net/manual/en/function.define.php" rel="noreferrer">reference</a>)</p>
<pre><code>// Works as of PHP 7
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // outputs "cat"
</code></pre>
<hr>
<p><strong>ORIGINAL ANSWER</strong></p>
<p>From php.net...</p>
<blockquote>
<p>The value of the constant; only <strong>scalar and null values are
allowed</strong>. Scalar values are integer, float, string or boolean values.
It is possible to define resource constants, however it is not
recommended and may cause unpredictable behavior.</p>
</blockquote>
<p><code>$months = array("January,"February",...)</code> will be just fine.</p> |
3,501,126 | How to draw a filled triangle in android canvas? | <p>So I'm drawing this triangle in android maps using the code below in my draw method:</p>
<pre><code>paint.setARGB(255, 153, 29, 29);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
Path path = new Path();
path.moveTo(point1_returned.x, point1_returned.y);
path.lineTo(point2_returned.x, point2_returned.y);
path.moveTo(point2_returned.x, point2_returned.y);
path.lineTo(point3_returned.x, point3_returned.y);
path.moveTo(point3_returned.x, point3_returned.y);
path.lineTo(point1_returned.x, point1_returned.y);
path.close();
canvas.drawPath(path, paint);
</code></pre>
<p>The pointX_returned are the coordinates which I'm getting from the fields. They are basically latitudes and longitudes.
The result is a nice triangle but the insider is empty and therefore I can see the map. Is there a way to fill it up somehow? </p> | 3,501,210 | 8 | 2 | null | 2010-08-17 09:37:35.363 UTC | 17 | 2017-07-14 12:45:16.95 UTC | 2013-07-18 10:42:44.363 UTC | null | 103,081 | null | 359,656 | null | 1 | 94 | java|android|google-maps|android-canvas | 107,259 | <p>You probably need to do something like :</p>
<pre><code>Paint red = new Paint();
red.setColor(android.graphics.Color.RED);
red.setStyle(Paint.Style.FILL);
</code></pre>
<p>And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.</p>
<p>Tell me if it works please !</p> |
3,869,954 | What's the actual use of 'fail' in JUnit test case? | <p>What's the actual use of 'fail' in JUnit test case?</p> | 3,869,986 | 8 | 0 | null | 2010-10-06 06:21:59.783 UTC | 18 | 2020-08-10 17:28:40.063 UTC | 2013-03-12 10:31:50.77 UTC | null | 568,664 | null | 261,707 | null | 1 | 142 | java|unit-testing|junit|junit4 | 184,735 | <p>Some cases where I have found it useful:</p>
<ul>
<li>mark a test that is incomplete, so it fails and warns you until you can finish it</li>
<li>making sure an exception is thrown:</li>
</ul>
<blockquote>
<pre><code>try{
// do stuff...
fail("Exception not thrown");
}catch(Exception e){
assertTrue(e.hasSomeFlag());
}
</code></pre>
</blockquote>
<p>Note:</p>
<p>Since JUnit4, there is a more elegant way to test that an exception is being thrown:
Use the annotation <code>@Test(expected=IndexOutOfBoundsException.class)</code></p>
<p>However, this won't work if you also want to inspect the exception, then you still need <code>fail()</code>.</p> |
3,457,136 | ASP.NET CheckBox does not fire CheckedChanged event when unchecking | <p>I have a CheckBox on an ASP.NET Content Form like so:</p>
<pre><code><asp:CheckBox runat="server" ID="chkTest" AutoPostBack="true" OnCheckedChanged="chkTest_CheckedChanged" />
</code></pre>
<p>In my code behind I have the following method:</p>
<pre><code>protected void chkTest_CheckedChanged(object sender, EventArgs e)
{
}
</code></pre>
<p>When I load the page in the browser and click the CheckBox it becomes checked, the page posts back, and I can see <code>chkTest_CheckedChanged</code> being called.</p>
<p>When I then click the CheckBox again it becomes unchecked, the page posts back, however <code>chkTest_CheckedChanged</code> is not called.</p>
<p>The process is repeatable, so once the CheckBox is unchecked, checking it will fire the event.</p>
<p>I have View State disabled in the Web.Config, enabling View State causes this issue to disappear. What can I do to have reliable event firing while the View State remains disabled?</p>
<p><strong>Update:</strong>
If I set <code>Checked="true"</code> on the server tag the situation becomes reversed with the event firing when un-checking the CheckBox, but not the other way around.</p>
<p><strong>Update 2:</strong>
I've overridden <code>OnLoadComplete</code> in my page and from within there I can confirm that <code>Request.Form["__EVENTTARGET"]</code> is set correctly to the ID of my CheckBox.</p> | 7,004,909 | 10 | 3 | null | 2010-08-11 09:46:41.1 UTC | 9 | 2021-08-10 12:02:37.61 UTC | 2010-08-11 16:04:31.857 UTC | null | 96,970 | null | 96,970 | null | 1 | 31 | asp.net|viewstate | 74,851 | <p>Implementing a custom CheckBox that stores the <code>Checked</code> property in <code>ControlState</code> rather than <code>ViewState</code> will probably solve that problem, even if the check box has <code>AutoPostBack=false</code></p>
<p>Unlike ViewState, ControlState cannot be disabled and can be used to store data that is essential to the control's behavior.</p>
<p>I don't have a visual studio environnement right now to test, but that should looks like this:</p>
<pre><code>public class MyCheckBox : CheckBox
{
private bool _checked;
public override bool Checked { get { return _checked; } set { _checked = value; } }
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//You must tell the page that you use ControlState.
Page.RegisterRequiresControlState(this);
}
protected override object SaveControlState()
{
//You save the base's control state, and add your property.
object obj = base.SaveControlState();
return new Pair (obj, _checked);
}
protected override void LoadControlState(object state)
{
if (state != null)
{
//Take the property back.
Pair p = state as Pair;
if (p != null)
{
base.LoadControlState(p.First);
_checked = (bool)p.Second;
}
else
{
base.LoadControlState(state);
}
}
}
}
</code></pre>
<p>more info <a href="http://msdn.microsoft.com/en-us/library/1whwt1k7.aspx#Y342" rel="noreferrer">here</a>.</p> |
3,692,363 | Android AVD not showing anything. only "ANDROID" in the middle of the screen | <p>I am an Android Newbie! please help.</p>
<p>I have been following googles introduction tutorial and managed to install everything with no problems. but whenever i try to run the HelloAndroid example the avd launches but doesnt show anything.</p>
<p>cone somebody help please?</p> | 3,693,851 | 10 | 1 | null | 2010-09-11 19:34:37.08 UTC | 3 | 2016-03-22 15:55:31.677 UTC | 2013-09-08 19:03:58.083 UTC | null | 2,256,325 | null | 445,245 | null | 1 | 37 | android|eclipse|avd | 52,509 | <p>After you create an AVD it really does take a long time to initialize. On my less than year old Core2Duo 2.8 GHz running Win7x64 and 4Gb of RAM, initializing a 2.2 version took at least 5 to 10 minutes (if not longer). Once it starts initializing you can watch the logcat in the DDMS panel of eclipse and watch it unpack and install all of the apps in the emulator.</p> |
3,407,256 | Height of status bar in Android | <p>What's the height of the status bar in Android? Is it always the same?</p>
<p>From my measurements it seems that it's 25dp, but I'm not sure if it has the same height on all platforms.</p>
<p>(I want to know this to properly implement a fade transition from an activity that doesn't have status bar to one that does)</p> | 3,410,200 | 23 | 2 | null | 2010-08-04 15:44:16.38 UTC | 115 | 2021-02-11 14:13:57.53 UTC | 2010-08-06 12:08:41.13 UTC | null | 143,378 | null | 143,378 | null | 1 | 371 | android|statusbar | 418,228 | <p>this question was answered before...
<a href="https://stackoverflow.com/questions/3355367/height-of-statusbar/3356263#3356263">Height of statusbar?</a></p>
<p><strong>Update</strong>::</p>
<h3>Current method:</h3>
<p>ok, the height of the status bar depends on the screen size, for example in a device
with 240 X 320 screen size the status bar height is 20px, for a device with 320 X 480 screen size the status bar height is 25px, for a device with 480 x 800 the status bar height must be 38px</p>
<p>so i recommend to use this script to get the status bar height</p>
<pre><code>Rect rectangle = new Rect();
Window window = getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
int statusBarHeight = rectangle.top;
int contentViewTop =
window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight= contentViewTop - statusBarHeight;
Log.i("*** Elenasys :: ", "StatusBar Height= " + statusBarHeight + " , TitleBar Height = " + titleBarHeight);
</code></pre>
<h3>(old Method) to get the Height of the status bar on the <code>onCreate()</code> method of your Activity, use this method:</h3>
<pre><code>public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
</code></pre> |
7,759,385 | How can you disable the iOS Notification Center within your App? | <p>If you have a full screen iOS app and you want to prevent the notification center from being pulled down, can you and how? </p>
<p>Also can you block notification alerts or banners from displaying while your app is loading? (I think this is a no way for sure but wanted to ask just in case.)</p> | 7,761,716 | 4 | 1 | null | 2011-10-13 19:25:29.577 UTC | 8 | 2019-03-29 15:52:40.57 UTC | null | null | null | null | 196,020 | null | 1 | 26 | objective-c|notifications|ios5 | 30,336 | <p>It has been my experience that fullscreen apps (<code>statusBarHidden = YES</code>) have a slightly different notification center behavior by default: Swiping down over the area previously occupied by the status bar will only show a little tab. Only swiping the tab will then show the notification center. This has been enough to prevent accidental activation for me so far.</p>
<p>Currently, there is no public API for manipulating the behavior of the notification center. I am of the opinion that it's not likely that an app will <em>ever</em> be able to block a notification's appearance, and only slightly less unlikely that an app would be able to prevent the notification center from appearing. iOS is all about a consistent user experience experience at the price of developer freedom. I could see being frustrated by this kind of functionality if I were an unexpecting user.</p>
<p>All that said, there is always the dark-side of undocumented APIs. I would not be surprised if you could pull off some cleverness using those on a jailbroken device, but that's not my cup-o'-tea.</p> |
7,907,734 | String to CLLocation latitude and Longitude | <p>I have two strings representing latitude and longitude like: "-56.6462520", and i want to assign then to a CLLocation object to compare to my current location.I tried the following code but i get errors only:</p>
<pre><code>CLLocation * LocationAtual = [[CLLocation alloc]init];
LocationAtual.coordinate.latitude = @"-56.6462520";
LocationAtual.coordinate.longitude = @"-36.6462520";
</code></pre>
<p>and then compare the object with my actual location latitude and longitude. Any suggestions?</p> | 7,907,753 | 5 | 1 | null | 2011-10-26 19:21:17.353 UTC | 8 | 2016-02-01 19:26:11.723 UTC | 2016-01-08 11:01:08.783 UTC | null | 3,840,428 | null | 927,838 | null | 1 | 20 | iphone|objective-c|string|cllocation | 51,695 | <p>I think you need to:</p>
<pre><code>LocationAtual.coordinate.latitude = [@"-56.6462520" floatValue];
LocationAtual.coordinate.longitude = [@"-36.6462520" floatValue];
</code></pre> |
8,332,362 | SCRIPT5009: 'JSON' is undefined | <p>I get the following error in IE 9 <code>SCRIPT5009: 'JSON' is undefined</code> only when in compatability mode. the line causing this error is </p>
<pre><code>JSON.stringify(togObj.Answers)
</code></pre>
<p>The error does not occur in ie (non-compatability mode), Chrome or Firefox.
Any idea what's going on here?</p> | 8,332,456 | 7 | 1 | null | 2011-11-30 20:15:10.25 UTC | 6 | 2014-02-04 07:04:07.2 UTC | null | null | null | null | 545,192 | null | 1 | 36 | javascript|json|internet-explorer | 68,623 | <p>See here for a blog post explaining the situation: <a href="http://www.devcurry.com/2010/12/resolve-json-is-undefined-error-in.html" rel="noreferrer">Resolve JSON is Undefined Error in Internet Explorer</a></p>
<p>Include the <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="noreferrer">JSON library</a> in your page and you should be good to go.</p> |
8,136,652 | Query Mongodb on month, day, year... of a datetime | <p>I'm using mongodb and I store datetime in my database in this way</p>
<p>for a date "17-11-2011 18:00" I store:</p>
<pre><code>date = datetime.datetime(2011, 11, 17, 18, 0)
db.mydatabase.mycollection.insert({"date" : date})
</code></pre>
<p>I would like to do a request like that</p>
<pre><code>month = 11
db.mydatabase.mycollection.find({"date.month" : month})
</code></pre>
<p>or</p>
<pre><code>day = 17
db.mydatabase.mycollection.find({"date.day" : day})
</code></pre>
<p>anyone knows how to do this query?</p> | 8,136,834 | 7 | 2 | null | 2011-11-15 12:55:52.06 UTC | 9 | 2020-05-09 14:12:11.187 UTC | 2017-07-02 05:37:44.187 UTC | null | 2,313,887 | null | 668,218 | null | 1 | 53 | python|mongodb|datetime|mongodb-query|pymongo | 123,905 | <p>Dates are stored in their timestamp format. If you want everything that belongs to a specific month, query for the start and the end of the month.</p>
<pre><code>var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);
db.posts.find({created_on: {$gte: start, $lt: end}});
//taken from http://cookbook.mongodb.org/patterns/date_range/
</code></pre> |
8,228,980 | Reset CSS display property to default value | <p>Is it possible to override the display property with its default value? For example if I have set it to none in one style, and I want to override it in a different with its default.</p>
<p>Or is the only way to find out what the default of that element is and then set it to that? Would like to not have to know if the element is usually block, inline or whichever...</p> | 8,229,026 | 8 | 3 | null | 2011-11-22 15:06:17.46 UTC | 36 | 2022-05-02 21:08:45.27 UTC | null | null | null | null | 39,321 | null | 1 | 191 | css|default | 177,466 | <p>A browser's default styles are defined in its user agent stylesheet, the sources of which you can find <a href="https://stackoverflow.com/questions/6867254/browsers-default-css-for-html-elements">here</a>. Unfortunately, the <a href="https://www.w3.org/TR/css-cascade-3" rel="noreferrer">Cascading and Inheritance level 3 spec</a> does not appear to propose a way to reset a style property to its browser default. However there are plans to reintroduce a keyword for this in <a href="https://www.w3.org/TR/css-cascade-4/#valdef-all-revert" rel="noreferrer">Cascading and Inheritance level 4</a> — the working group simply hasn't settled on a name for this keyword yet (the link currently says <code>revert</code>, but it is not final). Information about browser support for <code>revert</code> can be found on <a href="https://caniuse.com/#search=revert" rel="noreferrer">caniuse.com</a>.</p>
<p>While the level 3 spec does introduce an <a href="https://www.w3.org/TR/css-cascade-3/#initial" rel="noreferrer"><code>initial</code> keyword</a>, setting a property to its <strong>initial value</strong> resets it to its default value <strong>as defined by CSS</strong>, <em>not as defined by the browser</em>. The initial value of <code>display</code> is <code>inline</code>; this is specified <a href="https://www.w3.org/TR/CSS21/visuren.html#display-prop" rel="noreferrer">here</a>. The <code>initial</code> keyword refers to that value, not the browser default. The spec itself makes this note under the <a href="https://www.w3.org/TR/css-cascade-3/#all-shorthand" rel="noreferrer"><code>all</code> property</a>:</p>
<blockquote>
<p>For example, if an author specifies <code>all: initial</code> on an element it will block all inheritance and reset all properties, as if no rules appeared in the author, user, or user-agent levels of the cascade.</p>
<p>This can be useful for the root element of a "widget" included in a page, which does not wish to inherit the styles of the outer page. Note, however, that any "default" style applied to that element (such as, e.g. <code>display: block</code> from the UA style sheet on block elements such as <code><div></code>) will also be blown away.</p>
</blockquote>
<p>So I guess the only way right now using pure CSS is to look up the browser default value and set it manually to that:</p>
<pre><code>div.foo { display: inline-block; }
div.foo.bar { display: block; }
</code></pre>
<p>(An alternative to the above would be <code>div.foo:not(.bar) { display: inline-block; }</code>, but that involves modifying the original selector rather than an override.)</p> |
4,410,206 | Change order of blocks via local.xml file | <p>Is it possible to change the order of already existing blocks via the local.xml file?
I know you can change the order of a block with the after or before attribute, but how can one change those attributes of existing blocks.</p>
<p>For example, if I want to place the layered navigation block underneath the newsletter subscription block in the left column, how would I do that?</p> | 4,411,538 | 3 | 0 | null | 2010-12-10 15:11:13.923 UTC | 26 | 2019-02-02 14:55:51.963 UTC | 2019-02-02 14:55:51.963 UTC | null | 10,607,772 | null | 145,829 | null | 1 | 22 | magento|block | 30,553 | <p>You need to perform a small trick, remove child block and add it in new position:</p>
<pre><code><reference name="parent.block.name">
<action method="unsetChild">
<alias>child_block_alias</alias>
</action>
<action method="insert">
<blockName>child.block.name</blockName>
<siblingName>name_of_block</siblingName>
<after>1</after>
<alias>child_block_alias</alias>
</action>
</reference>
</code></pre>
<p>This Layout XML instruction does what you want. Look at this short reference of parameters for <code>insert</code> method:</p>
<ul>
<li><code>blockName</code> is your block unique name across the layout, <code>product.view</code> for example</li>
<li><code>siblingName</code> is an block unique name, that is already exists in insertion target block, used for positioning of your block. Leave empty to display it at the top or at the bottom.</li>
<li><code>after</code> is a boolean identifier of block position. If equals to <code>1</code>, then the block will be added after <code>siblingName</code> or in the bottom of the children list if <code>siblingName</code> is empty</li>
<li><code>alias</code> is the alias of your block, if it is empty the name of block will be used.</li>
</ul>
<p>Some Examples:</p>
<p><strong>Move cart sidebar block after recently viewed products</strong></p>
<pre><code><reference name="right">
<action method="unsetChild">
<alias>cart_sidebar</alias>
</action>
<action method="insert">
<blockName>cart_sidebar</blockName>
<siblingName>right.reports.product.viewed</siblingName>
<after>1</after>
</action>
</reference>
</code></pre>
<p><strong>Move cart sidebar block before recently viewed products</strong></p>
<pre><code><reference name="right">
<action method="unsetChild">
<alias>cart_sidebar</alias>
</action>
<action method="insert">
<blockName>cart_sidebar</blockName>
<siblingName>right.reports.product.viewed</siblingName>
<after>0</after>
</action>
</reference>
</code></pre>
<p><strong>Move cart sidebar block at the end of the right block</strong></p>
<pre><code><reference name="right">
<action method="unsetChild">
<alias>cart_sidebar</alias>
</action>
<action method="insert">
<blockName>cart_sidebar</blockName>
<siblingName></siblingName>
<after>1</after>
</action>
</reference>
</code></pre>
<p><strong>Move cart sidebar block at the top of the left block</strong></p>
<pre><code><reference name="right">
<action method="unsetChild">
<alias>cart_sidebar</alias>
</action>
</reference>
<reference name="left">
<action method="insert">
<blockName>cart_sidebar</blockName>
</action>
</reference>
</code></pre>
<p>Enjoy working with Magento!</p> |
4,265,161 | how to convert hexadecimal to RGB | <p>I want to make a conversion from hexadecimal to RGB, but the hexadecimal deal with a string like #FFFFFF. How can I do that?</p> | 4,266,390 | 4 | 5 | null | 2010-11-24 09:22:02.72 UTC | 16 | 2021-04-20 18:34:46.7 UTC | 2012-12-04 18:45:34.733 UTC | null | 106,435 | null | 515,986 | null | 1 | 29 | objective-c|ios|cocoa-touch|hex|rgb | 22,382 | <p>I've just expanded my UIColor Category for you.<br>
use it like <code>UIColor *green = [UIColor colorWithHexString:@"#00FF00"];</code></p>
<pre><code>//
// UIColor_Categories.h
//
// Created by Matthias Bauch on 24.11.10.
// Copyright 2010 Matthias Bauch. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface UIColor(MBCategory)
+ (UIColor *)colorWithHex:(UInt32)col;
+ (UIColor *)colorWithHexString:(NSString *)str;
@end
//
// UIColor_Categories.m
//
// Created by Matthias Bauch on 24.11.10.
// Copyright 2010 Matthias Bauch. All rights reserved.
//
#import "UIColor_Categories.h"
@implementation UIColor(MBCategory)
// takes @"#123456"
+ (UIColor *)colorWithHexString:(NSString *)str {
const char *cStr = [str cStringUsingEncoding:NSASCIIStringEncoding];
long x = strtol(cStr+1, NULL, 16);
return [UIColor colorWithHex:x];
}
// takes 0x123456
+ (UIColor *)colorWithHex:(UInt32)col {
unsigned char r, g, b;
b = col & 0xFF;
g = (col >> 8) & 0xFF;
r = (col >> 16) & 0xFF;
return [UIColor colorWithRed:(float)r/255.0f green:(float)g/255.0f blue:(float)b/255.0f alpha:1];
}
@end
</code></pre> |
4,454,058 | No ItemChecked event in a CheckedListBox? | <p>The ListView control has an <strong>ItemCheck</strong> event which is fired <em>before</em> the item changes, and an <strong>ItemChecked</strong> event that is fired <em>after</em> the item changes. See <a href="https://stackoverflow.com/questions/912798/listview-itemcheck-versus-listview-itemchecked-in-net">this SO question</a> for more detail.</p>
<p>The CheckedListBox control only has the ItemCheck event.</p>
<p>What is the best way to do something like this with a CheckedListBox?</p>
<pre><code>private void checkedListBox_ItemChecked(object sender ItemCheckedEventArgs e)
{
okButton.Enabled = (checkedListBox.CheckedItems.Count > 0);
}
</code></pre>
<p>Supplemental question:
Why is there no CheckedListBox.ItemChecked event?</p> | 4,454,594 | 4 | 1 | null | 2010-12-15 19:36:40.767 UTC | 4 | 2015-09-02 14:14:40.137 UTC | 2017-05-23 12:03:06.937 UTC | user166390 | -1 | null | 542,911 | null | 1 | 30 | c#|winforms | 12,837 | <p>A nice trick to deal with events that you cannot process when they are raised is to delay the processing. Which you can do with the Control.BeginInvoke() method, it runs as soon as all events are dispatched, side-effects are complete and the UI thread goes idle again. Often helpful for TreeView as well, another cranky control.</p>
<pre><code> private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
this.BeginInvoke((MethodInvoker)delegate {
okButton.Enabled = checkedListBox1.CheckedItems.Count > 0;
});
}
</code></pre>
<p>Just in case: this has nothing to do with threading and the trick is quite cheap.</p>
<p>Why no ItemChecked event? Not really sure. CheckedListBox just isn't a very good control. Definitely not done by one of the gurus in the original Winforms team.</p> |
4,643,105 | How to unittest a class using RestTemplate offline? | <p>I have a class which has direct dependency on the RestTemplate. I wish I have a JUnit test of it, offline.</p>
<p>How could I mock a RestTemplate in my unittest? </p> | 4,645,973 | 4 | 1 | null | 2011-01-10 01:51:51.177 UTC | 5 | 2013-09-12 09:50:00.73 UTC | 2011-01-10 08:41:05.507 UTC | null | 342,852 | null | 40,214 | null | 1 | 30 | java|unit-testing|spring|junit|resttemplate | 25,816 | <p>I suggest refactoring your client code to <em>remove</em> the direct dependency on <code>RestTemplate</code>, and replace it with references to <code>RestOperations</code>, which is the interface implemented by <code>RestTemplate</code>. and the one you should be coding to.</p>
<p>You can then inject a stub or mock of <code>RestOperations</code> into your code for unit testing, and inject a <code>RestTemplate</code> when using it for real.</p> |
4,668,640 | How can I execute a command stored in a variable? | <p>What is the correct way to call some command stored in variable?</p>
<p>Are there any differences between 1 and 2?</p>
<pre><code>#!/bin/sh
cmd="ls -la $APPROOTDIR | grep exception"
#1
$cmd
#2
eval "$cmd"
</code></pre> | 4,668,800 | 4 | 1 | null | 2011-01-12 12:13:08.767 UTC | 32 | 2022-01-06 08:52:08.873 UTC | 2021-12-03 03:21:49.053 UTC | null | 63,550 | null | 167,739 | null | 1 | 90 | shell|unix|parameter-expansion | 161,935 | <p>Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the <a href="https://linux.die.net/man/1/bash" rel="noreferrer">Bash man page</a>):</p>
<ul>
<li>initial word splitting</li>
<li>brace expansion</li>
<li>tilde expansion</li>
<li><strong>parameter, variable and arithmetic expansion</strong></li>
<li>command substitution</li>
<li>secondary word splitting</li>
<li>path expansion (aka globbing)</li>
<li><strong>quote removal</strong></li>
</ul>
<p>Using <code>$cmd</code> directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.</p>
<p>Using <code>eval "$cmd"</code> does nothing until the quote removal phase, where <code>$cmd</code> is returned as is, and passed as a parameter to <code>eval</code>, whose function is to run the whole chain again before executing.</p>
<p>So basically, they're the same in most cases and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:</p>
<pre><code>$ cmd="echo foo{bar,baz}"
$ $cmd
foo{bar,baz}
$ eval "$cmd"
foobar foobaz
</code></pre> |
4,763,757 | Regular Expressions in DB2 SQL | <p>(Other than using a UDF) Any REGEXP-In-SQL support for DB2 9.7 ?</p> | 4,763,881 | 5 | 1 | null | 2011-01-21 21:00:54.76 UTC | 3 | 2016-07-22 09:27:37.633 UTC | 2011-01-21 21:01:20.977 UTC | null | 135,152 | null | 171,428 | null | 1 | 12 | sql|regex|db2 | 47,219 | <p>There is no built-in support for regular expressions in DB2 9.7.</p>
<p>The only way is using UDFs or table functions as described in the article 'OMG Ponies' added in the comment.</p>
<p>@dan1111: I do not appreciate my post being edited, especially if people can't read the question correctly. The OP asked <em>Any REGEXP-In-<strong>SQL</strong> support for DB2 9.7</em> </p>
<p>SQL is not XQuery !!!</p>
<p>Sorry, don't delete the text of my 100% correct answer. You can add a comment or write your own answer.</p> |
4,459,891 | How to play wmv files in html5 video player | <p>Is there any way to play .wmv files using html5 video player?</p> | 4,459,949 | 6 | 7 | null | 2010-12-16 10:47:00.843 UTC | null | 2020-05-30 12:42:04.383 UTC | 2016-08-30 17:07:39.84 UTC | null | 881,229 | null | 201,387 | null | 1 | 23 | html|html5-video | 85,960 | <p>There is no way. No browser (currently, if ever) supports playing wmv files. You will have to convert it into a format that browsers know how to play.</p> |
4,138,202 | Using isdigit for floats? | <pre><code>a = raw_input('How much is 1 share in that company? ')
while not a.isdigit():
print("You need to write a number!\n")
a = raw_input('How much is 1 share in that company? ')
</code></pre>
<p>This only works if the user enters an <code>integer</code>, but I want it to work even if they enter a <code>float</code>, but not when they enter a <code>string</code>. </p>
<p>So the user should be able to enter both <code>9</code> and <code>9.2</code>, but not <code>abc</code>. </p>
<p>How should I do it?</p> | 4,138,301 | 8 | 0 | null | 2010-11-09 20:23:29.98 UTC | 7 | 2020-08-19 08:14:43.407 UTC | 2016-12-20 20:59:01.083 UTC | null | 355,230 | null | 502,382 | null | 1 | 38 | python|parsing|user-input | 62,268 | <p>Use regular expressions.</p>
<pre><code>import re
p = re.compile('\d+(\.\d+)?')
a = raw_input('How much is 1 share in that company? ')
while p.match(a) == None:
print "You need to write a number!\n"
a = raw_input('How much is 1 share in that company? ')
</code></pre> |
4,830,253 | Where is the Keytool application? | <p>I need to use mapview control in android and I can't seem to understand how to run <code>keytool</code>.
Is it installed with eclipse? I can't seem to find a download link.</p>
<p>Thanks</p> | 4,830,283 | 9 | 0 | null | 2011-01-28 15:57:38.383 UTC | 12 | 2021-02-25 16:13:35.013 UTC | 2014-09-30 11:48:30.64 UTC | null | 739,253 | null | 62,898 | null | 1 | 161 | java|eclipse|android-mapview|keytool | 320,737 | <p><a href="http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/keytool.html" rel="noreferrer"><code>keytool</code></a> is part of the standard java distribution.</p>
<p>In a windows 64-bit machine, you would normally find the jdk at </p>
<p><code>C:\Program Files\Java\jdk1.8.0_121\bin</code></p>
<p>It is used for managing keys and certificates you can sign things with, in your case, probably a jar file.</p>
<p>If you provide more details of what you need to do, we could probably give you a more specific answer.</p> |
4,165,195 | MySQL query to get column names? | <p>I'd like to get all of a mysql table's col names into an array in php?</p>
<p>Is there a query for this? </p> | 4,165,253 | 22 | 0 | null | 2010-11-12 13:42:23.747 UTC | 117 | 2021-11-08 13:27:54.33 UTC | null | null | null | null | 289,666 | null | 1 | 339 | php|mysql | 658,953 | <p>The best way is to use the <a href="http://dev.mysql.com/doc/refman/5.0/en/information-schema.html">INFORMATION_SCHEMA</a> metadata virtual database. Specifically the <a href="http://dev.mysql.com/doc/refman/5.0/en/columns-table.html">INFORMATION_SCHEMA.COLUMNS</a> table...</p>
<pre><code>SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename';
</code></pre>
<p>It's VERY powerful, and can give you TONS of information without need to parse text (Such as column type, whether the column is nullable, max column size, character set, etc)...</p>
<p>Oh, and it's standard SQL (Whereas <code>SHOW ...</code> is a MySQL specific extension)...</p>
<p>For more information about the difference between <code>SHOW...</code> and using the <code>INFORMATION_SCHEMA</code> tables, check out the MySQL <a href="http://dev.mysql.com/doc/refman/5.1/en/information-schema.html">Documentation on <code>INFORMATION_SCHEMA</code> in general</a>...</p> |
14,532,164 | Hash value for directed acyclic graph | <p>How do I transform a directed acyclic graph into a hash value such that any two isomorphic graphs hash to the same value? It is acceptable, but undesirable for two isomorphic graphs to hash to different values, which is what I have done in the code below. We can assume that the number of vertices in the graph is at most 11.</p>
<p>I am particularly interested in Python code.</p>
<p>Here is what I did. If <code>self.lt</code> is a mapping from node to descendants (not children!), then I relabel the nodes according to a modified topological sort (that prefers to order elements with more descendants first if it can). Then, I hash the sorted dictionary. Some isomorphic graphs will hash to different values, especially as the number of nodes grows.</p>
<p>I have included all the code to motivate my use case. I am calculating the number of comparisons required to find the median of 7 numbers. The more that isomorphic graphs hash to the same value the less work that has to be redone. I considered putting larger connected components first, but didn't see how to do that quickly.</p>
<pre><code>from tools.decorator import memoized # A standard memoization decorator
class Graph:
def __init__(self, n):
self.lt = {i: set() for i in range(n)}
def compared(self, i, j):
return j in self.lt[i] or i in self.lt[j]
def withedge(self, i, j):
retval = Graph(len(self.lt))
implied_lt = self.lt[j] | set([j])
for (s, lt_s), (k, lt_k) in zip(self.lt.items(),
retval.lt.items()):
lt_k |= lt_s
if i in lt_k or k == i:
lt_k |= implied_lt
return retval.toposort()
def toposort(self):
mapping = {}
while len(mapping) < len(self.lt):
for i, lt_i in self.lt.items():
if i in mapping:
continue
if any(i in lt_j or len(lt_i) < len(lt_j)
for j, lt_j in self.lt.items()
if j not in mapping):
continue
mapping[i] = len(mapping)
retval = Graph(0)
for i, lt_i in self.lt.items():
retval.lt[mapping[i]] = {mapping[j]
for j in lt_i}
return retval
def median_known(self):
n = len(self.lt)
for i, lt_i in self.lt.items():
if len(lt_i) != n // 2:
continue
if sum(1
for j, lt_j in self.lt.items()
if i in lt_j) == n // 2:
return True
return False
def __repr__(self):
return("[{}]".format(", ".join("{}: {{{}}}".format(
i,
", ".join(str(x) for x in lt_i))
for i, lt_i in self.lt.items())))
def hashkey(self):
return tuple(sorted({k: tuple(sorted(v))
for k, v in self.lt.items()}.items()))
def __hash__(self):
return hash(self.hashkey())
def __eq__(self, other):
return self.hashkey() == other.hashkey()
@memoized
def mincomps(g):
print("Calculating:", g)
if g.median_known():
return 0
nodes = g.lt.keys()
return 1 + min(max(mincomps(g.withedge(i, j)),
mincomps(g.withedge(j, i)))
for i in nodes
for j in nodes
if j > i and not g.compared(i, j))
g = Graph(7)
print(mincomps(g))
</code></pre> | 14,574,330 | 10 | 18 | null | 2013-01-25 23:52:01.75 UTC | 9 | 2017-03-20 10:45:47.147 UTC | 2013-01-28 19:52:32.863 UTC | null | 99,989 | null | 99,989 | null | 1 | 25 | python|algorithm|hash|directed-acyclic-graphs | 4,087 | <p>To effectively test for graph isomorphism you will want to use <a href="http://cs.anu.edu.au/people/bdm/nauty/">nauty</a>. Specifically for Python there is the wrapper <a href="http://web.cs.dal.ca/~peter/software/">pynauty</a>, but I can't attest its quality (to compile it correctly I had to do some simple patching on its <code>setup.py</code>). If this wrapper is doing everything correctly, then it simplifies nauty a lot for the uses you are interested and it is only a matter of hashing <code>pynauty.certificate(somegraph)</code> -- which will be the same value for isomorphic graphs.</p>
<p>Some quick tests showed that <code>pynauty</code> is giving the same certificate for every graph (with same amount of vertices). But that is only because of a minor issue in the wrapper when converting the graph to nauty's format. After fixing this, it works for me (I also used the graphs at <a href="http://funkybee.narod.ru/graphs.htm">http://funkybee.narod.ru/graphs.htm</a> for comparison). Here is the short patch which also considers the modifications needed in <code>setup.py</code>:</p>
<pre><code>diff -ur pynauty-0.5-orig/setup.py pynauty-0.5/setup.py
--- pynauty-0.5-orig/setup.py 2011-06-18 20:53:17.000000000 -0300
+++ pynauty-0.5/setup.py 2013-01-28 22:09:07.000000000 -0200
@@ -31,7 +31,9 @@
ext_pynauty = Extension(
name = MODULE + '._pynauty',
- sources = [ pynauty_dir + '/' + 'pynauty.c', ],
+ sources = [ pynauty_dir + '/' + 'pynauty.c',
+ os.path.join(nauty_dir, 'schreier.c'),
+ os.path.join(nauty_dir, 'naurng.c')],
depends = [ pynauty_dir + '/' + 'pynauty.h', ],
extra_compile_args = [ '-O4' ],
extra_objects = [ nauty_dir + '/' + 'nauty.o',
diff -ur pynauty-0.5-orig/src/pynauty.c pynauty-0.5/src/pynauty.c
--- pynauty-0.5-orig/src/pynauty.c 2011-03-03 23:34:15.000000000 -0300
+++ pynauty-0.5/src/pynauty.c 2013-01-29 00:38:36.000000000 -0200
@@ -320,7 +320,7 @@
PyObject *adjlist;
PyObject *p;
- int i,j;
+ Py_ssize_t i, j;
int adjlist_length;
int x, y;
</code></pre> |
14,796,546 | InvalidCastException for Object of the same type - Custom Control Load | <p>I have a very wired error, one of my custom controls seems that is create two compiled files, and when I try to load it dynamically with <code>LoadControl()</code> is just fail because can not cast the one to the other - even if they are exactly the same. I write the message to see that all is the same, is only change the compiled dll.</p>
<pre><code>System.Web.HttpUnhandledException (0x80004005):
Exception of type 'System.Web.HttpUnhandledException' was thrown. --->
System.InvalidCastException:
[A]ASP.Modules_OneProduct_MedioumImage cannot be cast to
[B]ASP.Modules_OneProduct_MedioumImage.
Type A originates from 'App_Web_kg4bazz1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
in the context 'Default'
at location 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\80ed7513\10eb08d9\App_Web_kg4bazz1.dll'.
Type B originates from 'App_Web_oneproduct_mediumimage.ascx.d1003923.4xoxco7b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
in the context 'Default'
at location 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\80ed7513\10eb08d9\App_Web_oneproduct_mediumimage.ascx.d1003923.4xoxco7b.dll'.
</code></pre>
<h2>The code</h2>
<p>This is the code as it is right now after I have follow <a href="http://msdn.microsoft.com/en-us/library/c0az2h86(v=vs.100).aspx">exactly what is written on MSDN</a>: </p>
<pre><code>foreach (int OneProductID in TheProductIdArrays)
{
// here is the throw.
ASP.Modules_OneProduct_MedioumImage OneProduct =
(ASP.Modules_OneProduct_MedioumImage)LoadControl(@"~/mod/OneProduct_MediumImage.ascx");
// do some work with
//OneProduct
}
</code></pre>
<p>Previously I have Load the control without the <code>ASP.</code> but after this bug appears and looking for solution, I strictly follow what is on MSDN. The bug is still here no matter what I do.</p>
<p>I have also try both of this methods, each one alone, and together (again fail)</p>
<pre><code><%@ Register src="~/mod/OneProduct_MediumImage.ascx" tagname="OneProduct_MediumImage" tagprefix="uc1" %>
<%@ Reference Control="~/mod/OneProduct_MediumImage.ascx" %>
</code></pre>
<h2>Config</h2>
<p>My web.config, I have try with <code>maxBatchSize</code> 20, 100, 1000, also with <code>optimizeCompilations</code> true or false, but the bug is appears again.</p>
<pre><code><compilation debug="false" defaultLanguage="C#" batch="true"
maxBatchSize="800" batchTimeout="10800" optimizeCompilations="false"
targetFramework="4.0">
</code></pre>
<h2>Now some details about</h2>
<ul>
<li>The error is random, in some compile appears, in some other not.</li>
<li>The project is a big one, the pages are live with a lot of people in every minute that ask to see something, but also appears when there is no one inside.</li>
<li>Is run on 64bit dot.net 4, Intergrated</li>
<li>Run as web garden but also tested and one pool alone (and get the same issue)</li>
<li>The session is off on the full project.</li>
<li>The pages are run from 2007 but this issue is appears the last month, unfortunately I can not find where and how is started, or what is trigger it because I late some days to see it.</li>
<li>Appears only one one custom control loads, the one that have heavy call.</li>
<li>I have change 4 times the code making small changes, or big changes and still there.</li>
<li>I have try with <code>optimizeCompilations</code> true and false and the same issue.</li>
<li>I have try also by stopping the web, delete all temporary files, reopening, and there was again.</li>
<li>I have try to place a mutex on global.asax when the application starts to lock only one compile at the time, but this fails also.</li>
<li>From the moment that works, then all is good, but if not works is not auto corrected.</li>
<li>The code that I load this custom control is exist and called in more than one places on the code, on different pages.</li>
<li>Other custom controls, with similar load did not have any problems.</li>
<li>ViewState is disabled for this custom control.</li>
<li>I have also try relocate some code, change the full function call with micro optimizes, no again fail.</li>
<li><strike>Is work fine on development computer</strike>. I place <code>batch="true"</code> on web.config and the bug appears right away.</li>
<li>There are no other issues like that, like a bug that we can not fix no matter what. The system is run for days, the pool is NOT recycle at all, the memory is stable, and there is more free to use. The program is run for years now, but we change is almost every day with updates.</li>
<li>Under the same core code runs more than one sites (something like stackexchange) and all have the same random problem.</li>
<li>The AutoEventWireup is false</li>
<li>Its appears and on other custom control that I load the same way.</li>
</ul>
<p>What I do now as workaround when this bug appears: I just force the project to recompile with a small change, and the error go away, until the next update.</p>
<p>I have a bug that try to solve the last tree weeks with out find the reason. I have try almost anything I can thing of, but all fails, and the bug appears again. So I post here maybe some can help me out and find a way out of this.</p>
<p>Last word: This bug is crazy, the custom control is the same, I do anything on it I only load it dynamically and boom, the compiler is have it two different times for some reason that only he knows - randomly.</p>
<h2>Update 1</h2>
<p>I been able to reproduce the bug on the developer machine. There I discover that the two dll modules that contains this custom control have a different.</p>
<p>The one was a bundle of 4 custom controls together. The other module was the custom control alone.</p>
<h2>Workaround</h2>
<p>After tree weeks trying to fix this bug I end up that this bug is appears when the compiler make batch compile of a directory, and bundle many different custom controls, in the same dll. So when I try to load it alone is throw this exception.</p>
<p>So I move the problematic custom control in a different directory alone and seems that I avoid it for now.</p>
<h2>Update 2</h2>
<p>Appears again, even after I move some files to a different directory. Is random and can not find a clear connection with what is triggers its.</p>
<h2>Update 3</h2>
<p>Because we have spot that the main issue here is the batch compile (<code>batch="true"</code>) that compiles on the same dll many custom controls, one way to say to the compiler to NOT do that, is the <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.compilationsection.maxbatchgeneratedfilesize.aspx"><code>maxBatchGeneratedFileSize</code></a> parameter. I use it with a value of 100, and the issue appears again, now I have lower it to 40 and test it.</p>
<pre><code>maxBatchGeneratedFileSize="40"
</code></pre> | 15,253,750 | 5 | 6 | null | 2013-02-10 10:00:19.293 UTC | 7 | 2016-02-14 23:43:25.173 UTC | 2013-03-05 13:04:29.517 UTC | null | 159,270 | null | 159,270 | null | 1 | 28 | c#|asp.net|compiler-construction|user-controls|dynamic-compilation | 4,005 | <p>This can happen when you have batching turned on and have some form of circular references at the directory level.</p>
<p>Please see this <a href="https://stackoverflow.com/questions/14784369/error-cs0433-in-large-precompiled-asp-net-website-project">answer</a> to see exactly what I mean by 'circular references' in this context, as the meaning is quite subtle.</p>
<p>If you manage to break the cycle (e.g. by moving a user control elsewhere), you will not hit this issue.</p>
<h2>Update 1</h2>
<p>I would think that in theory, this can only be caused by a cycle, but sometimes they can be hard to detect.</p>
<p>I'll give you an alternative solution which I think will work and is very easy to try (even though it is a bit of a hack). In the user control(s) that is giving you problems, add the following attribute in the directive:</p>
<pre><code><%@ Control Language="C#" [...] CompilerOptions="/define:dummy1" %>
</code></pre>
<p>If you see this with some other controls, you can add the same thing but with dummy2, dummy3, etc...</p>
<p>This will have the effect of not batching this one user control, since it has different compilation needs from the others. Technically, you can add any piece of C# command line as the <code>CompilerOptions</code>, but a dummy <code>/define</code> is the simplest and most harmless.</p>
<p>But unlike turning off batching globally, the perf impact will be minimal, since only a very small subset of pages will not be batched.</p>
<p>BTW, it goes without saying that what you're seeing is a bug in ASP.NET, and that bug has been there for probably 10+ years! Maybe at some point it should get addressed :)</p> |
14,513,305 | How to write Unix shell scripts with options? | <p>I don't know whether it's possible, but I want to write shell scripts that act like regular executables with options. As a very simple example, consider a shell script foo.sh that is configured to be executable:</p>
<pre><code> ./foo.sh
./foo.sh -o
</code></pre>
<p>and the code <code>foo.sh</code> works like</p>
<pre><code> #!/bin/sh
if ## option -o is turned on
## do something
else
## do something different
endif
</code></pre>
<p>Is it possible and how to do that? Thanks.</p> | 14,513,413 | 4 | 0 | null | 2013-01-25 00:22:17.403 UTC | 8 | 2019-04-20 02:09:46.22 UTC | null | null | null | null | 1,944,784 | null | 1 | 29 | shell | 76,586 | <pre><code>$ cat stack.sh
#!/bin/sh
if [[ $1 = "-o" ]]; then
echo "Option -o turned on"
else
echo "You did not use option -o"
fi
$ bash stack.sh -o
Option -o turned on
$ bash stack.sh
You did not use option -o
</code></pre>
<p><strong>FYI:</strong></p>
<pre><code>$1 = First positional parameter
$2 = Second positional parameter
.. = ..
$n = n th positional parameter
</code></pre>
<p>For more neat/flexible options, read this other thread: <a href="https://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options">Using getopts to process long and short command line options</a></p> |
14,438,325 | Why is <form> being given NoValidate attribute? | <p>Having trouble getting jQuery Validate plugin to play nice.</p>
<p>Model</p>
<pre><code>public class FooVM
{
[Required]
public string Name { get; set; }
}
</code></pre>
<p>Layout</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="@Url.Content("~/scripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/scripts/jquery-migrate-1.0.0.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/scripts/bootstrap.min.js")" type="text/javascript"></script>
<link href="@Url.Content("~/content/bootstrap-responsive.min.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
<title>@ViewBag.Title</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="span12">
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">idoneit</a>
<ul class="nav">
<li class="menu-link">@Html.ActionLink("Home", "index", "bar")</li>
</ul>
</div>
</div>
</div>
<div class="span12 error-container">
</div>
<div class="span12 main-body">
@RenderBody()
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p>View</p>
<pre><code>model bootstrapvalidate.Models.FooVM
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("add", "bar", FormMethod.Post, new { @class = "form-horizontal" }))
{
<fieldset>
@Html.ValidationSummary()
<legend>Testing Bootstrap & Validate</legend>
<div class="control-group">
<label for="Name" class="control-label">Name</label>
<div class="controls">
@Html.TextBoxFor(x => x.Name)
</div>
<button type="submit" class="btn">Add!</button>
</div>
</fieldset>
}
</code></pre>
<p>When I submit, the error message is briefly shown and then the form posts back anyway.</p>
<p>One thing I have noticed which I have not seen before is that the markup contains the 'novalidate' attribute</p>
<pre><code><form action="/bar/add" class="form-horizontal" method="post" novalidate="novalidate">
</code></pre>
<p>From the bits I have read, this is HTML5 attribute that prevents validation. So yeah, this is what is causing it I assume.</p>
<p>Question is - why the bejesus is it being added to the form? I've not asked for it!</p>
<p>edit: did a bit of digging based on @rob 's answer, it seems jquery validate is throwing an exception, hence the postback.. </p>
<p><img src="https://i.stack.imgur.com/EbVHR.png" alt="Debugging Outcome"></p>
<p>this is jquery.validate 1.10</p> | 14,440,287 | 5 | 1 | null | 2013-01-21 12:10:20.94 UTC | 3 | 2021-03-23 09:06:03.41 UTC | 2013-01-21 13:22:32.657 UTC | null | 343,889 | null | 343,889 | null | 1 | 33 | asp.net-mvc|html|jquery-validate | 63,306 | <p>This was really a poorly worded question on my part I think.</p>
<p>Essentially the issue was not the <code>novalidation</code> attribute at all (as @robasta said). </p>
<p>I couldn't get jQuery 1.9 and jQuery.Validate 1.10 to play nicely. Switching back to jQuery 1.83 fixed it straight away, all working as I'd expect.</p> |
2,895,214 | What is the semantically correct way to use the `<article>` tag in HTML 5, with `<ol>, <ul>, and <li>`? | <p>I currently have an ordered list that I want to markup using the new HTML 5 attributes. It looks like this:</p>
<pre><code><ol class="section">
<li class="article">
<h2>Article A</h2>
<p>Some text</p>
</li>
<li class="article">
<h2>Article B</h2>
<p>Some text</p>
</li>
<li class="article">
<h2>Article C</h2>
<p>Some text</p>
</li>
</ol>
</code></pre>
<p>It seems the only way to keep the list AND use HTML 5 tags is to add a whole bunch of unnecessary divs:</p>
<pre><code><section>
<ol>
<li>
<article>
<h2>Article A</h2>
<p>Some text</p>
</article>
</li>
<li>
<article>
<h2>Article B</h2>
<p>Some text</p>
</article>
</li>
<li>
<article>
<h2>Article C</h2>
<p>Some text</p>
</article>
</li>
</ol>
</section>
</code></pre>
<p>Is there a better way to do this? What are your thoughts?</p> | 2,895,665 | 2 | 0 | null | 2010-05-24 06:41:15.19 UTC | 9 | 2015-08-18 05:09:22.777 UTC | 2012-12-25 15:34:00.427 UTC | null | 106,224 | null | 169,992 | null | 1 | 14 | html | 5,211 | <p>If you’re using a list to add chronological order semantics to weblog posts, and as @Tomas mentioned each article is self-contained, then your code is ok (I’d remove the containing <code>section</code> though — it’s untitled and unnecessary).</p>
<p>However as you say there’s some extra markup. If you want to use less HTML, you can remove the list. You may think that you’ve then lost the chronological order semantics, but you can actually do this better using <code>time</code> with the <code>pubdate</code> attribute. This would look like:</p>
<pre><code><article>
<header>
<h2>The lolcat singularity</h2>
<time datetime="2010-05-24" pubdate="pubdate">Today</time>
</header>
<p>…</p>
</article>
<article>
<header>
<h2>The internet is made of cats</h2>
<time datetime="2010-05-23" pubdate="pubdate">Yesterday</time>
</header>
<p>…</p>
</article>
</code></pre>
<p>If you’re making a list of articles on the homepage, you’ll have to decide if the content stands alone (i.e. would you make a feed out of the article summaries). If so then the above code is still fine. If the summaries are too short to be self-contained, then you could choose to use a list, but at that stage you’re not dealing with “article” semantics, so your original classnames would be a little misleading:</p>
<pre><code><ol class="article-list">
<li>
<h2>Article A</h2>
<p>Some text</p>
</li>
<li>
<h2>Article B</h2>
<p>Some text</p>
</li>
<li>
<h2>Article C</h2>
<p>Some text</p>
</li>
</ol>
</code></pre>
<p>and select using <code>.article-list li {}</code> or <code>.article-list h2 {}</code> etc.</p>
<p>Fwiw I actually ended up using an ordered list containing <code>article</code> with <code>time pubdate</code> — the semantic belt and suspenders approach. I’m now wondering if I should remove the list myself :) You can also get carried away with hAtom, but note that ARIA’s <code>role="article"</code> shouldn’t be used on list items.</p>
<p>While HTML5 is an evolution, you’ll get the most benefit from throwing out your old code, starting from the content and a good guide to the spec, and marking stuff up from scratch. HTH!</p> |
44,543,842 | How to connect locally hosted MySQL database with the docker container | <p>Through <code>docker-compose.yml</code> I am able to run the application. Now we want to move the application to production, But we don't want to use the container database. So is there any way so that I can connect my local MySQL database with the application using <code>docker-compose</code>?</p>
<p>My docker-compose.yml looks like:</p>
<pre><code>version: '3'
services:
web-app:
build:
context: .
dockerfile: web-app/Dockerfile
ports:
- 8080:8080
links:
- app-db
app-db:
build:
context: .
dockerfile: app-db/Dockerfile
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_DATABASE=Optimize
ports:
- 3306:3306
</code></pre>
<p>Instead of <code>app-db</code> part I just want to connect to my locally hosted <code>mysql</code> database.</p> | 44,544,841 | 8 | 1 | null | 2017-06-14 11:43:45.653 UTC | 26 | 2022-04-21 13:22:27.893 UTC | 2019-02-02 01:59:35.383 UTC | null | 1,033,581 | null | 8,081,633 | null | 1 | 68 | mysql|docker|docker-compose | 103,690 | <p>Find the host machine ip in the docker network. If you use docker-compose.yml <code>version: "3"</code> it's probably that that IP is: <code>172.18.0.1</code>, <strong>but confirm it</strong> searching for the "Gateway" of your container (your host):</p>
<pre><code>docker inspect <container-id-or-name> | grep Gateway
"Gateway": "",
"IPv6Gateway": "",
"Gateway": "172.18.0.1",
"IPv6Gateway": "",
</code></pre>
<p>So inside your docker application point to MySQL as this: <code>172.18.0.1:3306</code> (maybe in a configuration file). Take into account that that IP is fixed as long as the docker network still the same (the network is created by docker-compose, and it is not removed unless you do <code>docker-compose down</code>)</p>
<p>Also, check that your MySQL is listening to all of its interfaces. In your <code>my.cnf</code> search for <code>bind-address</code> that should be <code>0.0.0.0</code> (consider security issues if your server has public IP).</p>
<hr>
<p>As an alternative you can bring to the container the same networking as your host, in order to share the localhost, so the container will find mysql there. Use network mode as "host":</p>
<pre><code>version: '3'
services:
web-app:
build:
context: .
dockerfile: web-app/Dockerfile
ports:
- 8080:8080
network_mode: "host"
</code></pre>
<p>Then, point in your <code>hibernate.properties</code> to mysql as this: <code>localhost:3306</code></p> |
21,115,771 | AngularJS: Upload files using $resource (solution) | <p>I'm using AngularJS to interact with a <code>RESTful</code> webservice, using <code>$resource</code> to abstract the various entities exposed. Some of this entities are images, so I need to be able to use the <code>save</code> action of <code>$resource</code> "object" to send both binary data and text fields within the same request.</p>
<p>How can I use AngularJS's <code>$resource</code> service to send data and upload images to a restful webservice in a single <code>POST</code> request?</p> | 21,115,779 | 3 | 0 | null | 2014-01-14 14:16:30.857 UTC | 15 | 2016-08-25 15:20:57.093 UTC | 2015-06-01 16:45:43.103 UTC | null | 2,021,046 | null | 1,053,772 | null | 1 | 55 | angularjs|upload|angular-resource | 48,557 | <p>I've searched far and wide and, while I might have missed it, I couldn't find a solution for this problem: uploading files using a $resource action. </p>
<p>Let's make this example: our RESTful service allows us to access images by making requests to the <code>/images/</code> endpoint. Each <code>Image</code> has a title, a description and the path pointing to the image file. Using the RESTful service, we can get all of them (<code>GET /images/</code>), a single one (<code>GET /images/1</code>) or add one (<code>POST /images</code>). Angular allows us to use the $resource service to accomplish this task easily, but doesn't allow for file uploading - which is required for the third action - out of the box (and <a href="https://github.com/angular/angular.js/issues/1236#issuecomment-29115377" rel="noreferrer">they don't seem to be planning on supporting it anytime soon</a>). How, then, would we go about using the very handy $resource service if it can't handle file uploads? It turns out it's quite easy!</p>
<p>We are going to use data binding, because it's one of the awesome features of AngularJS. We have the following HTML form:</p>
<pre><code><form class="form" name="form" novalidate ng-submit="submit()">
<div class="form-group">
<input class="form-control" ng-model="newImage.title" placeholder="Title" required>
</div>
<div class="form-group">
<input class="form-control" ng-model="newImage.description" placeholder="Description">
</div>
<div class="form-group">
<input type="file" files-model="newImage.image" required >
</div>
<div class="form-group clearfix">
<button class="btn btn-success pull-right" type="submit" ng-disabled="form.$invalid">Save</button>
</div>
</form>
</code></pre>
<p>As you can see, there are two text <code>input</code> fields that are binded each to a property of a single object, which I have called <code>newImage</code>. The file <code>input</code> is binded as well to a property of the <code>newImage</code> object, but this time I've used a custom directive taken straight from <a href="https://github.com/angular/angular.js/issues/1375#issuecomment-21933012" rel="noreferrer">here</a>. This directive makes it so that every time the content of the file <code>input</code> changes, a FileList object is put inside the binded property instead of a <code>fakepath</code> (which would be Angular's standard behavior). </p>
<p>Our controller code is the following: </p>
<pre><code>angular.module('clientApp')
.controller('MainCtrl', function ($scope, $resource) {
var Image = $resource('http://localhost:3000/images/:id', {id: "@_id"});
Image.get(function(result) {
if (result.status != 'OK')
throw result.status;
$scope.images = result.data;
})
$scope.newImage = {};
$scope.submit = function() {
Image.save($scope.newImage, function(result) {
if (result.status != 'OK')
throw result.status;
$scope.images.push(result.data);
});
}
});
</code></pre>
<p>(In this case I am running a NodeJS server on my local machine on port 3000, and the response is a json object containing a <code>status</code> field and an optional <code>data</code> field).</p>
<p>In order for the file upload to work, we just need to properly configure the $http service, for example within the .config call on the app object. Specifically, we need to transform the data of each post request to a FormData object, so that it's sent to the server in the correct format:</p>
<pre><code>angular.module('clientApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($httpProvider) {
$httpProvider.defaults.transformRequest = function(data) {
if (data === undefined)
return data;
var fd = new FormData();
angular.forEach(data, function(value, key) {
if (value instanceof FileList) {
if (value.length == 1) {
fd.append(key, value[0]);
} else {
angular.forEach(value, function(file, index) {
fd.append(key + '_' + index, file);
});
}
} else {
fd.append(key, value);
}
});
return fd;
}
$httpProvider.defaults.headers.post['Content-Type'] = undefined;
});
</code></pre>
<p>The <code>Content-Type</code> header is set to <code>undefined</code> because setting it manually to <code>multipart/form-data</code> would not set the boundary value, and the server would not be able to parse the request correctly.</p>
<p>That's it. Now you can use <code>$resource</code> to <code>save()</code> objects containing both standard data fields and files.</p>
<p><strong>WARNING</strong> This has some limitations:</p>
<ol>
<li>It doesn't work on older browsers. Sorry :(</li>
<li><p>If your model has "embedded" documents, like</p>
<p><code>{
title: "A title",
attributes: {
fancy: true,
colored: false,
nsfw: true
},
image: null
}</code></p>
<p>then you need to refactor the transformRequest function accordingly. <strong>You could, for example, <code>JSON.stringify</code> the nested objects, provided you can parse them on the other end</strong></p></li>
<li><p>English is not my main language, so if my explanation is obscure tell me and I'll try to rephrase it :)</p></li>
<li>This is just an example. You can expand on this depending on what your application needs to do.</li>
</ol>
<p>I hope this helps, cheers!</p>
<h3>EDIT:</h3>
<p>As pointed out by <a href="https://stackoverflow.com/users/1636718/david">@david</a>, a less invasive solution would be to define this behavior only for those <code>$resource</code>s that actually need it, and not to transform each and every request made by AngularJS. You can do that by creating your <code>$resource</code> like this:</p>
<pre><code>$resource('http://localhost:3000/images/:id', {id: "@_id"}, {
save: {
method: 'POST',
transformRequest: '<THE TRANSFORMATION METHOD DEFINED ABOVE>',
headers: '<SEE BELOW>'
}
});
</code></pre>
<p>As for the header, you should create one that satisfies your requirements. The only thing you need to specify is the <code>'Content-Type'</code> property by setting it to <code>undefined</code>.</p> |
21,168,375 | Elasticsearch array must and must_not | <p>I have a documents looking like this in my elasticsearch DB :</p>
<pre><code>{
"tags" => [
"tag-1",
"tag-2",
"tag-3",
"tag-A"
]
"created_at" =>"2013-07-02 12:42:19 UTC",
"label" =>"Mon super label"
}
</code></pre>
<p>I would like to be able to filter my documents with this criteria :
Documents tags array must have tags-1, tags-3 and tags-2 but must not have tags-A.</p>
<p>I tried to use a bool filter but I can't manage to make it work !</p> | 21,169,472 | 1 | 0 | null | 2014-01-16 17:12:53.98 UTC | 8 | 2016-01-29 02:10:16.16 UTC | null | null | null | null | 2,854,544 | null | 1 | 10 | elasticsearch|filtering | 27,847 | <p>Here is a method that seems to accomplish you want: <a href="http://sense.qbox.io/gist/4dd806936f12a9668d61ce63f39cb2c284512443">http://sense.qbox.io/gist/4dd806936f12a9668d61ce63f39cb2c284512443</a></p>
<p>First I created an index with an explicit mapping. I did this so I could set the <code>"tags"</code> property to <code>"index": "not_analyzed"</code>. This means that the text will not be modified in any way, which will simplify the querying process for this example.</p>
<pre><code>curl -XPUT "http://localhost:9200/test_index" -d'
{
"mappings": {
"docs" : {
"properties": {
"tags" : {
"type": "string",
"index": "not_analyzed"
},
"label" : {
"type": "string"
}
}
}
}
}'
</code></pre>
<p>and then add some docs:</p>
<pre><code>curl -XPUT "http://localhost:9200/test_index/docs/1" -d'
{
"tags" : [
"tag-1",
"tag-2",
"tag-3",
"tag-A"
],
"label" : "item 1"
}'
curl -XPUT "http://localhost:9200/test_index/docs/2" -d'
{
"tags" : [
"tag-1",
"tag-2",
"tag-3"
],
"label" : "item 2"
}'
curl -XPUT "http://localhost:9200/test_index/docs/3" -d'
{
"tags" : [
"tag-1",
"tag-2"
],
"label" : "item 3"
}'
</code></pre>
<p>Then we can query using <code>must</code> and <code>must_not</code> clauses in a <code>bool</code> filter as follows:</p>
<pre><code>curl -XPOST "http://localhost:9200/test_index/_search" -d'
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"bool": {
"must": [
{
"terms": {
"tags": [
"tag-1",
"tag-2",
"tag-3"
],
"execution" : "and"
}
}
],
"must_not": [
{
"term": {
"tags": "tag-A"
}
}
]
}
}
}
}
}'
</code></pre>
<p>which yields the correct result:</p>
<pre><code>{
"took": 3,
"timed_out": false,
"_shards": {
"total": 2,
"successful": 2,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "test_index",
"_type": "docs",
"_id": "2",
"_score": 1,
"_source": {
"tags": [
"tag-1",
"tag-2",
"tag-3"
],
"label": "item 2"
}
}
]
}
}
</code></pre>
<p>Notice the <code>"execution" : "and"</code> parameter in the <code>terms</code> filter in the <code>must</code> clause. This means only docs that have all the <code>"tags"</code> specified will be returned (rather than those that match one or more). That may have been what you were missing. You can read more about the options in the <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-terms-filter.html">ES docs</a>.</p>
<p>I made a runnable example <a href="http://sense.qbox.io/gist/4dd806936f12a9668d61ce63f39cb2c284512443">here</a> that you can play with, if you have ES installed and running at <code>localhost:9200</code>, or you can provide your own endpoint.</p> |
34,459,720 | Rails - Bundle: command not found | <p>Encountered a problem when I tried to run/check bundle on on Mac
Bundler/bundler are in the local gem list when I did gem list --local</p>
<p>Gem env returns the following</p>
<pre><code> RubyGems Environment:
- RUBYGEMS VERSION: 2.0.14
- RUBY VERSION: 2.0.0 (2014-05-08 patchlevel 481) [universal.x86_64-darwin14]
- INSTALLATION DIRECTORY: /Library/Ruby/Gems/2.0.0
- RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby
- EXECUTABLE DIRECTORY: /usr/bin
- RUBYGEMS PLATFORMS:
- ruby
- universal-darwin-14
- GEM PATHS:
- /Library/Ruby/Gems/2.0.0
- /Users/jenny0322/.gem/ruby/2.0.0
- /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/gems/2.0.0
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :backtrace => false
- :bulk_threshold => 1000
- REMOTE SOURCES:
- https://rubygems.org/
</code></pre>
<p>Echo Path returns</p>
<pre><code>/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin
</code></pre>
<p>which gem returns</p>
<pre><code>/usr/bin/gem
</code></pre>
<p>How do I add path to the directory? I tried </p>
<pre><code>export PATH ="/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin:$PATH"
</code></pre>
<p>and have no luck...</p> | 34,460,297 | 2 | 0 | null | 2015-12-25 03:12:16.307 UTC | 2 | 2017-05-14 09:17:58.157 UTC | null | null | null | null | 5,715,814 | null | 1 | 30 | ruby-on-rails|ruby | 41,979 | <p>It seems that <strong><a href="http://bundler.io/">Bundler</a></strong> is not installed in your machine.</p>
<p>You have to <strong>install bundler first</strong> for that.</p>
<p><strong>1:</strong> <code>gem install bundler</code></p>
<p><strong>2:</strong> <code>bundle install</code></p>
<p>Hope this help you !!!</p> |
34,800,731 | Module not found when I do a modprobe | <p>I am trying to install this module: <a href="https://github.com/mkottman/acpi_call" rel="noreferrer">https://github.com/mkottman/acpi_call</a></p>
<p>I did a make, make install.</p>
<p>I then saw <code>acpi_call.ko</code> is in <code>/lib/modules/4.3.3-5-default/extra/</code>.</p>
<p>When I do a </p>
<blockquote>
<p>modprobe acpi_call</p>
</blockquote>
<p>I get</p>
<blockquote>
<p>modprobe: FATAL: Module acpi_call not found in directory
/lib/modules/4.3.3-5-default</p>
</blockquote>
<p>Tried putting <code>acpi_call.ko</code> in <code>/lib/modules/4.3.3-5-default</code> but got the same result.</p>
<p>I would like to make it persistent so that when I reboot, module is loaded. I think it's possible only with modprobe.</p> | 34,800,857 | 3 | 0 | null | 2016-01-14 22:09:00.623 UTC | 3 | 2020-11-25 12:50:04.4 UTC | 2017-01-04 10:07:43.087 UTC | null | 2,221,227 | null | 1,095,362 | null | 1 | 29 | linux|linux-device-driver | 127,227 | <p>If the module .ko file is really under <code>/lib/modules/4.3.3-5-default/extra/</code> and <code>4.3.3-5-default</code> is indeed your current kernel version, then the problem may simply be that you need to run <a href="http://linux.die.net/man/8/depmod" rel="noreferrer"><code>depmod</code></a> to re-create the module dependency list. Run:</p>
<pre><code>sudo depmod
</code></pre>
<p>and try again to <code>modprobe</code> the module.</p> |
34,722,415 | Understand Spark: Cluster Manager, Master and Driver nodes | <p>Having read this <a href="https://stackoverflow.com/q/32621990/1374804">question</a>, I would like to ask additional questions:</p>
<ol>
<li>The Cluster Manager is a long-running service, on which node it is running?</li>
<li>Is it possible that the Master and the Driver nodes will be the same machine? I presume that there should be a rule somewhere stating that these two nodes should be different?</li>
<li>In case where the Driver node fails, who is responsible of re-launching the application? and what will happen exactly? i.e. how the Master node, Cluster Manager and Workers nodes will get involved (if they do), and in which order? </li>
<li>Similarly to the previous question: In case where the Master node fails, what will happen exactly and who is responsible of recovering from the failure?</li>
</ol> | 40,560,068 | 2 | 1 | null | 2016-01-11 13:10:23.46 UTC | 13 | 2019-08-27 18:16:42.63 UTC | 2017-10-07 02:47:41.82 UTC | null | 1,592,191 | null | 1,374,804 | null | 1 | 27 | hadoop|apache-spark|hadoop-yarn|failover|apache-spark-standalone | 11,573 | <blockquote>
<p><strong>1. The Cluster Manager is a long-running service, on which node it is running?</strong></p>
</blockquote>
<p><strong>Cluster Manager is Master process</strong> in Spark standalone mode. It can be started anywhere by doing <code>./sbin/start-master.sh</code>, in YARN it would be Resource Manager.</p>
<blockquote>
<p><strong>2. Is it possible that the Master and the Driver nodes will be the same machine? I presume that there should be a rule somewhere stating that these two nodes should be different?</strong></p>
</blockquote>
<p><code>Master</code> is per cluster, and <code>Driver</code> is per application. For standalone/yarn clusters, Spark currently supports two deploy modes. </p>
<ol>
<li><strong>In client mode, the driver is launched in the same process as the client that submits the application</strong>. </li>
<li><strong>In cluster mode</strong>, however, for <strong>standalone, the driver</strong> is launched from <strong>one of the Worker</strong> & for <strong>yarn</strong>, it is launched inside <strong>application master node</strong> and the client process exits as soon as it fulfils its responsibility of submitting the application without waiting for the app to finish. </li>
</ol>
<p>If an application submitted with <code>--deploy-mode client</code> in Master node, both <strong>Master and Driver will be on the same node</strong>. check <a href="https://stackoverflow.com/questions/24909958/spark-on-yarn-concept-understanding/38598830#38598830">deployment of Spark application over YARN</a> </p>
<blockquote>
<p><strong>3. In the case where the Driver node fails, who is responsible for re-launching the application? And what will happen exactly? i.e. how the Master node, Cluster Manager and Workers nodes will get involved (if they do), and in which order?</strong></p>
</blockquote>
<p>If the driver fails, <strong>all executors tasks will be killed</strong> for that submitted/triggered spark application.</p>
<blockquote>
<p><strong>4. In the case where the Master node fails, what will happen exactly and who is responsible for recovering from the failure?</strong></p>
</blockquote>
<p>Master node failures are handled in two ways.</p>
<ol>
<li><p><strong>Standby Masters with ZooKeeper:</strong></p>
<blockquote>
<p>Utilizing ZooKeeper to provide leader election and some state storage,
you can launch multiple Masters in your cluster connected to the same
ZooKeeper instance. One will be elected “leader” and the others will
remain in standby mode. If the current leader dies, another Master
will be elected, recover the old Master’s state, and then resume
scheduling. The entire recovery process (from the time the first
leader goes down) should take between 1 and 2 minutes. Note that this
delay only affects scheduling new applications – applications that
were already running during Master failover are unaffected. <a href="http://spark.apache.org/docs/2.0.1/spark-standalone.html#standby-masters-with-zookeeper" rel="noreferrer">check here
for configurations</a></p>
</blockquote></li>
<li><p><strong>Single-Node Recovery with Local File System:</strong></p>
<blockquote>
<p>ZooKeeper is the best way to go for production-level high
availability, but if you want to be able to restart the Master if
it goes down, FILESYSTEM mode can take care of it. When applications
and Workers register, they have enough state written to the provided
directory so that they can be recovered upon a restart of the Master
process. <a href="http://spark.apache.org/docs/2.0.1/spark-standalone.html#single-node-recovery-with-local-file-system" rel="noreferrer">check here for conf and more details</a></p>
</blockquote></li>
</ol> |
45,224,707 | Install and configure supervisord on centos 7 to run Laravel queues permanently | <p>I want to use Laravel queue system in my project and I want to run <strong>php artisan queue:work</strong> permanently on server's background, I did some searches about this and I found a command line which can run it even after quit from ssh terminal but It can be down in some cases and can make terrible problems for me. So after a while I found out that there is a package named Supervisord which can restart command even after server is rebooted. So I want to ask someone to help from 0 to 100 step by step how to install Supervisord and configure it on centos 7 and after that set the queue command line. Thank you so much..</p> | 47,322,239 | 3 | 0 | null | 2017-07-20 20:35:45.897 UTC | 22 | 2022-05-15 10:20:50.837 UTC | 2019-12-15 08:07:34.413 UTC | null | 4,189,435 | null | 4,189,435 | null | 1 | 34 | laravel|centos7|supervisord|laravel-queue | 72,171 | <p>here is how to install and config supervisord on centos 7 to run Laravel queues permanently:</p>
<ol>
<li><code>easy_install supervisor</code></li>
<li><code>yum install supervisor</code></li>
<li><code>vim /etc/supervisord.conf</code> edit section program as following: </li>
</ol>
<blockquote>
<pre><code>[program:laravel-worker]
command=php /path/to/app.com/artisan queue:work
process_name=%(program_name)s_%(process_num)02d
numprocs=8
priority=999
autostart=true
autorestart=true
startsecs=1
startretries=3
user=apache
redirect_stderr=true
stdout_logfile=/path/to/log/worker.log
</code></pre>
</blockquote>
<ol start="4">
<li><code>systemctl enable supervisord</code> to autorun at start</li>
<li><code>systemctl restart supervisord</code> to restart the service</li>
</ol> |
45,065,636 | PySpark: How to fillna values in dataframe for specific columns? | <p>I have the following sample DataFrame:</p>
<pre><code>a | b | c |
1 | 2 | 4 |
0 | null | null|
null | 3 | 4 |
</code></pre>
<p>And I want to replace null values only in the first 2 columns - Column "a" and "b":</p>
<pre><code>a | b | c |
1 | 2 | 4 |
0 | 0 | null|
0 | 3 | 4 |
</code></pre>
<p>Here is the code to create sample dataframe: </p>
<pre><code>rdd = sc.parallelize([(1,2,4), (0,None,None), (None,3,4)])
df2 = sqlContext.createDataFrame(rdd, ["a", "b", "c"])
</code></pre>
<p>I know how to replace all null values using: </p>
<pre><code>df2 = df2.fillna(0)
</code></pre>
<p>And when I try this, I lose the third column:</p>
<pre><code>df2 = df2.select(df2.columns[0:1]).fillna(0)
</code></pre> | 45,070,181 | 2 | 1 | null | 2017-07-12 19:02:06.137 UTC | 12 | 2019-04-17 20:08:14.613 UTC | 2017-07-12 21:05:44.413 UTC | null | 4,168,397 | null | 4,168,397 | null | 1 | 66 | apache-spark|pyspark|spark-dataframe | 135,709 | <pre><code>df.fillna(0, subset=['a', 'b'])
</code></pre>
<p>There is a parameter named <code>subset</code> to choose the columns unless your spark version is lower than 1.3.1</p> |
7,512,698 | Flask app that routes based on subdomain | <p>I want to have my top-level domain as a portal for various subdomains that correspond to different sections of my site. <code>example.com</code> should route to a <code>welcome.html</code> template. <code>eggs.example.com</code> should route to an "eggs" subsection or application of the site. How would I achieve this in Flask?</p> | 7,536,714 | 1 | 0 | null | 2011-09-22 09:40:13.09 UTC | 13 | 2021-08-01 10:36:24.063 UTC | 2018-08-16 21:19:28.28 UTC | null | 400,617 | null | 821,032 | null | 1 | 17 | python|google-app-engine|flask|url-routing|werkzeug | 9,512 | <p><a href="http://flask.pocoo.org/docs/api/#flask.Flask.route" rel="noreferrer"><code>@app.route()</code></a> takes a <code>subdomain</code> argument to specify what subdomain the route is matched on. <a href="http://flask.pocoo.org/docs/api/#blueprint-objects" rel="noreferrer"><code>Blueprint</code></a> also takes a <code>subdomain</code> argument to set subdomain matching for all routes in a blueprint.</p>
<p>You must set <code>app.config['SERVER_NAME']</code> to the base domain so Flask knows what to match against. You will also need to specify the port, unless your app is running on port 80 or 443 (i.e in production).</p>
<p>As of Flask 1.0 you must also set <code>subdomain_matching=True</code> when creating the app object.</p>
<pre><code>from flask import Flask
app = Flask(__name__, subdomain_matching=True)
app.config['SERVER_NAME'] = "example.com:5000"
@app.route("/")
def index():
return "example.com"
@app.route("/", subdomain="eggs")
def egg_index():
return "eggs.example.com"
</code></pre>
<pre><code>ham = Blueprint("ham", __name__, subdomain="ham")
@ham.route("/")
def index():
return "ham.example.com"
app.register_blueprint(ham)
</code></pre>
<p>When running locally, you'll need to edit your computer's hosts file (<code>/etc/hosts</code> on Unix) so that it will know how to route the subdomains, since the domains don't actually exist locally.</p>
<pre><code>127.0.0.1 localhost example.com eggs.example.com ham.example.com
</code></pre>
<p>Remember to still specify the port in the browser, <code>http://example.com:5000</code>, <code>http://eggs.example.com:5000</code>, etc.</p>
<p>Similarly, when deploying to production, you'll need to configure DNS so that the subdomains route to the same host as the base name, and configure the web server to route all those names to the app.</p>
<p>Remember, all Flask routes are really instances of <a href="http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule" rel="noreferrer"><code>werkzeug.routing.Rule</code></a>. Consulting <a href="http://werkzeug.pocoo.org/docs/routing/#werkzeug.routing.Rule" rel="noreferrer">Werkzeug's documentation for <code>Rule</code></a> will show you quite a few things that routes can do that Flask's documentation glosses over (since it is already well documented by Werkzeug).</p> |
42,025,767 | How to declare a type globally in a project (typescript) | <p>In a typescript project,
is there any way to declare a type and share it across all files, in the same way we have access to types defined globally at <code>node.d.ts</code>?</p>
<p>For example, let's say that in my project a <code>IUser</code> is something such as </p>
<pre><code>interface IUser {
name: string,
mail: string
}
</code></pre>
<p>Ok, I can create that interface in a <code>common/interfaces.ts</code> file and import it every time I need it... but would be so nice to be able to declare such interfaces globally for the whole project and have quick access to them without importing any file</p> | 42,026,565 | 3 | 0 | null | 2017-02-03 13:47:40.963 UTC | 6 | 2020-04-26 06:12:03.54 UTC | null | null | null | null | 1,614,677 | null | 1 | 62 | typescript | 38,863 | <p>You can create a <em>definition file</em>, ending with the <code>.d.ts</code> extension, and place it in your project where you'd like:</p>
<p><strong>user.d.ts</strong></p>
<pre><code>interface IUser {
name: string,
mail: string
}
</code></pre>
<p>This is also a good way to fill missing global types. I have a <code>lib/global</code> folder per project to place these files.</p>
<p>This only works with type definitions, not actual code, as (1) that actual code would have to be imported some way, (2) <code>.d.ts</code> is <a href="https://basarat.gitbooks.io/typescript/content/docs/types/ambient/intro.html" rel="noreferrer">ambient</a>. Also, for types defined this way to be globally visible, the corresponding declaration file <strong>should not contain top-level exports</strong> (otherwise the declaration file will be regarded as a <em>module</em>, requiring an import to access its types).</p>
<hr>
<p>You can also declare modules:</p>
<pre><code>declare module "my-module" {
export declare class Something {
public something: number;
}
}
</code></pre>
<p>And then TypeScript will allow the following:</p>
<pre><code>import { Something } from "my-module";
</code></pre> |
24,606,650 | reading CSV file and inserting it into 2d list in python | <p>I want to insert the data of CSV file (network data such as: time, IP address, port number) into 2D list in Python.</p>
<p>Here is the code:</p>
<pre><code>import csv
datafile = open('a.csv', 'r')
datareader = csv.reader(datafile, delimiter=';')
data = []
for row in datareader:
data.append(row)
print (data[1:4])
</code></pre>
<p>the result is:</p>
<pre><code>[['1', '6', '192.168.4.118', '1605', '', '115.85.145.5', '80', '', '60', '0.000000000', '0x0010', 'Jun 15, 2010 18:27:57.490835000', '0.000000000'],
['2', '6','115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.002365000', '0x0010', 'Jun 15, 2010 18:27:57.493200000', '0.002365000'],
['3', '6', '115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.003513000', '0x0018', 'Jun 15, 2010 18:27:57.496713000', '0.005878000']]
</code></pre>
<p>But it is just one dimension and I don't know how to create 2D array and insert each element into the array.</p>
<p>Please suggest me what code should I use for this purpose. (I looked the previous hints in the website but none of them worked for me)</p> | 24,606,805 | 4 | 0 | null | 2014-07-07 08:56:15.47 UTC | 3 | 2017-11-02 18:53:57.563 UTC | 2017-11-02 18:53:57.563 UTC | null | 7,492,195 | null | 3,636,424 | null | 1 | 12 | python|csv|multidimensional-array | 46,252 | <p>You already have list of lists, which is sort of 2D array and you can address it like one data[1][1], etc.</p> |
50,366,935 | ENOENT: no such file or directory for node_modules\jquery\dist\jquery.min.js' | <p>I am not sure what I am doing wrong:</p>
<p>I am following the tutorial <a href="https://medium.com/codingthesmartway-com-blog/using-bootstrap-with-angular-c83c3cee3f4a" rel="noreferrer">here</a>, but I keep getting the following error:</p>
<blockquote>
<p>ENOENT: no such file or directory, open
'C:\Users\andrewkp\Documents\VSCode\Projects\node_modules\jquery\dist\jquery.min.js'
Error: ENOENT: no such file or directory, open
'C:\Users\andrewkp\Documents\VSCode\Projects\node_modules\jquery\dist\jquery.min.js'</p>
</blockquote>
<p>Here is my angular.json file.</p>
<pre><code>{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"MyProjectName": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/MyProjectName",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js"
]
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "MyProjectName:build"
},
"configurations": {
"production": {
"browserTarget": "MyProjectName:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "MyProjectName:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js"
],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"MyProjectName-e2e": {
"root": "e2e/",
"projectType": "application",
"architect": {
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "MyProjectName:serve"
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "MyProjectName"
}
</code></pre> | 50,367,468 | 1 | 0 | null | 2018-05-16 09:21:11.483 UTC | 4 | 2019-08-12 14:31:15.067 UTC | null | null | null | null | 6,024,969 | null | 1 | 25 | angularjs|visual-studio-code|angular-cli|angular-cli-v6 | 43,749 | <p>After reviewing my error carefully:</p>
<blockquote>
<p>C:\Users\andrewkp\Documents\VSCode\Projects\node_modules\jquery\dist\jquery.min.js'</p>
</blockquote>
<p>I noticed that I was navigating to far back, as I can see above the path it is trying to read from is totally wrong, not including my project name at all. </p>
<p>The fix was to change:</p>
<pre><code>"styles": [
"src/styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js"
]
</code></pre>
<p>To: </p>
<pre><code>"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
</code></pre> |
50,104,172 | Could not find or load main class org.apache.maven.wrapper.MavenWrapperMain | <p>I have a spring boot project here: <a href="https://github.com/jcasbin/jcasbin-springboot-plugin" rel="noreferrer">https://github.com/jcasbin/jcasbin-springboot-plugin</a>. I encountered <a href="https://travis-ci.org/jcasbin/jcasbin-springboot-plugin/jobs/373086014" rel="noreferrer">the following error in Travis CI</a>:</p>
<pre><code>shell
3.43s$ ./mvnw install -DskipTests=true -Dmaven.javadoc.skip=true -B -V
/home/travis/build/jcasbin/jcasbin-springboot-plugin
Picked up _JAVA_OPTIONS: -Xmx2048m -Xms512m
Error: Could not find or load main class org.apache.maven.wrapper.MavenWrapperMain
The command "eval ./mvnw install -DskipTests=true -Dmaven.javadoc.skip=true -B -V " failed. Retrying, 2 of 3.
</code></pre>
<p>It seems that the <code>mvnw</code> command fails. This file is generated by my IDE: IntelliJ IDEA 2018.1. I don't know what it is used for and why does it fail?</p>
<p>I already fired an issue in Spring Boot's github issues <a href="https://github.com/spring-projects/spring-boot/issues/13002" rel="noreferrer">here</a>, but Spring project said it's Maven wrapper's issue and pointed me here. I don't quite understand what it means. Is it a Maven bug? How to fix the error then? </p> | 50,105,966 | 7 | 3 | null | 2018-04-30 16:01:53.41 UTC | 8 | 2022-08-10 12:36:24.923 UTC | 2018-05-03 18:07:31.377 UTC | null | 466,862 | null | 1,087,890 | null | 1 | 55 | java|spring|maven|spring-boot|travis-ci | 66,270 | <p>You're missing the <code>.mvn</code> folder in your git repository. You should have a folder called <code>.mvn</code> which contains the files <code>wrapper/maven-wrapper.jar</code>, <code>wrapper/maven-wrapper.properties</code> and <code>jvm.config</code>. Perhaps you missed it because it's a hidden folder.</p>
<p>Try doing <code>git add -f .mvn</code> from the command line then commit and push.</p> |
55,904,485 | Custom "navigate up" behavior for certain fragment using Navigation component | <p>I want to add custom <em>up navigation</em> from fragment using Navigation component</p>
<p>In my <code>build.gradle(app)</code> I use <code>androidx.appcompat:appcompat:1.1.0-alpha04</code> dependency to have access to <code>onBackPressedDispatcher</code> from activity.</p>
<p>So I implemented <code>OnBackPressedCallback</code> in my fragment and
registered callback to dispatcher:</p>
<pre><code>requireActivity().onBackPressedDispatcher.addCallback(this)
</code></pre>
<p>I expected that pressing <em>navigate up</em> in toolbar will call it, but it doesn't.
Pressing device's back button calls it as expected.</p>
<p>Is there a similar way to add some callback in fragment on navigate up action?</p>
<p><strong>UPDATE</strong></p>
<p>overridden methods <code>onOptionsItemSelected</code> and <code>onSupportNavigateUp</code> doesn't invoked on pressing <em>up button</em> in toolbar</p> | 55,930,024 | 5 | 0 | null | 2019-04-29 13:31:10.537 UTC | 8 | 2021-11-07 10:18:43.76 UTC | 2019-05-01 00:09:13.983 UTC | null | 10,914,552 | null | 10,914,552 | null | 1 | 28 | android|android-fragments|kotlin|android-architecture-navigation | 13,609 | <p>I found a solution</p>
<p><code>handleOnBackPressed()</code> method invokes only on device's back button click.
I wonder, why neither <code>onOptionsItemSelected()</code> nor <code>onSupportNavigateUp()</code> methods haven't been called on pressing "up button" in toolbar. And the answer is I used</p>
<pre><code>NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration)
</code></pre>
<p>in activity to setup toolbar with navigation component.
And that made toolbar responsive for work with navigation internally, pressing "up button" haven't invoked any of overridden methods in activity or fragments.</p>
<p>Instead should be used</p>
<pre><code>NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)
</code></pre>
<p>That will make actionBar responsive for navigation, thus I can use overridden functions <code>onOptionsItemSelected()</code> and <code>onSupportNavigateUp()</code>
And best place (in my case) to add custom behavior on "up button" click for certain screen is</p>
<pre><code>onSupportNavigateUp()
</code></pre>
<p>of hosted activity, like that</p>
<pre><code>override fun onSupportNavigateUp(): Boolean {
val navController = this.findNavController(R.id.mainNavHostFragment)
return when(navController.currentDestination?.id) {
R.id.destinationOfInterest -> {
// custom behavior here
true
}
else -> navController.navigateUp()
}
}
</code></pre>
<p>But worth to say, that if you want implement custom behavior directly in fragment, answer of @Enzokie should work like a charm</p> |
38,803,760 | How to get a release build with debugging information when using cargo? | <p>The following command</p>
<pre><code>$ cargo build
</code></pre>
<p>produces a <strong>non-optimized</strong> build <strong>with</strong> debugging information. On the contrary,</p>
<pre><code>$ cargo build --release
</code></pre>
<p>produces an <strong>optimized</strong> build <strong>without</strong> debugging information.</p>
<p>Is there a way of producing an <strong>optimized</strong> build <strong>with</strong> debugging information? I need this to get meaningful profiling information.</p> | 38,804,737 | 2 | 0 | null | 2016-08-06 11:27:56.03 UTC | 15 | 2022-04-19 17:55:28.703 UTC | null | null | null | null | 2,580,955 | null | 1 | 74 | rust|rust-cargo | 29,840 | <p>As of <a href="https://github.com/rust-lang/rust/blob/1.57.0/RELEASES.md#cargo" rel="noreferrer">Rust 1.57</a>, Cargo now allows for <a href="https://doc.rust-lang.org/cargo/reference/profiles.html#custom-profiles" rel="noreferrer"><em>custom profiles</em></a>. This allows you to define your own profile that adds debug information:</p>
<pre><code>[profile.release-with-debug]
inherits = "release"
debug = true
</code></pre>
<p>You can then use that profile when building:</p>
<pre class="lang-none prettyprint-override"><code>% cargo build --profile=release-with-debug
Compiling buggin v0.1.0 (/tmp/buggin)
Finished release-with-debug [optimized + debuginfo] target(s) in 0.48s
</code></pre>
<p>Prior to this version, or if you <strong>always</strong> wanted to have debugging information, you can modify the <code>release</code> <a href="https://doc.rust-lang.org/cargo/reference/profiles.html" rel="noreferrer"><em>profile</em></a> to include debugging symbols:</p>
<pre><code>[profile.release]
debug = true
</code></pre>
<p>Note that the <code>release</code> profile and the <code>bench</code> profile differ.</p>
<p>See also</p>
<ul>
<li><a href="https://stackoverflow.com/q/29818084/155423">Can tests be built in release mode using Cargo?</a></li>
<li><a href="https://stackoverflow.com/q/34054669/155423">How to compile and run an optimized Rust program with overflow checking enabled</a></li>
<li><a href="https://stackoverflow.com/q/41920192/155423">Does Cargo support custom profiles?</a></li>
</ul>
<p>Or basically any of the top search results for "rust profiling":</p>
<ul>
<li><a href="http://carol-nichols.com/2015/12/09/rust-profiling-on-osx-cpu-time/" rel="noreferrer">Rust Profiling with Instruments and FlameGraph on OSX: CPU/Time</a></li>
<li><a href="https://llogiq.github.io/2015/07/15/profiling.html" rel="noreferrer">Profiling Rust applications on Linux</a></li>
<li><a href="https://web.archive.org/web/20170508162645/https://shunyata.github.io/2015/10/01/profiling-rust/" rel="noreferrer">Profiling rust code with callgrind</a></li>
</ul> |
50,270,330 | How to get date and time in Angular 4,5,6 and above using DatePipe | <p>I am working in an angular 4 application, Here I need to get the current <code>Date and Time Using</code> angular <code>DatePipe</code>.</p>
<p>I want to get the date and time in the following format </p>
<p><strong>dd-mm-yyyy hh:MM:ss AM/PM</strong></p>
<p>I got the expected by using the Angular DatePipe as follows </p>
<pre><code><p>{{today | date:'dd-MM-yyyy hh:mm:ss a':'+0530'}}</p>
</code></pre>
<p>output :</p>
<pre><code>10-05-2018 03:28:57 PM
</code></pre>
<p>Here I What I want to do is get the same output from my app.component.ts without touching the HTML's </p>
<p>So I tried the below code but it generates a 13 digit timestamp</p>
<pre><code>today = Date.now();
fixedTimezone = this.today;
</code></pre>
<p>SO how can I get the date and time as the mentioned format purely from app.component.ts file without using HTML's.</p> | 50,270,509 | 4 | 0 | null | 2018-05-10 10:02:32.12 UTC | 6 | 2021-10-22 07:45:15.3 UTC | 2020-04-04 04:33:31.283 UTC | null | 1,594,359 | null | 9,390,197 | null | 1 | 14 | javascript|angular|typescript|date|date-pipe | 115,580 | <pre><code>let dateFormat = require('dateformat');
let now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
</code></pre>
<hr />
<pre><code>Thursday, May 10th, 2018, 7:11:21 AM
</code></pre>
<hr />
<p>And this format is exactly like your question</p>
<pre><code>dateFormat(now, "dd, mm, yyyy, h:MM:ss TT");
</code></pre>
<p>returns <code>10, 05, 2018 7:26:57 PM</code></p>
<p>you need npm package <code>npm i dateformat</code>
here is a link for the npm package <a href="https://www.npmjs.com/package/dateformat" rel="noreferrer">https://www.npmjs.com/package/dateformat</a></p>
<p>Here is another question that inspires me <a href="https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date">How to format a JavaScript date</a></p>
<hr />
<p><code>h:MM:ss TT</code> results <code>7:26:57 PM</code></p>
<p><code>HH:MM:ss</code> results <code>13:26:57</code></p>
<h2>Here is it <a href="https://jsfiddle.net/5z1tLspw/" rel="noreferrer">https://jsfiddle.net/5z1tLspw/</a></h2>
<p>I hope that helps.</p> |
14,182,823 | Echo image with php | <p>I am trying to do something really simple with php but I can not find where I have the mistake! So, I want to echo an image like this (part of the code):</p>
<pre><code> $file_path[0] = "/Applications/MAMP/htdocs/php_test/image_archive/".$last_file[0];
echo $file_path[0];
echo "<br>";
echo "<img src=\".$file_path[0].\" alt=\"error\">";
</code></pre>
<p>I must have some kind of error when I echo the img tag but I can not find it. Any help would be appreciated.</p>
<pre><code> <div class="content">
<h1> Map</h1>
<?php
include '/Applications/MAMP/htdocs/php_test/web_application_functions/last_file.php';
$last_file = last_file();
$file_path[0] = "/Applications/MAMP/htdocs/php_test/image_archive/".$last_file[0];
echo $file_path[0];
echo "<br>";
echo '<img src="' . $file_path[0] . '" alt="error">';
?>
<!-- end .content --></div>
</code></pre> | 14,182,836 | 2 | 8 | null | 2013-01-06 13:57:25.457 UTC | null | 2013-01-06 15:23:39.657 UTC | 2013-01-06 15:23:39.657 UTC | null | 493,122 | null | 1,712,543 | null | 1 | 0 | php | 65,800 | <p>You should use a path either relative to the server root, or the current file.</p>
<pre><code>echo "<img src='/php_test/image_archive/" . $last_file[0] . "' alt='error'>";
</code></pre> |
42,983,095 | Coroutine vs Fiber difference clarification | <p>In the book <code>Linux System Programming, 2nd Edition</code>, the difference between coroutines and fiber is explained as follows:</p>
<blockquote>
<p>Coroutines and fibers provide a unit of execution even lighter in weight than the thread (with the former being their name when they are a programming language construct, and the latter when they are a system construct).</p>
</blockquote>
<p>I have some example of Coroutines (language constructs) but unable to find the example of Fibers.</p>
<p>Can anyone provide me some example of Fiber (a system construct)?</p> | 44,563,119 | 1 | 0 | null | 2017-03-23 17:33:12.277 UTC | 10 | 2017-06-15 08:57:02.933 UTC | null | null | null | null | 3,454,167 | null | 1 | 21 | coroutine|fiber | 10,792 | <p>You could take a look at <a href="http://www.boost.org/doc/libs/1_64_0/libs/coroutine2/doc/html/index.html" rel="noreferrer">boost.coroutine2</a> and <a href="http://www.boost.org/doc/libs/1_64_0/libs/fiber/doc/html/index.html" rel="noreferrer">boost.fiber</a> (C++ libraries) - both use the same context switching mechanism (<a href="http://www.boost.org/doc/libs/1_64_0/libs/context/doc/html/context/cc.html" rel="noreferrer">callcc()/continuation</a>) from <a href="http://www.boost.org/doc/libs/1_64_0/libs/context/doc/html/index.html" rel="noreferrer">boost.context</a>.</p>
<p>In short - the difference between coroutines and fibers is, that the context switch between fibers is managed by a scheduler (selects the next fiber ...). Coroutines don't have a concept of a scheduler.</p>
<p>A more detailed explanation of the difference between coroutines and fibers can be read in <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4024.pdf" rel="noreferrer">N4024: Distinguishing coroutines and fibers</a>.</p> |
29,075,375 | "Cache-Control: max-age=0, no-cache" but browser bypasses server query (and hits cache)? | <p>I'm using Chrome 40 (so something nice and modern).</p>
<p><code>Cache-Control: max-age=0, no-cache</code> is set on all pages - so I expect the browser to only use something from its cache if it has first checked with the server and gotten a <code>304 Not Modified</code> response.</p>
<p>However on pressing the back button the browser merrily hits its own cache without checking with the server.</p>
<p>If I open the same page, as I reached with the back button, in a new tab then it does check with the server (and gets a <code>303 See Other</code> response as things have changed).</p>
<p>See the screen captures below showing the output for the two different cases from the Network tab of the Chrome Developer Tools.</p>
<p>I thought I could use <code>max-age=0, no-cache</code> as a lighter weight alternative to <code>no-store</code> where I don't want users seeing stale data via the back button (but where the data is non-valuable and so can be cached).</p>
<p>My understanding of <code>no-cache</code> (see <a href="https://stackoverflow.com/a/1383359/245602">here</a> and <a href="https://stackoverflow.com/questions/18148884/difference-between-no-cache-and-must-revalidate">here</a> on SO) is that the browser must always revalidate all responses. So why doesn't Chrome do this when using the back button?</p>
<p>Is <code>no-store</code> the only option?</p>
<hr>
<p><code>200</code> response (from cache) on pressing back button:</p>
<p><img src="https://i.stack.imgur.com/4rpIF.png" alt="enter image description here"></p>
<p><code>303</code> response on requesting the same page in a new tab:</p>
<p><img src="https://i.stack.imgur.com/vtWdz.png" alt="enter image description here"></p> | 29,237,792 | 3 | 0 | null | 2015-03-16 11:10:12.01 UTC | 8 | 2016-05-25 00:15:02.03 UTC | 2017-05-23 12:02:39.663 UTC | null | -1 | null | 245,602 | null | 1 | 21 | google-chrome|http-headers|browser-cache | 38,449 | <p>From <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1" rel="noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.1</a></p>
<blockquote>
<p>no-cache</p>
<p>If the no-cache directive does not specify a field-name, then a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server. This allows an origin server to prevent caching even by caches that have been configured to return stale responses to client requests.</p>
<p>If the no-cache directive does specify one or more field-names, then a cache MAY use the response to satisfy a subsequent request, subject to any other restrictions on caching. However, the specified field-name(s) MUST NOT be sent in the response to a subsequent request without successful revalidation with the origin server. This allows an origin server to prevent the re-use of certain header fields in a response, while still allowing caching of the rest of the response.</p>
</blockquote>
<p>Other than the name implies, <code>no-cache</code> does not require that the response must not be stored in cache. It only specifies that the cached response must not be reused to serve a <strong>subsequent</strong> request without re-validating, so it's a shorthand for <code>must-revalidate, max-age=0</code>.</p>
<p>It is up to the browser what to qualify as a <strong>subsequent</strong> request, and to my understanding using the back-button does not. This behavior varies between different browser engines.</p>
<p><code>no-store</code> forbids the use of the cached response for all requests, not only for subsequent ones.</p>
<p>Note that even with <code>no-store</code>, the RFC actually permits the client to store the response for use in history buffers. That means client may still use a cached response even when <code>no-store</code> has been specified.</p>
<p>Latter behavior covers cases where the page has been recorded with its original page title in the browser history. Another use case is the behavior of various mobile browsers which will not discard the previous page until the following page has fully loaded as the user might want to abort.</p>
<p>For clarification on the the behavior of the back button: It is not subject to any cache header, according to <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.13" rel="noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.13</a></p>
<blockquote>
<p>User agents often have history mechanisms, such as "Back" buttons and history lists, which can be used to redisplay an entity retrieved earlier in a session.</p>
<p>History mechanisms and caches are different. In particular history mechanisms SHOULD NOT try to show a semantically transparent view of the current state of a resource. Rather, a history mechanism is meant to show exactly what the user saw at the time when the resource was retrieved.</p>
<p>By default, an expiration time does not apply to history mechanisms. If the entity is still in storage, a history mechanism SHOULD display it even if the entity has expired, unless the user has specifically configured the agent to refresh expired history documents.</p>
</blockquote>
<p>That means that disrespecting any cache control headers when using the back button is the recommended behavior. If your browser happens to honor a backdated expiration date or applies the <code>no-store</code> directive not only to the browser cache but also to the history, it's actually already departing from that recommendation.</p>
<p>For how to solve it:<br />
You can't, and you are not supposed to. If the user is returning to a previously visited page, most browsers will even try to restore the viewport. You may use deferred mechanism like AJAX to refresh content if this was the original behavior before the user left the page, but otherwise you should not even modify the content.</p> |
50,180,735 | How can dataclasses be made to work better with __slots__? | <p>It <a href="https://github.com/ericvsmith/dataclasses/issues/28" rel="noreferrer">was decided</a> to remove direct support for <code>__slots__</code> from dataclasses for Python 3.7.</p>
<p>Despite this, <code>__slots__</code> can still be used with dataclasses:</p>
<pre><code>from dataclasses import dataclass
@dataclass
class C():
__slots__ = "x"
x: int
</code></pre>
<p>However, because of the way <code>__slots__</code> works it isn't possible to assign a default value to a dataclass field:</p>
<pre><code>from dataclasses import dataclass
@dataclass
class C():
__slots__ = "x"
x: int = 1
</code></pre>
<p>This results in an error:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'x' in __slots__ conflicts with class variable
</code></pre>
<p>How can <code>__slots__</code> and default <code>dataclass</code> fields be made to work together?</p> | 50,180,784 | 6 | 0 | null | 2018-05-04 18:02:23.887 UTC | 7 | 2022-03-17 16:19:41.823 UTC | 2021-10-21 12:19:17.333 UTC | null | 244,297 | null | 2,437,514 | null | 1 | 36 | python|python-3.x|slots|python-dataclasses | 21,666 | <p>2021 UPDATE: direct support for <code>__slots__</code> is <a href="https://stackoverflow.com/a/69661861/758345">added to python 3.10</a>. I am leaving this answer for posterity and won't be updating it.</p>
<p>The problem is not unique to dataclasses. ANY conflicting class attribute will stomp all over a slot:</p>
<pre><code>>>> class Failure:
... __slots__ = tuple("xyz")
... x=1
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'x' in __slots__ conflicts with class variable
</code></pre>
<p>This is simply how slots work. The error happens because <code>__slots__</code> creates a class-level descriptor object for each slot name:</p>
<pre><code>>>> class Success:
... __slots__ = tuple("xyz")
...
>>>
>>> type(Success.x)
<class 'member_descriptor'>
</code></pre>
<p>In order to prevent this conflicting variable name error, the class namespace must be altered <em>before</em> the class object is instantiated such that there are not two objects competing for the same member name in the class:</p>
<ul>
<li>the specified (default) value*</li>
<li>the slot descriptor (created by the slots machinery)</li>
</ul>
<p>For this reason, an <code>__init_subclass__</code> method on a parent class will not be sufficient, nor will a class decorator, because in both cases the class object has already been created by the time these functions have received the class to alter it.</p>
<h2>Current option: write a metaclass</h2>
<p>Until such time as the slots machinery is altered to allow more flexibility, or the language itself provides an opportunity to alter the class namespace before the class object is instantiated, our only choice is to use a metaclass.</p>
<p>Any metaclass written to solve this problem must, at minimum:</p>
<ul>
<li>remove the conflicting class attributes/members from the namespace</li>
<li>instantiate the class object to create the slot descriptors</li>
<li>save references to the slot descriptors</li>
<li>put the previously removed members and their values back in the class <code>__dict__</code> (so the <code>dataclass</code> machinery can find them)</li>
<li>pass the class object to the <code>dataclass</code> decorator</li>
<li>restore the slots descriptors to their respective places</li>
<li>also take into account plenty of corner cases (such as what to do if there is a <code>__dict__</code> slot)</li>
</ul>
<p>To say the least, this is an extremely complicated endeavor. It would be easier to define the class like the following- without a default value so that the conflict doesn't occur at all- and then add a default value afterward.</p>
<h2>Current option: make alterations after class object instantiation</h2>
<p>The unaltered dataclass would look like this:</p>
<pre><code>@dataclass
class C:
__slots__ = "x"
x: int
</code></pre>
<p>The alteration is straightforward. Change the <code>__init__</code> signature to reflect the desired default value, and then change the <code>__dataclass_fields__</code> to reflect the presence of a default value.</p>
<pre><code>from functools import wraps
def change_init_signature(init):
@wraps(init)
def __init__(self, x=1):
init(self,x)
return __init__
C.__init__ = change_init_signature(C.__init__)
C.__dataclass_fields__["x"].default = 1
</code></pre>
<p>Test:</p>
<pre><code>>>> C()
C(x=1)
>>> C(2)
C(x=2)
>>> C.x
<member 'x' of 'C' objects>
>>> vars(C())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute
</code></pre>
<p>It works!</p>
<h2>Current option: a <code>setmember</code> decorator</h2>
<p>With some effort, a so-called <code>setmember</code> decorator could be employed to automatically alter the class in the manner above. This would require deviating from the dataclasses API in order to define the default value in a location other than inside the class body, perhaps something like:</p>
<pre><code>@setmember(x=field(default=1))
@dataclass
class C:
__slots__="x"
x: int
</code></pre>
<p>The same thing could also be accomplished through a <code>__init_subclass__</code> method on a parent class:</p>
<pre><code>class SlottedDataclass:
def __init_subclass__(cls, **kwargs):
cls.__init_subclass__()
# make the class changes here
class C(SlottedDataclass, x=field(default=1)):
__slots__ = "x"
x: int
</code></pre>
<h2>Future possibility: change the slots machinery</h2>
<p>Another possibility, as mentioned above, would be for the python language to alter the slots machinery to allow more flexibility. One way of doing this might be to change the slots descriptor itself to store class level data at the time of class definition.</p>
<p>This could be done, perhaps, by supplying a <code>dict</code> as the <code>__slots__</code> argument (see below). The class-level data (1 for x, 2 for y) could just be stored on the descriptor itself for retrieval later:</p>
<pre><code>class C:
__slots__ = {"x": 1, "y": 2}
assert C.x.value == 1
assert C.y.value == y
</code></pre>
<p>One difficulty: it may be desired to only have a <code>slot_member.value</code> present on some slots and not others. This could be accommodated by importing a null-slot factory from a new <code>slottools</code> library:</p>
<pre><code>from slottools import nullslot
class C:
__slots__ = {"x": 1, "y": 2, "z": nullslot()}
assert not hasattr(C.z, "value")
</code></pre>
<p>The style of code suggested above would be a deviation from the dataclasses API. However, the slots machinery itself could even be altered to allow for this style of code, with accommodation of the dataclasses API specifically in mind:</p>
<pre><code>class C:
__slots__ = "x", "y", "z"
x = 1 # 1 is stored on C.x.value
y = 2 # 2 is stored on C.y.value
assert C.x.value == 1
assert C.y.value == y
assert not hasattr(C.z, "value")
</code></pre>
<h2>Future possibility: "prepare" the class namespace inside the class body</h2>
<p>The other possibility is altering/preparing (synonymous with the <code>__prepare__</code> method of a metaclass) the class namespace.</p>
<p>Currently, there is no opportunity (other than writing a metaclass) to write code that alters the class namespace before the class object is instantiated, and the slots machinery goes to work. This could be changed by creating a hook for preparing the class namespace beforehand, and making it so that an error complaining about the conflicting names is only produced after that hook has been run.</p>
<p>This so-called <code>__prepare_slots__</code> hook could look something like this, which I think is not too bad:</p>
<pre><code>from dataclasses import dataclass, prepare_slots
@dataclass
class C:
__slots__ = ('x',)
__prepare_slots__ = prepare_slots
x: int = field(default=1)
</code></pre>
<p>The <code>dataclasses.prepare_slots</code> function would simply be a function-- similar to the <a href="https://docs.python.org/3/reference/datamodel.html#preparing-the-class-namespace" rel="noreferrer"><code>__prepare__</code> method</a>-- that receives the class namespace and alters it before the class is created. For this case in particular, the default dataclass field values would be stored in some other convenient place so that they can be retrieved after the slot descriptor objects have been created.</p>
<hr />
<p>* Note that the default field value conflicting with the slot might also be created by the dataclass machinery if <code>dataclasses.field</code> is being used.</p> |
52,064,303 | ReactJS - Pass props with Redirect component | <p>How should you pass props with the <code>Redirect</code> component without having them exposed in the url? </p>
<p>Like this <code><Redirect to="/order?id=123 />"</code>? I'm using <code>react-router-dom</code>.</p> | 61,381,519 | 6 | 0 | null | 2018-08-28 18:34:43.753 UTC | 25 | 2021-09-03 06:24:48.287 UTC | 2019-01-22 08:07:54.993 UTC | null | 9,437,734 | null | 9,437,734 | null | 1 | 74 | javascript|reactjs|react-router-dom | 114,694 | <p>You should first pass the props in Route where you have define in your App.js</p>
<pre><code><Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>
</code></pre>
<p>then in your first Component</p>
<pre><code><Redirect
to={{
pathname: "/test/new",
state: { property_id: property_id }
}}
/>
</code></pre>
<p>and then in your Redirected NewTestComp you can use it where ever you want like this</p>
<pre><code>componentDidMount(props){
console.log("property_id",this.props.location.state.property_id);}
</code></pre> |
22,485,298 | stopSelf() vs stopSelf(int) vs stopService(Intent) | <p>What's the difference in calling<br>
<code>stopSelf()</code> , <code>stopSelf(int)</code> or <code>stopService(new Intent(this,MyServiceClass.class))</code><br>
inside <code>onStartCommand()</code> ?</p>
<p>for example if I start the same services twice this way:</p>
<pre><code>...
Intent myIntent1 = new Intent(AndroidAlarmService.this, MyAlarmService.class);
myIntent1.putExtra("test", 1);
Intent myIntent2 = new Intent(AndroidAlarmService.this, MyAlarmService.class);
myIntent2.putExtra("test", 2);
startService(myIntent1);
startService(myIntent2);
...
</code></pre>
<p>And implement onStartCommand in this way:</p>
<pre><code>public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(this, "onStartCommand called "+intent.getIntExtra("test", 0), Toast.LENGTH_LONG).show();
stopService(new Intent(this,MyAlarmService.class));
return START_NOT_STICKY;
}
</code></pre>
<p>I get exactly the same behaviour with the three methods,
that is onDestroy will only be called after onStartCommand is executed twice.</p> | 22,711,201 | 7 | 0 | null | 2014-03-18 16:26:21.68 UTC | 7 | 2019-07-09 21:41:29.29 UTC | 2014-03-27 18:22:42.38 UTC | null | 569,885 | null | 986,437 | null | 1 | 50 | android|service | 34,855 | <p>I hope this will help you:</p>
<p>A started service must manage its own lifecycle. That is, the system does not stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. So, the service must stop itself by calling stopSelf() or another component can stop it by calling stopService().</p>
<p>Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.</p>
<p>However, if your service handles multiple requests to onStartCommand() concurrently, then you shouldn't stop the service when you're done processing a start request, because you might have since received a new start request (stopping at the end of the first request would terminate the second one). To avoid this problem, you can use stopSelf(int) to ensure that your request to stop the service is always based on the most recent start request. </p>
<p>That is, when you call stopSelf(int), you pass the ID of the start request (the startId delivered to onStartCommand()) to which your stop request corresponds. Then if the service received a new start request before you were able to call stopSelf(int), then the ID will not match and the service will not stop.</p> |
22,886,500 | How to render text in SDL2? | <p>I'm using an <code>SDL_Window</code> and <code>SDL_Renderer</code>.</p>
<p>Is it possible to use <code>SDL_TTF</code> with <code>SDL_Render/SDL_Window</code>? If so, how?</p> | 22,889,483 | 7 | 0 | null | 2014-04-05 20:39:54.37 UTC | 18 | 2022-06-01 23:33:20.937 UTC | 2021-05-13 17:59:57.44 UTC | null | 44,729 | null | 3,501,975 | null | 1 | 53 | c|sdl-2 | 123,246 | <p>Yep, it is possible, given that you have a renderer and a window plus you don't really have any thoughts on dabbling with surfaces then you might want to mind on creating texture, here is a sample code</p>
<pre><code>//this opens a font style and sets a size
TTF_Font* Sans = TTF_OpenFont("Sans.ttf", 24);
// this is the color in rgb format,
// maxing out all would give you the color white,
// and it will be your text's color
SDL_Color White = {255, 255, 255};
// as TTF_RenderText_Solid could only be used on
// SDL_Surface then you have to create the surface first
SDL_Surface* surfaceMessage =
TTF_RenderText_Solid(Sans, "put your text here", White);
// now you can convert it into a texture
SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
SDL_Rect Message_rect; //create a rect
Message_rect.x = 0; //controls the rect's x coordinate
Message_rect.y = 0; // controls the rect's y coordinte
Message_rect.w = 100; // controls the width of the rect
Message_rect.h = 100; // controls the height of the rect
// (0,0) is on the top left of the window/screen,
// think a rect as the text's box,
// that way it would be very simple to understand
// Now since it's a texture, you have to put RenderCopy
// in your game loop area, the area where the whole code executes
// you put the renderer's name first, the Message,
// the crop size (you can ignore this if you don't want
// to dabble with cropping), and the rect which is the size
// and coordinate of your texture
SDL_RenderCopy(renderer, Message, NULL, &Message_rect);
// Don't forget to free your surface and texture
SDL_FreeSurface(surfaceMessage);
SDL_DestroyTexture(Message);
</code></pre>
<p>I tried to explain the code line by line, you don't see any window right there since I already assumed that you knew how to initialize a renderer which would give me an idea that you also know how to initialize a window, then all you need is the idea on how to initialize a texture.</p>
<p>Minor questions here, did your window open? was it colored black? if so then my thoughts were right, if not, then you can just ask me and I could change this code to implement the whole section which consists of a renderer and a window.</p> |
2,770,333 | Can extension methods be applied to interfaces? | <p>Is it possible to apply an extension method to an interface? (C# question)</p>
<p>That is for example to achieve the following:</p>
<ol>
<li><p>create an ITopology interface</p></li>
<li><p>create an extension method for this interface (e.g. public static int CountNodes(this ITopology topologyIf) )</p></li>
<li><p>then when creating a class (e.g. MyGraph) which implements ITopology, then it would automatically have the Count Nodes extension.</p></li>
</ol>
<p>This way the classes implementing the interface would not have to have a set class name to align with what was defined in the extension method. </p> | 2,770,341 | 1 | 0 | null | 2010-05-05 02:56:16.777 UTC | 16 | 2016-10-14 15:08:23.353 UTC | null | null | null | null | 173,520 | null | 1 | 158 | c#|.net|interface|extension-methods | 68,671 | <p>Of course they can; most of Linq is built around interface extension methods.</p>
<p>Interfaces were actually one of the driving forces for the development of extension methods; since they can't implement any of their own functionality, extension methods are the easiest way of associating actual code with interface definitions.</p>
<p>See the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx" rel="noreferrer">Enumerable</a> class for a whole collection of extension methods built around <code>IEnumerable<T></code>. To implement one, it's the same as implementing one for a class:</p>
<pre><code>public static class TopologyExtensions
{
public static void CountNodes(this ITopology topology)
{
// ...
}
}
</code></pre>
<p>There's nothing particularly different about extension methods as far as interfaces are concerned; an extension method is just a static method that the compiler applies some syntactic sugar to to make it look like the method is part of the target type.</p> |
21,017,404 | Reading and writing java.util.Date from Parcelable class | <p>I'm working with Parcelable class. How can I read and write <code>java.util.Date</code> object to and from this class?</p> | 21,017,453 | 6 | 0 | null | 2014-01-09 10:19:47.857 UTC | 13 | 2021-05-23 10:53:32.99 UTC | 2014-01-09 10:39:44.863 UTC | null | 913,707 | null | 997,757 | null | 1 | 78 | java|android | 32,576 | <p>Use <a href="http://developer.android.com/reference/android/os/Parcel.html#writeSerializable%28java.io.Serializable%29">writeSerializable</a> where Date is Serializable. (<strong><em>But not a good idea. See below for another better way</em></strong>)</p>
<pre><code>@Override
public void writeToParcel(Parcel out, int flags) {
// Write object
out.writeSerializable(date_object);
}
private void readFromParcel(Parcel in) {
// Read object
date_object = (java.util.Date) in.readSerializable();
}
</code></pre>
<hr>
<blockquote>
<p>But Serializing operations consume much performance. How can overcome
this?</p>
</blockquote>
<p><em>So better use is to convert date into Long while writing, and read Long and pass to Date constructor to get Date. See below code</em> </p>
<pre><code> @Override
public void writeToParcel(Parcel out, int flags) {
// Write long value of Date
out.writeLong(date_object.getTime());
}
private void readFromParcel(Parcel in) {
// Read Long value and convert to date
date_object = new Date(in.readLong());
}
</code></pre> |
38,655,630 | How does Docker know when to use the cache during a build and when not? | <p>I'm amazed at how good Docker's caching of layers works but I'm also wondering how it determines whether it may use a cached layer or not.</p>
<p>Let's take these build steps for example:</p>
<pre><code>Step 4 : RUN npm install -g node-gyp
---> Using cache
---> 3fc59f47f6aa
Step 5 : WORKDIR /src
---> Using cache
---> 5c6956ba5856
Step 6 : COPY package.json .
---> d82099966d6a
Removing intermediate container eb7ecb8d3ec7
Step 7 : RUN npm install
---> Running in b960cf0fdd0a
</code></pre>
<p>For example how does it know it can use the cached layer for <code>npm install -g node-gyp</code> but creates a fresh layer for <code>npm install</code> ? </p> | 38,656,553 | 2 | 1 | null | 2016-07-29 09:46:42.877 UTC | 15 | 2021-08-27 16:11:31.027 UTC | null | null | null | null | 446,835 | null | 1 | 78 | caching|docker | 25,752 | <p>The build cache process is explained fairly thoroughly in the <a href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#leverage-build-cache" rel="noreferrer">Best practices for writing Dockerfiles: Leverage build cache</a> section.</p>
<blockquote>
<ul>
<li><p>Starting with a parent image that is already in the cache, the next instruction is compared against all child images derived from that base image to see if one of them was built using the exact same instruction. If not, the cache is invalidated.</p>
</li>
<li><p>In most cases, simply comparing the instruction in the <code>Dockerfile</code> with one of the child images is sufficient. However, certain instructions require more examination and explanation.</p>
</li>
<li><p>For the <code>ADD</code> and <code>COPY</code> instructions, the contents of the file(s) in the image are examined and a checksum is calculated for each file. The last-modified and last-accessed times of the file(s) are not considered in these checksums. During the cache lookup, the checksum is compared against the checksum in the existing images. If anything has changed in the file(s), such as the contents and metadata, then the cache is invalidated.</p>
</li>
<li><p>Aside from the <code>ADD</code> and <code>COPY</code> commands, cache checking does not look at the files in the container to determine a cache match. For example, when processing a <code>RUN apt-get -y update</code> command the files updated in the container are not examined to determine if a cache hit exists. In that case just the command string itself is used to find a match.</p>
</li>
</ul>
<p>Once the cache is invalidated, all subsequent <code>Dockerfile</code> commands generate new images and the cache is not used.</p>
</blockquote>
<p>You will run into situations where OS packages, NPM packages or a Git repo are updated to newer versions (say a <code>~2.3</code> semver in <code>package.json</code>) but as your <code>Dockerfile</code> or <code>package.json</code> hasn't updated, docker will continue using the cache.</p>
<p>It's possible to programatically generate a <code>Dockerfile</code> that busts the cache by modifying lines on certain smarter checks (e.g retrieve the latest git branch shasum from a repo to use in the clone instruction). You can also periodically run the build with <code>--no-cache=true</code> to enforce updates.</p> |
31,234,168 | How do I calculate the shortest path (geodesic) distance between two adjectives in WordNet using Python NLTK? | <p>Computing the semantic similarity between two synsets in WordNet can be easily done with several built-in similarity measures, such as:</p>
<pre><code>synset1.path_similarity(synset2)
</code></pre>
<p><code>synset1.lch_similarity(synset2)</code>, Leacock-Chodorow Similarity</p>
<p><code>synset1.wup_similarity(synset2)</code>, Wu-Palmer Similarity</p>
<p><a href="https://stackoverflow.com/questions/22031968/how-to-find-distance-between-two-synset-using-python-nltk-in-wordnet-hierarchy">(as seen here)</a> </p>
<p>However, all of these exploit WordNet's taxonomic relations, which are relations for nouns and verbs. Adjectives and adverbs are related via synonymy, antonymy and pertainyms. How can one measure the distance (number of hops) between two adjectives? </p>
<p>I tried <code>path_similarity()</code>, but as expected, it returns <code>'None'</code>:</p>
<pre><code>from nltk.corpus import wordnet as wn
x = wn.synset('good.a.01')
y = wn.synset('bad.a.01')
print(wn.path_similarity(x,y))
</code></pre>
<p>If there is any way to compute the distance between one adjective and another, pointing it out would be greatly appreciated.</p> | 31,234,446 | 2 | 0 | null | 2015-07-05 19:26:25.323 UTC | 8 | 2015-07-05 22:58:46.04 UTC | 2017-05-23 12:34:50.137 UTC | null | -1 | null | 3,141,533 | null | 1 | 5 | python|nlp|nltk|wordnet|cosine-similarity | 3,475 | <p>There's no easy way to get similarity between words that are not nouns/verbs.</p>
<p>As noted, nouns/verbs similarity are easily extracted from </p>
<pre><code>>>> from nltk.corpus import wordnet as wn
>>> dog = wn.synset('dog.n.1')
>>> cat = wn.synset('cat.n.1')
>>> car = wn.synset('car.n.1')
>>> wn.path_similarity(dog, cat)
0.2
>>> wn.path_similarity(dog, car)
0.07692307692307693
>>> wn.wup_similarity(dog, cat)
0.8571428571428571
>>> wn.wup_similarity(dog, car)
0.4
>>> wn.lch_similarity(dog, car)
1.072636802264849
>>> wn.lch_similarity(dog, cat)
2.0281482472922856
</code></pre>
<p>For adjective it's hard, so you would need to build your own text similarity device. The easiest way is to use vector space model, basically, all words are represented by a number of floating point numbers, e.g.</p>
<pre><code>>>> import numpy as np
>>> blue = np.array([0.2, 0.2, 0.3])
>>> red = np.array([0.1, 0.2, 0.3])
>>> pink = np.array([0.1001, 0.221, 0.321])
>>> car = np.array([0.6, 0.9, 0.5])
>>> def cosine(x,y):
... return np.dot(x,y) / (np.linalg.norm(x) * np.linalg.norm(y))
...
>>> cosine(pink, red)
0.99971271929384864
>>> cosine(pink, blue)
0.96756147991512709
>>> cosine(blue, red)
0.97230558532824662
>>> cosine(blue, car)
0.91589118863996888
>>> cosine(red, car)
0.87469454283170045
>>> cosine(pink, car)
0.87482313596223782
</code></pre>
<p>To train a bunch of vectors for something like <code>pink = np.array([0.1001, 0.221, 0.321])</code>, you should try google for</p>
<ul>
<li>Latent semantic indexing / Latent semantic analysis</li>
<li>Bag of Words</li>
<li>Vector space model semantics</li>
<li>Word2Vec, Doc2Vec, Wiki2Vec</li>
<li>Neural Nets</li>
<li>cosine similarity natural language semantics</li>
</ul>
<p>You can also try some off the shelf software / libraries like:</p>
<ul>
<li>Gensim <a href="https://radimrehurek.com/gensim/" rel="nofollow noreferrer">https://radimrehurek.com/gensim/</a></li>
<li><a href="http://webcache.googleusercontent.com/search?q=cache:u5y4He592qgJ:takelab.fer.hr/sts/+&cd=2&hl=en&ct=clnk&gl=sg" rel="nofollow noreferrer">http://webcache.googleusercontent.com/search?q=cache:u5y4He592qgJ:takelab.fer.hr/sts/+&cd=2&hl=en&ct=clnk&gl=sg</a></li>
</ul>
<p>Other than vector space model, you can try some graphical model that puts words into a graph and uses something like pagerank to walk around the graph to give you some similarity measure. </p>
<p>See also: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/16877517/compare-similarity-of-terms-expressions-using-nltk">Compare similarity of terms/expressions using NLTK?</a></li>
<li><a href="https://stackoverflow.com/questions/18871706/check-if-two-words-are-related-to-each-other/18872777#18872777">check if two words are related to each other</a></li>
<li><a href="https://stackoverflow.com/questions/15625509/how-to-determine-semantic-hierarchies-relations-in-using-nltk">How to determine semantic hierarchies / relations in using NLTK?</a></li>
<li><a href="https://stackoverflow.com/questions/62328/is-there-an-algorithm-that-tells-the-semantic-similarity-of-two-phrases">Is there an algorithm that tells the semantic similarity of two phrases</a></li>
<li><a href="https://stackoverflow.com/questions/21374375/semantic-relatedness-algorithms-python">Semantic Relatedness Algorithms - python</a></li>
</ul> |
23,661,677 | Laravel convert an array to a model | <p>i have an array as follows </p>
<pre><code> 'topic' =>
array (
'id' => 13,
'title' => 'Macros',
'content' => '<p>Macros. This is the updated content.</p>
',
'created_at' => '2014-02-28 18:36:55',
'updated_at' => '2014-05-14 16:42:14',
'category_id' => '5',
'tags' => 'tags',
'referUrl' => '',
'user_id' => 3,
'videoUrl' => '',
'useDefaultVideoOverlay' => 'true',
'positive' => 0,
'negative' => 1,
'context' => 'macros',
'viewcount' => 60,
'deleted_at' => NULL,
)
</code></pre>
<p>I would like to use this array and convert/cast it into the Topic Model . Is there a way this can be done. </p>
<p>thanks</p> | 23,661,752 | 7 | 0 | null | 2014-05-14 17:50:05.697 UTC | 4 | 2018-07-27 19:43:32.977 UTC | null | null | null | null | 412,628 | null | 1 | 30 | laravel|laravel-4 | 41,481 | <p>Try creating a new object and passing the array into the constructor</p>
<pre><code>$topic = new Topic($array['topic']);
</code></pre> |
23,861,101 | "Controller as" syntax for ng-view | <p>I was wondering how I use the <code>Controller as</code> syntax in combination with <code>ngRoute</code> since I cant do <code>ng-controller="Controller as ctrl"</code> </p> | 23,861,159 | 2 | 0 | null | 2014-05-26 00:04:57.02 UTC | 1 | 2015-04-22 09:34:58.573 UTC | 2015-04-22 09:16:08.73 UTC | null | 596,068 | null | 1,703,761 | null | 1 | 30 | angularjs|ngroute | 5,928 | <p>You can use the <code>controller as</code> syntax when you specify your controller in the <code>$routeProvider</code> configuration.</p>
<p>e.g.</p>
<pre><code>$routeProvider
.when('/somePath', {
template: htmlTemplate,
controller: 'myController as ctrl'
});
</code></pre> |
25,767,522 | Disable UITextField Predictive Text | <p>With the release of iOS 8 I would like to disable the predictive text section of the keyboard when I begin typing in a UITextField. Not sure how this is done, any help would be appreciated!</p> | 25,768,242 | 8 | 0 | null | 2014-09-10 14:05:26.877 UTC | 12 | 2022-05-22 13:38:26.803 UTC | 2015-10-26 09:07:18.507 UTC | null | 2,725,435 | null | 1,014,029 | null | 1 | 90 | xcode|uitextfield|ios8 | 56,856 | <p>Setting the autoCorrectionType to UITextAutocorrectionTypeNo did the trick</p>
<p>Objective-C</p>
<pre><code>textField.autocorrectionType = UITextAutocorrectionTypeYes;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
</code></pre>
<p>Swift 2</p>
<pre><code>textField.autocorrectionType = .Yes
textField.autocorrectionType = .No
</code></pre>
<p>Swift 3</p>
<pre><code>textField.autocorrectionType = .yes
textField.autocorrectionType = .no
</code></pre>
<p>SwiftUI</p>
<pre><code>textField.disableAutocorrection(true)
textField.disableAutocorrection(false)
</code></pre> |
3,052,571 | How to get table cell at specified index using jQuery | <p>I know that I can get first or last table cell (e.g. for last row) using jQuery expression like below:</p>
<p>first cell: <code>$('#table tr:last td:first')</code> or last cell: <code>$('#table tr:last td:last')</code></p>
<p>But, how can I get cell at <em>specific index</em>, for example index 2, using similar expression, i.e. something like <code>$('#table tr:last td:[2]')</code> ?</p>
<p>Regards.</p> | 3,052,583 | 3 | 0 | null | 2010-06-16 10:45:31.873 UTC | 6 | 2012-11-28 10:30:06.74 UTC | 2012-11-28 10:30:06.74 UTC | null | 270,315 | null | 270,315 | null | 1 | 28 | javascript|jquery | 52,151 | <p>Yes:</p>
<pre><code>$('#table tr:last td:eq(1)')
</code></pre>
<p>that will give you the second <code>td</code> in the last row.</p> |
2,674,736 | Loading a dll from a dll? | <p>What's the best way for loading a dll from a dll ?</p>
<p>My problem is I can't load a dll on process_attach, and I cannot load the dll from the main program, because I don't control the main program source. And therefore I cannot call a non-dllmain function, too.</p> | 2,686,042 | 4 | 13 | null | 2010-04-20 11:44:19.743 UTC | 16 | 2021-03-07 21:09:05.857 UTC | null | null | null | null | 155,077 | null | 1 | 8 | c++|multithreading|loadlibrary|dll | 16,408 | <p>After all the debate that went on in the comments, I think that it's better to summarize my positions in a "real" answer.</p>
<p>First of all, it's still not clear <em>why</em> you need to load a dll in DllMain with LoadLibrary. This is definitely a bad idea, since your DllMain is running <em>inside</em> another call to LoadLibrary, which holds the loader lock, as explained by the <a href="http://msdn.microsoft.com/en-us/library/ms682583%28VS.85%29.aspx" rel="nofollow noreferrer" title="DllMain Callback Function (Windows)">documentation of DllMain</a>:</p>
<blockquote>
During initial process startup or after a call to LoadLibrary, the system scans the list of loaded DLLs for the process. For each DLL that has not already been called with the DLL_PROCESS_ATTACH value, the system calls the DLL's entry-point function. <b>This call is made in the context of the thread that caused the process address space to change, such as the primary thread of the process or the thread that called LoadLibrary.</b> Access to the entry point is serialized by the system on a process-wide basis. <b>Threads in DllMain hold the loader lock so no additional DLLs can be dynamically loaded or initialized.</b>
</blockquote>
<blockquote>
The entry-point function should perform <b>only simple initialization or termination tasks</b>. It <b>must not call the LoadLibrary or LoadLibraryEx function (or a function that calls these functions)</b>, because this may create dependency loops in the DLL load order. This can result in a DLL being used before the system has executed its initialization code. Similarly, the entry-point function must not call the FreeLibrary function (or a function that calls FreeLibrary) during process termination, because this can result in a DLL being used after the system has executed its termination code.
</blockquote>
(emphasis added)
<p>So, this on why it is forbidden; for a clear, more in-depth explanation, see <a href="http://blogs.msdn.com/oleglv/archive/2003/10/24/56141.aspx" rel="nofollow noreferrer">this</a> and <a href="http://blogs.msdn.com/oleglv/archive/2003/10/28/56142.aspx" rel="nofollow noreferrer">this</a>, for some other examples about what can happen if you don't stick to these rules in DllMain see also some posts in <a href="http://blogs.msdn.com/oldnewthing/" rel="nofollow noreferrer">Raymond Chen's blog</a>.</p>
<p>Now, on Rakis answer.</p>
<p>As I already repeated several times, what you think that is DllMain, isn't the <em>real</em> DllMain of the dll; instead, it's just a function that is called by the real entrypoint of the dll. This one, in turn, is automatically took by the CRT to perform its additional initialization/cleanup tasks, among which there is the construction of global objects and of the static fields of the classes (actually all these from the compiler's perspective are almost the same thing). After (or before, for the cleanup) it completes such tasks, it calls your DllMain.</p>
<p>It goes somehow like this (obviously I didn't write all the error checking logic, it's just to show how it works):</p>
<pre><code>/* This is actually the function that the linker marks as entrypoint for the dll */
BOOL WINAPI CRTDllMain(
__in HINSTANCE hinstDLL,
__in DWORD fdwReason,
__in LPVOID lpvReserved
)
{
BOOL ret=FALSE;
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
/* Init the global CRT structures */
init_CRT();
/* Construct global objects and static fields */
construct_globals();
/* Call user-supplied DllMain and get from it the return code */
ret = DllMain(hinstDLL, fdwReason, lpvReserved);
break;
case DLL_PROCESS_DETACH:
/* Call user-supplied DllMain and get from it the return code */
ret = DllMain(hinstDLL, fdwReason, lpvReserved);
/* Destruct global objects and static fields */
destruct_globals();
/* Destruct the global CRT structures */
cleanup_CRT();
break;
case DLL_THREAD_ATTACH:
/* Init the CRT thread-local structures */
init_TLS_CRT();
/* The same as before, but for thread-local objects */
construct_TLS_globals();
/* Call user-supplied DllMain and get from it the return code */
ret = DllMain(hinstDLL, fdwReason, lpvReserved);
break;
case DLL_THREAD_DETACH:
/* Call user-supplied DllMain and get from it the return code */
ret = DllMain(hinstDLL, fdwReason, lpvReserved);
/* Destruct thread-local objects and static fields */
destruct_TLS_globals();
/* Destruct the thread-local CRT structures */
cleanup_TLS_CRT();
break;
default:
/* ?!? */
/* Call user-supplied DllMain and get from it the return code */
ret = DllMain(hinstDLL, fdwReason, lpvReserved);
}
return ret;
}
</code></pre>
<p>There isn't anything special about this: it also happens with normal executables, with your main being called by the real entrypoint, which is reserved by the CRT for the exact same purposes.</p>
<p>Now, from this it will be clear why the Rakis' solution isn't going to work: the constructors for global objects are called by the real DllMain (i.e. the actual entrypoint of the dll, which is the one about the MSDN page on DllMain talks about), so calling LoadLibrary from there has exactly the same effect as calling it from your fake-DllMain.</p>
<p>Thus, following that advice you'll obtain the same negative effects of calling directly LoadLibrary in the DllMain, and you'll also hide the problem in a seemingly-unrelated position, which will make the next maintainer work hard to find where this bug is located.</p>
<p>As for delayload: it may be an idea, but you must be really careful not to call any function of the referenced dll in your DllMain: in fact, if you did that you would trigger a hidden call to LoadLibrary, which would have the same negative effects of calling it directly.</p>
<p>Anyhow, in my opinion, if you need to refer to some functions in a dll the best option is to link statically against its import library, so the loader will automatically load it without giving you any problem, and it will resolve automatically any strange dependency chain that may arise.</p>
<p>Even in this case you mustn't call any function of this dll in DllMain, since it's not guaranteed that it's already been loaded; actually, in DllMain you can rely only on kernel32 being loaded, and maybe on dlls you're <em>absolutely sure</em> that your caller has already loaded before the LoadLibrary that is loading your dll was issued (but still you shouldn't rely on this, because your dll may also be loaded by applications that don't match these assumptions, and just want to, e.g., <a href="https://devblogs.microsoft.com/oldnewthing/20040127-00/?p=40873" rel="nofollow noreferrer">load a resource of your dll without calling your code</a>).</p>
<p>As pointed out by the article I linked before,</p>
<blockquote>
The thing is, as far as your binary is concerned, DllMain gets called at a truly unique moment. By that time OS loader has found, mapped and bound the file from disk, but - depending on the circumstances - in some sense your binary may not have been "fully born". Things can be tricky.</blockquote>
<blockquote>
In a nutshell, when DllMain is called, OS loader is in a rather fragile state. First off, it has applied a lock on its structures to prevent internal corruption while inside that call, and secondly, <b>some of your dependencies may not be in a fully loaded state</b>. Before a binary gets loaded, OS Loader looks at its static dependencies. If those require additional dependencies, it looks at them as well. As a result of this analysis, it comes up with a sequence in which DllMains of those binaries need to be called. It's pretty smart about things and in most cases you can even get away with not following most of the rules described in MSDN - <b>but not always</b>.</blockquote>
<blockquote>The thing is, <b>the loading order is unknown to you</b>, but more importantly, it's built based on the static import information. <b>If some dynamic loading occurs in your DllMain during DLL_PROCESS_ATTACH and you're making an outbound call, all bets are off</b>. There is <b>no guarantee that DllMain of that binary will be called</b> and therefore if you then attempt to GetProcAddress into a function inside that binary, <b>results are completely unpredictable as global variables may not have been initialized. Most likely you will get an AV.</b>
</blockquote>
<p>(again, emphasis added)</p>
<p>By the way, on the Linux vs Windows question: I'm not a Linux system programming expert, but I don't think that things are so different there in this respect.</p>
<p>There are still some equivalents of DllMain (the <i>_init</i> and <i>_fini</i> functions), which are - what a coincidence! - automatically took by the CRT, which in turn, from <i>_init</i>, calls all the constructors for the global objects and the functions marked with <i>__attribute__ constructor</i> (which are somehow the equivalent of the "fake" DllMain provided to the programmer in Win32). A similar process goes on with destructors in <i>_fini</i>.</p>
<p>Since <i>_init</i> too is called while the dll loading is still taking place (<i>dlopen</i> didn't return yet), I think that you're subject to similar limitations in what you can do in there. Still, in my opinion on Linux the problem is felt less, because (1) you have to explicitly opt-in for a DllMain-like function, so you aren't immediately tempted to abuse of it and (2), Linux applications, as far as I saw, tend to use less dynamic loading of dlls.</p>
<h3>In a nutshell</h3>
<b>No "correct" method will allow you to reference to any dll other than kernel32.dll in DllMain.</b>
<p>Thus, don't do anything important from DllMain, neither directly (i.e. in "your" DllMain called by the CRT) neither indirectly (in global class/static fields constructors), <em>especially</em> <b>don't load other dlls</b>, again, neither directly (via LoadLibrary) neither indirectly (with calls to functions in delay-loaded dlls, which trigger a LoadLibrary call).</p>
<p>The right way to have another dll loaded as a dependency is to - doh! - mark it as a static dependency. Just link against its static import library and reference at least one of its functions: the linker will add it to the dependency table of the executable image, and the loader will load it automatically (initializing it before or after the call to your DllMain, you don't need to know about it because you mustn't call it from DllMain).</p>
<p>If this isn't viable for some reason, there's still the delayload options (with the limits I said before).</p>
<p>If you <em>still</em>, for some unknown reason, have the inexplicable need to call LoadLibrary in DllMain, well, go ahead, shoot in your foot, it's in your faculties. But don't tell me I didn't warn you.</p>
<hr />
I was forgetting: another fundamental source of information on the topic is the [Best Practices for Creating DLLs][6] document from Microsoft, which actually talks almost only about the loader, DllMain, the loader lock and their interactions; have a look at it for additional information on the topic.
<hr />
<h2>Addendum</h2>
<blockquote>
No, not really an answer to my question. All it says is: "It's not possible with dynamic linking, you must link statically", and "you musn't call from dllmain".</blockquote>
Which *is* an answer to your question: under the conditions you imposed, you can't do what you want. In a nutshell of a nutshell, from DllMain you can't call *anything other than kernel32 functions*. Period.
<blockquote>
Although in detail, but I'm not really interested in why it doesn't work,</blockquote>
You should, instead, because understanding why the rules are made in that way makes you avoid big mistakes.
<blockquote>
fact is, the loader is not resolving dependenies correctly and the loading process is improperly threaded from Microsoft's part.</blockquote>
No, my dear, the loader does its job correctly, because *after* LoadLibrary has returned, all the dependencies are loaded and everything is ready to be used. The loader tries to call the DllMain in dependency order (to avoid problems with broken dlls which rely on other dlls in DllMain), but there are cases in which this is simply impossible.
<p>For example, there may be two dlls (say, A.dll and B.dll) that depend on each other: now, whose DllMain is to call first? If the loader initialized A.dll first, and this, in its DllMain, called a function in B.dll, anything could happen, since B.dll isn't initialized yet (its DllMain hasn't been called yet). The same applies if we reverse the situation.</p>
<p>There may be other cases in which similar problems may arise, so the simple rule is: don't call any external functions in DllMain, DllMain is just for initializing the <em>internal</em> state of your dll.</p>
<blockquote>The problem is there is no other way then doing it on dll_attach, and all the nice talk about not doing anything there is superfluous, because there is no alternative, at least not in my case.</blockquote>
<p>This discussion is going on like this: you say "I want to solve an equation like x^2+1=0 in the real domain". Everybody says you that it's not possible; you say that it's not an answer, and blame the math.</p>
<p>Someone tells you: hey, you can, here's a trick, the solution is just +/-sqrt(-1); everybody downvotes this answer (because it's wrong for your question, we're going outside the real domain), and you blame who downvotes. I explain you why that solution is not correct according to your question and why this problem can't be solved in the real domain. You say that you don't care about why it can't be done, that you can only do that in the real domain and again blame math.</p>
<p>Now, since, as explained and restated a million times, <em>under your conditions your answer has no solution</em>, can you explain us <strong>why on earth do you "have" to do such an idiotic thing as loading a dll in DllMain</strong>? Often "impossible" problems arise because we've chosen a strange route to solve another problem, which brings us to deadlock. If you explained the bigger picture, we could suggest a better solution to it which does not involve loading dlls in DllMain.</p>
<blockquote>
PS: If I statically link DLL2 (ole32.dll, Vista x64) against DLL1 (mydll), which version of the dll will the linker require on older operating systems?</blockquote>
The one that is present (obviously I'm assuming you're compiling for 32 bit); if an exported function needed by your application isn't present in the found dll, your dll is simply not loaded (LoadLibrary fails).
<hr />
<h2>Addendum (2)</h2>
<blockquote>Positive on injection, with CreateRemoteThread if you wanna know. Only on Linux and Mac the dll/shared library is loaded by the loader.</blockquote>
Adding the dll as a static dependency (what has been suggested since the beginning) makes it to be loaded by the loader exactly as Linux/Mac do, but the problem is still there, since, as I explained, in DllMain you still cannot rely on anything other than kernel32.dll (even if the loader in general intelligent enough to init first the dependencies).
<p>Still, the problem <em>can</em> be solved. Create the thread (that actually calls LoadLibrary to load your dll) with CreateRemoteThread; in DllMain use some IPC method (for example named shared memory, whose handle will be saved somewhere to be closed in the init function) to pass to the injector program the address of the "real" init function that your dll will provide. DllMain then will exit without doing anything else. The injector application, instead, will wait for the end of the remote thread with WaitForSingleObject using the handle provided by CreateRemoteThread. Then, after the remote thread will be ended (thus LoadLibrary will be completed, and all the dependencies will be initialized), the injector will read from the named shared memory created by DllMain the address of the init function in the remote process, and start it with CreateRemoteThread.</p>
<p>Problem: on Windows 2000 using named objects from DllMain is prohibited because</p>
<blockquote>In Windows 2000, named objects are provided by the Terminal Services DLL. If this DLL is not initialized, calls to the DLL can cause the process to crash.</blockquote>
So, this address may have to be passed in another manner. A quite clean solution would be to create a shared data segment in the dll, load it both in the injector application and in the target one and have it put in such data segment the required address. The dll would obviously have to be loaded first in the injector and then in the target, because otherwise the "correct" address would be overwritten.
<p>Another really interesting method that can be done is to write in the other process memory a little function (directly in assembly) that calls LoadLibrary and returns the address of our init function; since we wrote it there, we can also call it with CreateRemoteThread because we know where it is.</p>
<p>In my opinion, this is the best approach, and is also the simplest, since the code is already there, written in this <a href="http://www.codeproject.com/KB/threads/completeinject.aspx" rel="nofollow noreferrer" title="A More Complete DLL Injection Solution Using CreateRemoteThread - CodeProject">nice article</a>. Have a look at it, it is quite interesting and it probably will do the trick for your problem.</p> |
2,735,023 | Convert String to java.util.Date | <p>I am storing the dates in a SQLite database in this format:</p>
<pre><code>d-MMM-yyyy,HH:mm:ss aaa
</code></pre>
<p>When I retrieve the date with that format I am get every thing fine
except the hour. The hour is always <code>00</code>. Here is my output:</p>
<pre><code>String date--->29-Apr-2010,13:00:14 PM
After convrting Date--->1272479414000--Thu Apr 29 00:00:14 GMT+05:30 2010
</code></pre>
<p>Here is the code:</p>
<pre><code> Date lScheduledDate = CalendarObj.getTime();
DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
SomeClassObj.setTime(formatter.format(lScheduledDate));
String lNextDate = SomeClassObj.getTime();
DateFormat lFormatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
Date lNextDate = (Date)lFormatter.parse(lNextDate);
System.out.println("output here"+lNextDate);
</code></pre>
<p>What am I doing wrong?</p> | 2,735,198 | 4 | 2 | null | 2010-04-29 05:48:12.743 UTC | 7 | 2020-02-19 17:11:12.357 UTC | 2016-01-12 21:23:04.44 UTC | null | 344,286 | null | 28,557 | null | 1 | 35 | java|date|datetime-format | 145,297 | <p>I think your date format does not make sense. There is no 13:00 PM. Remove the "aaa" at the end of your format or turn the HH into hh.</p>
<p>Nevertheless, this works fine for me:</p>
<pre><code>String testDate = "29-Apr-2010,13:00:14 PM";
DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
Date date = formatter.parse(testDate);
System.out.println(date);
</code></pre>
<p>It prints "Thu Apr 29 13:00:14 CEST 2010".</p> |
31,756,756 | Axios Http client - How to construct Http Post url with form params | <p>I am trying to create a postHTTP request with some form parameters that are to be set. I am using the axios with node server. I already have a java code implementation of constructing a url as given below: </p>
<p>JAVA CODE: </p>
<pre><code>HttpPost post = new HttpPost(UriBuilder.fromUri (getProperty("authServerUrl"))
.path(TOKEN_ACCESS_PATH).build(getProperty("realm")));
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new NameValuePair("username",getProperty ("username")));
formParams.add(new NameValuePair("password",getProperty ("password")));
formParams.add(new NameValuePair("client_id, "user-client"));
</code></pre>
<p>I am trying to do the same thing in axios. </p>
<p>AXIOS IMPLEMENTATION: </p>
<pre><code>axios.post(authServerUrl +token_access_path,
{
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}).then(function(response) {
console.log(response); //no output rendered
}
</code></pre>
<p>Is the approach to set these form params on the post request correct?</p> | 31,758,005 | 4 | 0 | null | 2015-07-31 23:43:21.99 UTC | 26 | 2021-04-14 07:31:53.017 UTC | 2018-06-14 20:52:25.967 UTC | null | 5,535,245 | null | 5,001,265 | null | 1 | 89 | javascript|node.js|axios | 120,997 | <p>You have to do the following:</p>
<pre class="lang-js prettyprint-override"><code>var querystring = require('querystring');
//...
axios.post(authServerUrl + token_access_path,
querystring.stringify({
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function(response) {
console.log(response);
});
</code></pre> |
37,619,694 | How do I animate Views in Toolbar when user scrolls? | <p>I am trying to put some animation in my application. Please find the photo attached to get animation idea.</p>
<p><a href="https://i.stack.imgur.com/RBMzX.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/RBMzX.jpg" alt="Toolbar is cart icon rectangle and search_layout is below that."></a></p>
<p>I have used CoordinatorLayout. My search layout and toolbar is hosted inside AppBarLayout/CollapsingToolbarLayout. Below that is my NestedScrollView hosting fragment.</p>
<p>I am able to hide search layout when user scrolls using scroll flags. I am trying to implement a CoordinatorLayout.Behavior which will start moving the cart icon to the left and start search icon to scale from 0 to 1; as soon as the user scrolls and search layout starts to hide. When search layout is fully hidden, I want to show toolbar like in second screen. And it will come back to original state as shown in first screen when user scrolls down and search layout starts to show up by slowly moving cart to right and scaling down search icon.</p>
<p>Initially I have made the search icon on toolbar as hidden and cart icon & search icon are inside a linearlayout.</p>
<p>Please find my xml activity_home_page.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<com.example.ui.customviews.CustomDrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/ab_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="131dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<LinearLayout
android:id="@+id/ll_search_layout"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_gravity="bottom"
android:orientation="vertical"
android:visibility="visible"
app:layout_scrollFlags="scroll|snap">
<LinearLayout
android:id="@+id/ll_search_box"
android:layout_width="match_parent"
android:layout_height="51dp"
android:layout_marginBottom="@dimen/dimen_12_dp"
android:layout_marginLeft="@dimen/dimen_8_dp"
android:layout_marginRight="@dimen/dimen_8_dp"
android:layout_marginTop="@dimen/dimen_12_dp"
android:background="@drawable/round_corner_layout_white"
android:elevation="@dimen/dimen_5_dp"
android:focusableInTouchMode="true"
android:orientation="horizontal">
<EditText
android:id="@+id/et_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/dimen_15_dp"
android:layout_weight="80"
android:background="@android:color/transparent"
android:hint="Search for Products"
android:padding="@dimen/dimen_5_dp"
android:textColor="@color/black"
android:textColorHint="@color/hint_text_color"
android:textSize="@dimen/dimen_text_16_sp" />
<ImageView
android:id="@+id/iv_search_icon"
android:layout_width="@dimen/dimen_22_dp"
android:layout_height="@dimen/dimen_24_dp"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/dimen_17_dp"
android:layout_marginRight="@dimen/dimen_20_dp"
android:src="@drawable/ic_search_grey" />
</LinearLayout>
</LinearLayout>
<include
layout="@layout/layout_primary_toolbar"
android:layout_width="match_parent"
android:layout_height="@dimen/toolbar_primary_height"
android:layout_gravity="top"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<ImageView
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@color/askme_blue"
app:layout_behavior="com.GetIt.animation.SearchLayoutBehavior"/>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
<fragment
android:id="@+id/navigation_drawer"
android:name="com.example.ui.fragment.SideMenuFragment"
android:layout_width="@dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start" />
</com.example.ui.customviews.CustomDrawerLayout>
</code></pre>
<p>My xml for layout_primary_toolbar.xml is</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="@dimen/toolbar_primary_height"
android:background="@color/askme_blue"
app:contentInsetEnd="0dp"
app:contentInsetStart="0dp"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<LinearLayout
android:id="@+id/layout_toolbar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_drawer_menu"
android:layout_width="@dimen/dimen_22_dp"
android:layout_height="@dimen/dimen_22_dp"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/dimen_16_dp"
android:layout_marginRight="@dimen/dimen_15_dp"
android:src="@drawable/ic_drawer_menu" />
<ImageView
android:id="@+id/iv_back_btn"
android:layout_width="@dimen/dimen_22_dp"
android:layout_height="@dimen/dimen_20_dp"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/dimen_16_dp"
android:layout_marginRight="@dimen/dimen_15_dp"
android:src="@drawable/ic_back_button"
android:visibility="gone"/>
<LinearLayout
android:id="@+id/ll_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<com.GetIt.ui.customviews.TextViewRRegular
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delhi"
android:textColor="@color/white"
android:textSize="20sp"
android:visibility="visible" />
<ImageView
android:id="@+id/toolbar_location_change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:src="@drawable/ic_edit_location"
android:visibility="gone"/>
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:gravity="right"
android:layout_marginRight="@dimen/dimen_16_dp">
<RelativeLayout
android:id="@+id/rl_cart_count"
android:layout_width="@dimen/dimen_40_dp"
android:layout_height="@dimen/dimen_40_dp"
android:layout_centerVertical="true">
<ImageView
android:layout_width="@dimen/dimen_25_dp"
android:layout_height="@dimen/dimen_24_dp"
android:layout_centerInParent="true"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:scaleType="center"
android:src="@drawable/ic_cart" />
<TextView
android:id="@+id/tv_cart_count"
android:layout_width="@dimen/dimen_17_dp"
android:layout_height="@dimen/dimen_17_dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="@dimen/dimen_3_dp"
android:layout_marginTop="@dimen/dimen_3_dp"
android:background="@drawable/cart_count_background_circle"
android:elevation="@dimen/dimen_5_dp"
android:gravity="center"
android:textColor="@color/white"
android:textSize="@dimen/dimen_text_10_sp"
android:textStyle="bold"
android:visibility="visible" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl_search"
android:layout_width="@dimen/dimen_40_dp"
android:layout_height="@dimen/dimen_40_dp"
android:layout_centerVertical="true"
android:layout_marginLeft="14dp"
android:layout_toRightOf="@+id/rl_cart_count">
<ImageView
android:id="@+id/iv_search"
android:layout_width="@dimen/dimen_24_dp"
android:layout_height="@dimen/dimen_24_dp"
android:layout_centerInParent="true"
android:src="@drawable/ic_search" />
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</code></pre>
<p>I am stuck on this for last 7 hours. I am new to android animation.</p>
<p>Initially I am hiding rl_search (search box) programmatically. I want that when ll_search_layout scrolls up (beneath the toolbar), rl_cart should move to left (which is its original position had rl_search not been made hidden) and rl_search should scale from 0 to 1.</p>
<p>I have used ObjectAnimator with LinearInterpolator but its not working at all.</p>
<p>Any suggestions how to achieve this?</p>
<p>P.S. - I can post the code if you guys need that for reference.</p>
<p>Thanks</p> | 37,672,471 | 2 | 0 | null | 2016-06-03 16:49:51.737 UTC | 14 | 2016-06-07 06:56:39.753 UTC | 2016-06-03 17:20:40.923 UTC | null | 1,383,666 | null | 1,383,666 | null | 1 | 12 | android|animation|android-animation|objectanimator | 5,313 | <p>After trying myself for over 2 days, finally I am able to do the animation. I am posting this answer for others if they also wants to do something like that.</p>
<p>I have not used animation utility of android but a hack to increase and decrease padding and scaling up and down the search icon.</p>
<p>This is my behaviour class</p>
<pre><code>public class SearchLayoutBehavior extends CoordinatorLayout.Behavior<ImageView> {
Context mContext;
private static final int DIRECTION_UP = 1;
private static final int DIRECTION_DOWN = -1;
private static final int CART_PADDING_LOWER_LIMIT = 0;
private static int CART_PADDING_UPPER_LIMIT;
private static final float SEARCH_SCALING_LOWER_LIMIT = 0.0f;
private static final float SEARCH_SCALING_UPPER_LIMIT = 1.0f;
private float CART_PADDING_MULTIPLICATION_FACTOR;
private float SEARCH_SCALE_MULTIPLICATION_FACTOR;
RelativeLayout mRlSearch, mRlParentCart;
Toolbar mToolbar;
LinearLayout mLlSearchLayout;
boolean mIsSetupDone = false;
int mScrollingDirection, mPrevDiff1, mPrevDiff2;
public SearchLayoutBehavior() {
super();
}
public SearchLayoutBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, ImageView child, View dependency) {
return (dependency.getId() == R.id.ab_app_bar);
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, ImageView child, View dependency) {
mRlParentCart = (RelativeLayout) dependency.findViewById(R.id.rl_parent_cart_count);
mRlSearch = (RelativeLayout) dependency.findViewById(R.id.rl_search);
mToolbar = (Toolbar) dependency.findViewById(R.id.toolbar);
mLlSearchLayout = (LinearLayout) dependency.findViewById(R.id.ll_search_layout);
int searchLayoutBottom = mLlSearchLayout.getBottom();
int searchLayoutTop = mLlSearchLayout.getTop();
int toolbarBottom = mToolbar.getBottom();
int diff1 = searchLayoutBottom - toolbarBottom;
int diff2 = searchLayoutTop - toolbarBottom;
if (!mIsSetupDone) {
CART_PADDING_UPPER_LIMIT = mContext.getResources().getDimensionPixelSize(R.dimen.cart_animation_move_left);
CART_PADDING_MULTIPLICATION_FACTOR = (float) CART_PADDING_UPPER_LIMIT / diff1;
SEARCH_SCALE_MULTIPLICATION_FACTOR = (float) 1 / diff1;
mPrevDiff1 = diff1;
mPrevDiff2 = -diff1;
mIsSetupDone = true;
}
if (mScrollingDirection == DIRECTION_UP && mPrevDiff1 >= diff1) {
moveCart(mRlParentCart, mPrevDiff1 - diff1, true);
mPrevDiff1 = diff1;
} else if (mScrollingDirection == DIRECTION_DOWN && mPrevDiff2 <= diff2) {
moveCart(mRlParentCart, diff2 - mPrevDiff2, false);
mPrevDiff2 = diff2;
}
if (diff2 == 0) {
mPrevDiff1 = diff1;
mPrevDiff2 = -diff1;
}
return true;
}
private void moveCart(final View view, float by, boolean doMoveLeft) {
int paddingRight = view.getPaddingRight();
float scaleX = mRlSearch.getScaleX();
float scaleY = mRlSearch.getScaleY();
if (doMoveLeft) {
paddingRight += (int) (by * CART_PADDING_MULTIPLICATION_FACTOR);
if (paddingRight >= CART_PADDING_UPPER_LIMIT) {
view.setPadding(0, 0, CART_PADDING_UPPER_LIMIT, 0);
} else {
view.setPadding(0, 0, paddingRight, 0);
}
scaleX += by * SEARCH_SCALE_MULTIPLICATION_FACTOR;
scaleY += by * SEARCH_SCALE_MULTIPLICATION_FACTOR;
if (Float.compare(scaleX, SEARCH_SCALING_UPPER_LIMIT) >= 0) {
mRlSearch.setScaleX(SEARCH_SCALING_UPPER_LIMIT);
} else {
mRlSearch.setScaleX(scaleX);
}
if (Float.compare(scaleY, SEARCH_SCALING_UPPER_LIMIT) >= 0) {
mRlSearch.setScaleY(SEARCH_SCALING_UPPER_LIMIT);
} else {
mRlSearch.setScaleY(scaleY);
}
} else {
paddingRight -= (int) (by * CART_PADDING_MULTIPLICATION_FACTOR);
if (paddingRight <= CART_PADDING_LOWER_LIMIT) {
view.setPadding(0, 0, CART_PADDING_LOWER_LIMIT, 0);
} else {
view.setPadding(0, 0, paddingRight, 0);
}
scaleX -= by * SEARCH_SCALE_MULTIPLICATION_FACTOR;
scaleY -= by * SEARCH_SCALE_MULTIPLICATION_FACTOR;
if (Float.compare(scaleX, SEARCH_SCALING_LOWER_LIMIT) == -1) {
mRlSearch.setScaleX(SEARCH_SCALING_LOWER_LIMIT);
} else {
mRlSearch.setScaleX(scaleX);
}
if (Float.compare(scaleY, SEARCH_SCALING_LOWER_LIMIT) == -1) {
mRlSearch.setScaleY(SEARCH_SCALING_LOWER_LIMIT);
} else {
mRlSearch.setScaleY(scaleY);
}
}
}
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, ImageView child, View target, int dx, int dy, int[] consumed) {
//Determine direction changes here
if (dy > 0 && mScrollingDirection != DIRECTION_UP) {
mScrollingDirection = DIRECTION_UP;
} else if (dy < 0 && mScrollingDirection != DIRECTION_DOWN) {
mScrollingDirection = DIRECTION_DOWN;
}
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, ImageView child, View directTargetChild, View target, int nestedScrollAxes) {
return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
}
}
</code></pre>
<p>This is my xml which uses coordinator layout. When the search layout moves up, cart moves to left and search icon scales up.</p>
<pre><code><com.example.ui.customviews.CustomDrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/ab_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="131dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<LinearLayout
android:id="@+id/ll_search_layout"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_gravity="bottom"
android:orientation="vertical"
android:visibility="visible"
android:background="@drawable/search_layout_twin_background"
app:layout_scrollFlags="scroll|snap">
<LinearLayout
android:id="@+id/ll_search_box"
android:layout_width="match_parent"
android:layout_height="51dp"
android:layout_marginBottom="@dimen/dimen_12_dp"
android:layout_marginLeft="@dimen/dimen_8_dp"
android:layout_marginRight="@dimen/dimen_8_dp"
android:layout_marginTop="@dimen/dimen_12_dp"
android:background="@drawable/round_corner_layout_white"
android:elevation="@dimen/dimen_5_dp"
android:focusableInTouchMode="true"
android:orientation="horizontal">
<EditText
android:id="@+id/et_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/dimen_15_dp"
android:layout_weight="80"
android:background="@android:color/transparent"
android:hint="Search for Products"
android:padding="@dimen/dimen_5_dp"
android:textColor="@color/black"
android:textColorHint="@color/hint_text_color"
android:textSize="@dimen/dimen_text_16_sp" />
<ImageView
android:id="@+id/iv_search_icon"
android:layout_width="@dimen/dimen_22_dp"
android:layout_height="@dimen/dimen_24_dp"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/dimen_17_dp"
android:layout_marginRight="@dimen/dimen_20_dp"
android:src="@drawable/ic_search_grey" />
</LinearLayout>
</LinearLayout>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="@dimen/toolbar_primary_height"
android:background="@color/askme_blue"
app:contentInsetEnd="0dp"
app:contentInsetStart="0dp"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<LinearLayout
android:id="@+id/layout_toolbar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="@+id/iv_drawer_menu"
android:layout_width="@dimen/dimen_22_dp"
android:layout_height="@dimen/dimen_22_dp"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/dimen_16_dp"
android:layout_marginRight="@dimen/dimen_15_dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:src="@drawable/ic_drawer_menu" />
<ImageView
android:id="@+id/iv_back_btn"
android:layout_width="@dimen/dimen_22_dp"
android:layout_height="@dimen/dimen_20_dp"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/dimen_16_dp"
android:layout_marginRight="@dimen/dimen_15_dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:src="@drawable/ic_back_button"
android:visibility="gone" />
</FrameLayout>
<LinearLayout
android:id="@+id/ll_location"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="?attr/selectableItemBackgroundBorderless">
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Delhi"
android:textColor="@color/white"
android:textSize="20sp"
android:visibility="visible" />
<ImageView
android:id="@+id/toolbar_location_change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/dimen_3_dp"
android:layout_marginTop="@dimen/dimen_4_dp"
android:src="@drawable/ic_edit_location"
android:visibility="visible" />
</LinearLayout>
</LinearLayout>
<FrameLayout
android:layout_width="@dimen/dimen_100_dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_marginRight="@dimen/dimen_16_dp"
android:gravity="right">
<RelativeLayout
android:id="@+id/rl_search"
android:layout_width="@dimen/dimen_40_dp"
android:layout_height="@dimen/dimen_40_dp"
android:layout_gravity="center_vertical|right"
android:layout_marginLeft="14dp"
android:background="?attr/selectableItemBackgroundBorderless">
<ImageView
android:id="@+id/iv_search"
android:layout_width="@dimen/dimen_24_dp"
android:layout_height="@dimen/dimen_24_dp"
android:layout_centerInParent="true"
android:src="@drawable/ic_search" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/rl_parent_cart_count"
android:layout_width="94dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|right"
android:gravity="right"
android:paddingRight="54dp">
<RelativeLayout
android:id="@+id/rl_cart_count"
android:layout_width="@dimen/dimen_40_dp"
android:layout_height="@dimen/dimen_40_dp"
android:layout_gravity="center_vertical|right"
android:background="?attr/selectableItemBackgroundBorderless">
<ImageView
android:layout_width="@dimen/dimen_25_dp"
android:layout_height="@dimen/dimen_24_dp"
android:layout_centerInParent="true"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:scaleType="center"
android:src="@drawable/ic_cart" />
<TextView
android:id="@+id/tv_cart_count"
android:layout_width="@dimen/dimen_17_dp"
android:layout_height="@dimen/dimen_17_dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="@dimen/dimen_3_dp"
android:layout_marginTop="@dimen/dimen_3_dp"
android:background="@drawable/cart_count_background_circle"
android:elevation="@dimen/dimen_5_dp"
android:gravity="center"
android:textColor="@color/white"
android:textSize="@dimen/dimen_text_10_sp"
android:textStyle="bold"
android:visibility="visible" />
</RelativeLayout>
</RelativeLayout>
</FrameLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<ImageView
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@color/askme_blue"
app:layout_behavior="com.GetIt.animation.SearchLayoutBehavior"/>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
<fragment
android:id="@+id/navigation_drawer"
android:name="com.example.ui.fragment.SideMenuFragment"
android:layout_width="@dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start" />
</com.example.ui.customviews.CustomDrawerLayout>
</code></pre>
<p>This is how it will look like.</p>
<p><a href="https://i.stack.imgur.com/w486j.gif"><img src="https://i.stack.imgur.com/w486j.gif" alt="enter image description here"></a></p> |
28,512,394 | How to lookup from and insert into a HashMap efficiently? | <p>I'd like to do the following:</p>
<ul>
<li>Lookup a <code>Vec</code> for a certain key, and store it for later use.</li>
<li>If it doesn't exist, create an empty <code>Vec</code> for the key, but still keep it in the variable.</li>
</ul>
<p>How to do this efficiently? Naturally I thought I could use <code>match</code>:</p>
<pre><code>use std::collections::HashMap;
// This code doesn't compile.
let mut map = HashMap::new();
let key = "foo";
let values: &Vec<isize> = match map.get(key) {
Some(v) => v,
None => {
let default: Vec<isize> = Vec::new();
map.insert(key, default);
&default
}
};
</code></pre>
<p>When I tried it, it gave me errors like:</p>
<pre class="lang-none prettyprint-override"><code>error[E0502]: cannot borrow `map` as mutable because it is also borrowed as immutable
--> src/main.rs:11:13
|
7 | let values: &Vec<isize> = match map.get(key) {
| --- immutable borrow occurs here
...
11 | map.insert(key, default);
| ^^^ mutable borrow occurs here
...
15 | }
| - immutable borrow ends here
</code></pre>
<p>I ended up with doing something like this, but I don't like the fact that it performs the lookup twice (<code>map.contains_key</code> and <code>map.get</code>):</p>
<pre><code>// This code does compile.
let mut map = HashMap::new();
let key = "foo";
if !map.contains_key(key) {
let default: Vec<isize> = Vec::new();
map.insert(key, default);
}
let values: &Vec<isize> = match map.get(key) {
Some(v) => v,
None => {
panic!("impossiburu!");
}
};
</code></pre>
<p>Is there a safe way to do this with just one <code>match</code>?</p> | 28,512,504 | 2 | 0 | null | 2015-02-14 04:23:30.29 UTC | 30 | 2022-04-06 19:47:49.433 UTC | 2017-11-21 20:28:56.867 UTC | null | 155,423 | null | 4,416,558 | null | 1 | 163 | hashmap|rust|lookup | 39,551 | <p>The <a href="https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html#method.entry" rel="noreferrer"><code>entry</code> API</a> is designed for this. In manual form, it might look like</p>
<pre class="lang-rust prettyprint-override"><code>let values = match map.entry(key) {
Entry::Occupied(o) => o.into_mut(),
Entry::Vacant(v) => v.insert(default),
};
</code></pre>
<p>One can use the briefer form via <a href="https://doc.rust-lang.org/stable/std/collections/hash_map/enum.Entry.html#method.or_insert_with" rel="noreferrer"><code>Entry::or_insert_with</code></a>:</p>
<pre class="lang-rust prettyprint-override"><code>let values = map.entry(key).or_insert_with(|| default);
</code></pre>
<p>If <code>default</code> is already computed, or if it's OK/cheap to compute even when it isn't inserted, you can use <a href="https://doc.rust-lang.org/stable/std/collections/hash_map/enum.Entry.html#method.or_insert" rel="noreferrer"><code>Entry::or_insert</code></a>:</p>
<pre class="lang-rust prettyprint-override"><code>let values = map.entry(key).or_insert(default);
</code></pre>
<p>If the <code>HashMap</code>'s value implements <code>Default</code>, you can use <a href="https://doc.rust-lang.org/stable/std/collections/hash_map/enum.Entry.html#method.or_default" rel="noreferrer"><code>Entry::or_default</code></a>, although you may need to provide some type hints:</p>
<pre class="lang-rust prettyprint-override"><code>let values = map.entry(key).or_default();
</code></pre> |
28,489,720 | UITableViewCell Subclass with XIB Swift | <p>I have a <code>UITableViewCell</code> subclass <code>NameInput</code> that connects to an xib with a custom <code>init</code> method. </p>
<pre><code>class NameInput: UITableViewCell {
class func make(label: String, placeholder: String) -> NameInput {
let input = NSBundle.mainBundle().loadNibNamed("NameInput", owner: nil, options: nil)[0] as NameInput
input.label.text = label
input.valueField.placeholder = placeholder
input.valueField.autocapitalizationType = .Words
return input
}
}
</code></pre>
<p>Is there a way I can initialize this cell in the <code>viewDidLoad</code> method and still reuse it? Or do I have to register the class itself with a reuse identifier?</p> | 28,490,468 | 2 | 0 | null | 2015-02-12 23:17:12.113 UTC | 9 | 2017-03-08 23:31:20.84 UTC | null | null | null | null | 2,510,041 | null | 1 | 9 | ios|uitableview|swift | 20,938 | <p>The customary NIB process is:</p>
<ol>
<li><p>Register your NIB with the reuse identifier. In Swift 3:</p>
<pre><code>override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
}
</code></pre>
<p>In Swift 2:</p>
<pre><code>override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
}
</code></pre></li>
<li><p>Define your custom cell class:</p>
<pre><code>import UIKit
class NameInput: UITableViewCell {
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet weak var lastNameLabel: UILabel!
}
</code></pre></li>
<li><p>Create a NIB file in Interface Builder (with the same name referenced in step 1):</p>
<ul>
<li><p>Specify the base class of the tableview cell in the NIB to reference your custom cell class (defined in step 2).</p></li>
<li><p>Hook up references between the controls in the cell in the NIB to the <code>@IBOutlet</code> references in the custom cell class.</p></li>
</ul></li>
<li><p>Your <code>cellForRowAtIndexPath</code> would then instantiate the cell and set the labels. In Swift 3:</p>
<pre><code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NameInput
let person = people[indexPath.row]
cell.firstNameLabel.text = person.firstName
cell.lastNameLabel.text = person.lastName
return cell
}
</code></pre>
<p>In Swift 2:</p>
<pre><code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NameInput
let person = people[indexPath.row]
cell.firstNameLabel.text = person.firstName
cell.lastNameLabel.text = person.lastName
return cell
}
</code></pre></li>
</ol>
<p>I wasn't entirely sure from your example what controls you placed on your cell, but the above has two <code>UILabel</code> controls. Hook up whatever <code>@IBOutlet</code> references make sense for your app.</p> |
36,396,765 | Commenting (out) code in Angular2 TypeScript | <p>I have the following Angular2 TypeScript code with a section commented out as per Javascript convention:</p>
<pre><code>@Component({
selector: 'my-app',
template:
`<h1>{{title}}</h1>
<h2>{{lene.name}}</h2>
<div><label>id: </label>{{lene.id}}</div>
/*<div>
<label>name: </label>
<input [(ngModel)]="lene.name" placeholder="name">
</div>*/`
<div><label>description: </label>{{lene.description}}</div>
})
</code></pre>
<p>However, once the TypeScript compiles to Javascript I get the following output to my web browser:</p>
<p><a href="https://i.stack.imgur.com/e6ujy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/e6ujy.png" alt="Browser image"></a></p>
<p>I've searched the API docs and can't find an entry specifying the syntax for this quite basic feature. Anyone know how you do multi-line comments in TypeScript?</p> | 36,396,788 | 3 | 0 | null | 2016-04-04 07:26:32.647 UTC | 2 | 2020-06-05 04:05:39.253 UTC | 2016-04-04 11:02:11.323 UTC | null | 5,202,687 | null | 5,202,687 | null | 1 | 10 | javascript|angularjs|angular|comments | 49,105 | <p><code>/* */</code> is typescript comment delimiter</p>
<p>They don't work inside a string literal.</p>
<p>You can use HTML comment syntax instead <code><!-- --></code>.</p>
<pre><code>@Component({
selector: 'my-app',
template:
`<h1>{{title}}</h1>
<h2>{{lene.name}}</h2>
<div><label>id: </label>{{lene.id}}</div>
<!-- <div>
<label>name: </label>
<input [(ngModel)]="lene.name" placeholder="name">
</div> -->'
<div><label>description: </label>{{lene.description}}</div>
})
</code></pre>
<p>The HTML commented out this way still is added to the DOM but only as comment.</p> |
38,481,764 | rxjs flatmap missing | <p>I try to chain multiple rx.js observables and pass the data. <code>Flatmap</code> should be the fitting operator but with an import of</p>
<pre><code>import { Observable } from 'rxjs/Observable';
</code></pre>
<p>it is not found:</p>
<pre><code>Error TS2339: Property 'flatmap' does not exist on type 'Observable<Coordinates>'
</code></pre>
<p>Version <code>5.0.0-beta.6</code> of rx.js is used.</p>
<pre><code>public getCurrentLocationAddress():Observable<String> {
return Observable.fromPromise(Geolocation.getCurrentPosition())
.map(location => location.coords)
.flatmap(coordinates => {
console.log(coordinates);
return this.http.request(this.geoCodingServer + "/json?latlng=" + coordinates.latitude + "," + coordinates.longitude)
.map((res: Response) => {
let data = res.json();
return data.results[0].formatted_address;
});
});
}
</code></pre> | 38,482,172 | 6 | 1 | null | 2016-07-20 12:46:48.58 UTC | 6 | 2019-05-05 11:40:32.73 UTC | 2016-07-20 12:53:38.173 UTC | null | 2,587,904 | null | 2,587,904 | null | 1 | 65 | rxjs|observable|reactive-extensions-js | 47,122 | <p>It turns out the answer is quite simple:</p>
<p>the operator is called <code>mergeMap</code> in this version of rxjs</p>
<p>EDIT:</p>
<p>Furthermore, you might have to use <code>import 'rxjs/add/operator/mergeMap'</code>.</p> |
1,316,963 | Vim: padding out lines with a character | <p>How can I repeatedly add a character at the end of one or more lines, padding out the line(s) to a specific column? </p>
<p>For instance:<br>
('x' represents column 40, not a character on the line; and there are no spaces or tabs after the text)</p>
<pre><code>line one x
line two x
line three x
line eleventy-billion x
</code></pre>
<p>becomes </p>
<pre><code>line one ------------------------------x
line two ------------------------------x
line three ----------------------------x
line eleventy-billion -----------------x
</code></pre> | 1,317,056 | 2 | 0 | null | 2009-08-22 20:27:42.34 UTC | 10 | 2018-12-04 20:56:26.607 UTC | null | null | null | null | 39,442 | null | 1 | 15 | vim | 4,505 | <p>A combination of <a href="http://vimdoc.sourceforge.net/htmldoc/change.html#sub-replace-expression" rel="noreferrer"><code>\=</code></a>, <a href="http://vimdoc.sourceforge.net/htmldoc/eval.html#submatch%28%29" rel="noreferrer">submatch()</a>, and <a href="http://vimdoc.sourceforge.net/htmldoc/eval.html#repeat%28%29" rel="noreferrer">repeat()</a>:</p>
<pre><code>:%s/\v^.*$/\= submatch(0) . " " . repeat("-", 39 - len(submatch(0)))
</code></pre> |
686,571 | Why does Assert.IsInstanceOfType(0.GetType(), typeof(int)) fail? | <p>I'm kind of new to unit testing, using <code>Microsoft.VisualStudio.TestTools.UnitTesting</code>;</p>
<p>The <code>0.GetType()</code> is actually <code>System.RuntimeType</code>, so what kind of test do I need to write to pass <code>Assert.IsInstanceOfType(0.GetType(), typeof(int))</code>?</p>
<p>--- following up, this is my own user error... <code>Assert.IsInstanceOfType(0, typeof(int))</code></p> | 686,592 | 2 | 5 | null | 2009-03-26 16:37:13.027 UTC | 3 | 2013-09-16 16:25:48.89 UTC | 2013-03-19 14:21:30.803 UTC | Dave | 467,172 | Dave | 21,909 | null | 1 | 47 | c#|unit-testing|mstest | 40,461 | <p>Change the call to the following</p>
<pre><code>Assert.IsInstanceOfType(0, typeof(int));
</code></pre>
<p>The first parameter is the object being tested, not the type of the object being tested. by passing 0.GetType(), you were saying is "RunTimeType" an instance of System.int which is false. Under the covers thes call just resolves to</p>
<pre><code>if (typeof(int).IsInstanceOfType(0))
</code></pre> |
2,339,142 | How to break out of multiple loops at once in C#? | <p>What if I have nested loops, and I want to break out of all of them at once?</p>
<pre><code>while (true) {
// ...
while (shouldCont) {
// ...
while (shouldGo) {
// ...
if (timeToStop) {
break; // Break out of everything?
}
}
}
}
</code></pre>
<p>In PHP, <code>break</code> takes an argument for the number of loops to break out of. Can something like this be done in C#?</p>
<p>What about something hideous, like <code>goto</code>?</p>
<pre><code>// In the innermost loop
goto BREAK
// ...
BREAK: break; break; break;
</code></pre> | 2,339,152 | 5 | 6 | null | 2010-02-26 02:29:51.607 UTC | 7 | 2022-07-05 13:55:23.157 UTC | 2015-08-21 18:29:40.853 UTC | null | 63,550 | null | 147,601 | null | 1 | 75 | c#|loops|goto|break | 55,389 | <p>Extract your nested loops into a function and then you can use return to get out of the loop from anywhere, rather than break.</p> |
2,386,542 | resuming an activity from a notification | <p>I have a notification in the status bar for my app:</p>
<pre><code> Notification notification = new Notification(R.drawable.icon, null, System.currentTimeMillis());
Intent notificationIntent = new Intent(this.parent, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this.parent, 0, notificationIntent, 0);
...
notification.flags = Notification.FLAG_ONGOING_EVENT;
mNotificationManager.notify(NOTIFICATION_ID, notification);
</code></pre>
<p>The problem with this is that when you press the home button from the app (pushing it to the background) then press on the notification in the list accessed from the status bar, it starts a fresh copy of the activity. All I want to do is resume the app (like when you longpress the home button and press on the app's icon). Is there a way of creating an Intent to do this?</p> | 5,631,993 | 7 | 1 | null | 2010-03-05 12:11:28.25 UTC | 2 | 2019-09-25 04:31:08.97 UTC | null | null | null | null | 284,527 | null | 1 | 39 | java|android|android-activity|notifications | 16,058 | <p>I've solved this issue by changing the <code>launchMode</code> of my activity to <code>singleTask</code> in the androidManifest.xml file. </p>
<p>The default value for this property is <code>standard</code>, which allows any number of instances to run. </p>
<blockquote>
<p>"singleTask" and "singleInstance" activities can only begin a task. They are always at the root of the activity stack. Moreover, the device can hold only one instance of the activity at a time — only one such task. [...]</p>
<p>The "singleTask" and "singleInstance" modes also differ from each other in only one respect: A "singleTask" activity allows other activities to be part of its task. It's always at the root of its task, but other activities (necessarily "standard" and "singleTop" activities) can be launched into that task. A "singleInstance" activity, on the other hand, permits no other activities to be part of its task. It's the only activity in the task. If it starts another activity, that activity is assigned to a different task — as if FLAG_ACTIVITY_NEW_TASK was in the intent. </p>
</blockquote>
<p>you can find a detailed explanation in the <a href="http://developer.android.com/guide/topics/manifest/activity-element.html#lmode">Android Developers' Guide</a></p>
<p>I hope this helps</p> |
2,578,116 | How can I test if line is empty in shell script? | <p>I have a shell script like this: </p>
<pre><code>cat file | while read line
do
# run some commands using $line
done
</code></pre>
<p>Now I need to check if the line contains any non-whitespace character ([\n\t ]), and if not, skip it.
How can I do this?</p> | 2,578,289 | 7 | 0 | null | 2010-04-05 11:33:26.13 UTC | 3 | 2022-01-15 13:49:02.103 UTC | 2010-04-05 11:45:49.61 UTC | null | 275,088 | null | 275,088 | null | 1 | 39 | bash|shell|sh | 94,635 | <p>Since <code>read</code> reads whitespace-delimited fields by default, a line containing only whitespace should result in the empty string being assigned to the variable, so you should be able to skip empty lines with just:</p>
<pre><code>[ -z "$line" ] && continue
</code></pre> |
2,679,524 | Block direct access to a file over http but allow php script access | <p>I'm loading my files (pdf, doc, flv, etc) into a buffer and serving them to my users with a script. I need my script to be able to access the file but not allow direct access to it. Whats the best way to achieve this? Should I be doing something with my permissions or locking out the directory with .htaccess?</p> | 2,679,597 | 7 | 1 | null | 2010-04-21 00:04:57.923 UTC | 35 | 2019-09-15 11:35:55.057 UTC | null | null | null | null | 207,318 | null | 1 | 76 | php|apache|permissions | 139,615 | <p>The safest way is to put the files you want kept to yourself outside of the web root directory, like Damien suggested. This works because the web server follows local file system privileges, not its own privileges.</p>
<p>However, there are a lot of hosting companies that only give you access to the web root. To still prevent HTTP requests to the files, put them into a directory by themselves with a .htaccess file that blocks all communication. For example,</p>
<pre><code>Order deny,allow
Deny from all
</code></pre>
<p>Your web server, and therefore your server side language, will still be able to read them because the directory's local permissions allow the web server to read and execute the files.</p> |
2,341,660 | How to compare nullable types? | <p>I have a few places where I need to compare 2 (nullable) values, to see if they're the same.</p>
<p>I think there should be something in the framework to support this, but can't find anything, so instead have the following:</p>
<pre><code>public static bool IsDifferentTo(this bool? x, bool? y)
{
return (x.HasValue != y.HasValue) ? true : x.HasValue && x.Value != y.Value;
}
</code></pre>
<p>Then, within code I have <code>if (x.IsDifferentTo(y)) ...</code></p>
<p>I then have similar methods for nullable ints, nullable doubles etc.</p>
<p>Is there not an easier way to see if two nullable types are the same?</p>
<p><strong>Update:</strong></p>
<p>Turns out that the reason this method existed was because the code has been converted from VB.Net, where Nothing = Nothing returns false (compare to C# where null == null returns true). The VB.Net code should have used <code>.Equals...</code> instead.</p> | 2,341,691 | 8 | 1 | null | 2010-02-26 12:53:45.667 UTC | 10 | 2022-04-25 15:18:32.147 UTC | 2010-04-01 01:59:57.533 UTC | null | 164,901 | null | 209,578 | null | 1 | 74 | c#|extension-methods|nullable | 55,070 | <p>C# supports "lifted" operators, so if the type (<code>bool?</code> in this case) is known at compile you should just be able to use:</p>
<pre><code>return x != y;
</code></pre>
<p>If you need generics, then <code>EqualityComparer<T>.Default</code> is your friend:</p>
<pre><code>return !EqualityComparer<T>.Default.Equals(x,y);
</code></pre>
<p>Note, however, that both of these approaches use the "<code>null == null</code>" approach (contrast to ANSI SQL). If you need "<code>null != null</code>" then you'll have to test that separately:</p>
<pre><code>return x == null || x != y;
</code></pre> |
2,470,072 | Circular gradient in android | <p>I'm trying to make a gradient that emits from the middle of the screen in white, and turns to black as it moves toward the edges of the screen.</p>
<p>As I make a "normal" gradient like this, I have been experimenting with different shapes:</p>
<pre><code><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#E9E9E9" android:endColor="#D4D4D4"
android:angle="270"/>
</shape>
</code></pre>
<p>When using the "oval"-shape I at least got a round shape, but there were no gradient effect. How can I achieve this?'</p> | 2,470,289 | 8 | 0 | null | 2010-03-18 13:24:18.84 UTC | 36 | 2021-02-21 14:03:37.553 UTC | 2017-07-17 04:06:33.363 UTC | null | 3,681,880 | null | 249,871 | null | 1 | 122 | android|gradient | 119,129 | <p>You can get a circular gradient using <code>android:type="radial"</code>:</p>
<pre><code><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:type="radial" android:gradientRadius="250dp"
android:startColor="#E9E9E9" android:endColor="#D4D4D4" />
</shape>
</code></pre> |
2,766,233 | What is the C runtime library? | <p>What actually is a C runtime library and what is it used for? I was searching, Googling like a devil, but I couldn't find anything better than Microsoft's: "The Microsoft run-time library provides routines for programming for the Microsoft Windows operating system. These routines automate many common programming tasks that are not provided by the C and C++ languages."</p>
<p>OK, I get that, but for example, what is in <code>libcmt.lib</code>? What does it do? I thought that the C standard library was a part of C compiler. So is <code>libcmt.lib</code> Windows' implementation of C standard library functions to work under win32?</p> | 2,766,421 | 8 | 1 | null | 2010-05-04 14:37:52.727 UTC | 81 | 2020-09-25 15:38:40.367 UTC | 2017-02-15 10:40:51.253 UTC | null | 4,627,134 | null | 307,797 | null | 1 | 196 | c|runtime | 91,971 | <p>Yes, libcmt is (one of several) implementations of the C standard library provided with Microsoft's compiler. They provide both "debug" and "release" versions of three basic types of libraries: <strong>single-threaded</strong> (always statically linked), <strong>multi-threaded statically linked</strong>, and <strong>multi-threaded dynamically linked</strong> (though, depending on the compiler version you're using, some of those may not be present).</p>
<p>So, in the name "libcmt", "libc" is the (more or less) traditional name for the C library. The "mt" means "multi-threaded". A "debug" version would have a "d" added to the end, giving "libcmtd".</p>
<p>As far as what functions it includes, the C standard (part 7, if you happen to care) defines a set of functions a conforming (hosted) implementation must supply. Most vendors (including Microsoft) add various other functions themselves (for compatibility, to provide capabilities the standard functions don't address, etc.) In most cases, it will also contain quite a few "internal" functions that are used by the compiler but not normally by the end user.</p>
<p>The runtime library is basically a collection of the implementations of those functions in one big file (or a few big files--e.g., on UNIX the floating point functions are traditionally stored separately from the rest). That big file is typically something on the same general order as a zip file, but without any compression, so it's basically just some little files collected together and stored together into one bigger file. The archive will usually contain at least some indexing to make it relatively fast/easy to find and extract the data from the internal files. At least at times, Microsoft has used a library format with an "extended" index the linker can use to find which functions are implemented in which of the sub-files, so it can find and link in the parts it needs faster (but that's purely an optimization, not a requirement).</p>
<p>If you want to get a complete list of the functions in "libcmt" (to use your example) you could open one of the Visual Studio command prompts (under "Visual Studio Tools", normally), switch to the directory where your libraries were installed, and type something like: <code>lib -list libcmt.lib</code> and it'll generate a (<em>long</em>) list of the names of all the object files in that library. Those don't always correspond <em>directly</em> to the names of the functions, but will generally give an idea. If you want to look at a particular object file, you can use <code>lib -extract</code> to extract one of those object files, then use <code>dumpbin /symbols <object file name></code> to find what function(s) is/are in that particular object file.</p> |
23,691,645 | Enabling horizontal scroll in flexbox | <p>I am new to flexbox, and I am trying to make a horizontal scrolling website. The idea is to show the first item as 100% height and width, like covering the screen with the remaining items to the right side, which will only be shown when I scroll.</p>
<p>Here is an image of what I am trying to do:
<img src="https://i.stack.imgur.com/3TiOu.jpg" alt="enter image description here"></p>
<p><strong>I tried setting the first item to 100% width, but it's still fitted just like other items.</strong></p>
<p>Here is my CSS code:</p>
<pre><code> body
{
margin: 0;
padding: 0;
background-color: rgb(242, 242, 242);
}
.flex-container
{
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
flex-flow:row;
height:100%;
position:absolute;
width:100%;
/*flex-wrap:wrap;*/
}
.box
{
padding: 20px;
color:white;
font-size:22px;
background-color: crimson;
border:1px solid white;
flex:1;
-webkit-flex:1;
text-align:center;
min-width:200px;
}
.splash
{
background-image: url(1.jpg);
width:100%;
background-size:cover;
background-position:50% 50%;
background-repeat: no-repeat;
transition: all 0.6s ease;
flex:10;
-webkit-flex:10;
}
.flex1:hover
{
flex:4;
-webkit-flex:4;
}
</code></pre>
<p>And my HTML code:</p>
<pre><code><div class="flex-container">
<div class="box splash">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
</div>
</code></pre> | 23,706,151 | 4 | 0 | null | 2014-05-16 02:20:34.333 UTC | 16 | 2021-10-28 13:03:32.033 UTC | 2014-05-17 00:01:06.06 UTC | null | 1,427,098 | null | 1,960,667 | null | 1 | 64 | css|flexbox | 88,284 | <p>Flex items have "flex-shrink: 1" by default. If you want the first item to fill the container and force the others to overflow (as it sounds like you do), then you need to set "flex-shrink: 0" on it.</p>
<p>The best way to do this is via the "flex" shorthand, which you're already using to give it "flex: 10".</p>
<p>Just replace that with <code>flex: 10 0 auto</code> -- the '0' there gives it a flex-shrink of 0, which prevents it from shrinking below the <code>width:100%</code> that you've given it.</p>
<p>Perhaps better: just give it <code>flex: none</code>, since I don't think you're really getting any benefit from the "10" there, since there's no free space to distribute anyway, so the "10" is giving you 10 useless shares of nothing.</p>
<p>So that makes your 'splash' rule into this:</p>
<pre class="lang-css prettyprint-override"><code>.splash {
background-image: url(1.jpg);
width:100%;
background-size:cover;
background-position:50% 50%;
background-repeat: no-repeat;
transition: all 0.6s ease;
flex:none;
}
</code></pre>
<p>Here's a fiddle with this change (but otherwise using your provided CSS/HTML). This renders like your mock-up in Firefox Nightly and Chrome:
<a href="http://jsfiddle.net/EVAXW/" rel="noreferrer">http://jsfiddle.net/EVAXW/</a></p> |
50,935,730 | How do I disable HTTPS in ASP.NET Core 2.1 + Kestrel? | <p>So it appears with the advent of ASP.NET Core 2.1, Kestrel now automatically creates an HTTPS endpoint along side the HTTP one, and default project templates are setup to redirect from HTTP to HTTPS (which is easy enough to undo).</p>
<p>However my question is... how can I disable HTTPS entirely for my project. I've read through the docs and played with a variety of config settings for HTTPS but nothing I do seems to allow me to turn it off and just run an HTTP project.</p>
<p>Am I crazy or just missing something. I would expect this to be super easy to do.</p> | 51,344,917 | 11 | 0 | null | 2018-06-19 19:34:45.173 UTC | 12 | 2022-02-08 13:05:21.683 UTC | 2020-12-31 18:18:35.657 UTC | null | 3,241,243 | null | 3,022,291 | null | 1 | 111 | https|kestrel-http-server|asp.net-core-2.1 | 114,843 | <p>Turns out the proper way to achieve what I wanted to do, was to specifically configure Kestrel with .UseKestrel() and simply specify a single address, like this:</p>
<pre><code> WebHost.CreateDefaultBuilder(args)
.UseKestrel(options => {
if (context.Configuration[WebHostDefaults.EnvironmentKey] == Environments.Development) {
options.Listen(IPAddress.Loopback, 5080); //HTTP port
}
})
.UseStartup<Startup>();
</code></pre>
<p>in effect overriding the default setup, and displaying this warning when Kestel starts:</p>
<pre><code>warn: Microsoft.AspNetCore.Server.Kestrel[0]
Overriding address(es) 'https://localhost:5001, http://localhost:5000'. Binding to endpoints defined in UseKestrel() instead.
</code></pre>
<p>Note the check for development environment; in production the default ports are different (80) and without HTTPS.</p>
<p>if a second address is specified it will assume that address is to be secured with the built-in developer cert, as such:</p>
<pre><code> WebHost.CreateDefaultBuilder(args)
.UseKestrel(options => {
options.Listen(IPAddress.Loopback, 5080); //HTTP port
options.Listen(IPAddress.Loopback, 5443); //HTTPS port
})
.UseStartup<Startup>();
</code></pre>
<p>you may of course specifically secure your SSL address as described here:</p>
<p><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.1&tabs=aspnetcore2x" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.1&tabs=aspnetcore2x</a></p>
<p>which is necessary for production setups.</p> |
50,708,772 | how to emit a value with a click event in vue.js | <p>I am following Vuejs documentation and trying to emit a value with click event.</p>
<p>The code follows:</p>
<p><strong>Vue Template:</strong></p>
<pre><code><div id="app">
<div class="container">
<div class="col-lg-offset-4 col-lg-4">
<sidebar v-on:incrementBtn="increment += $event"></sidebar>
<p>{{ increment }}</p>
</div>
</div>
</div>
</code></pre>
<p><strong>Vue instances:</strong></p>
<pre><code> Vue.component('sidebar',{
template:`
<div>
<button class="btn btn-info" v-on:click="$emit('incrementBtn', 1)">Increment on click</button>
</div>
`,
});
new Vue ({
el:'#app',
data:{
increment:0
}
});
</code></pre> | 50,708,894 | 1 | 0 | null | 2018-06-05 20:54:11.923 UTC | 1 | 2022-07-15 19:57:10.043 UTC | 2019-10-08 08:25:28.53 UTC | null | 2,957,890 | null | 6,836,495 | null | 1 | 16 | vue.js|vue-component | 44,276 | <p>Check <a href="https://v2.vuejs.org/v2/guide/components-custom-events.html#Event-Names" rel="nofollow noreferrer">Vue Custom Event</a>, Vue always recommends using <strong>kebab-case</strong> for event names.</p>
<p>And as above Vue guide said:</p>
<blockquote>
<p>Unlike components and props, event names don’t provide any automatic
case transformation. Instead, the name of an emitted event must
exactly match the name used to listen to that event.</p>
</blockquote>
<p>And</p>
<blockquote>
<p>Additionally, v-on event listeners inside DOM templates will be
automatically transformed to lowercase (due to HTML’s
case-insensitivity), <strong>so v-on:myEvent would become v-on:myevent – making myEvent impossible to listen to</strong>.</p>
</blockquote>
<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>Vue.component('sidebar',{
template:`
<div>
<button class="btn btn-info" v-on:click="$emit('increment-btn', 1)">Increment on click</button>
</div>
`
})
new Vue ({
el:'#app',
data () {
return {
increment:0
}
}
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div class="container">
<div class="col-lg-offset-4 col-lg-4">
<sidebar v-on:increment-btn="increment += $event"></sidebar>
<p>{{ increment }}</p>
</div>
</div>
</div></code></pre>
</div>
</div>
</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.