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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
14,532,230 | Analytics and Mining of data sitting on Cassandra | <p>We have a lot of user interaction data from various websites stored in Cassandra such as cookies, page-visits, ads-viewed, ads-clicked, etc.. that we would like to do reporting on. Our current Cassandra schema supports basic reporting and querying. However we also would like to build large queries that would typically involve Joins on large Column Families (containing millions of rows).</p>
<p>What approach is best suited for this? One possibility is to extract data out to a relational database such as mySQL and do data mining there. Alternate could be to attempt at use hadoop with hive or pig to run map reduce queries for this purpose? I must admit I have zero experience with the latter.</p>
<p>Anyone have experience of performance differences in one one vs the other? Would you run map reduce queries on a live Cassandra production instance or on a backup copy to prevent query load from affecting write performance?</p> | 14,555,791 | 2 | 0 | null | 2013-01-25 23:59:37.66 UTC | 9 | 2013-01-28 05:09:28.72 UTC | 2013-01-26 01:24:04.513 UTC | null | 1,293,955 | null | 1,293,955 | null | 1 | 14 | hadoop|mapreduce|cassandra|analytics | 8,253 | <p>Disclosure: I'm an engineer at DataStax.</p>
<p>In addition to Charles' suggestions, you might want to look into <a href="http://www.datastax.com/products/enterprise">DataStax Enterprise</a> (DSE), which offers a nice integration of Cassandra with Hadoop, Hive, Pig, and Mahout.</p>
<p>As Charles mentioned, you don't want to run your analytics directly against Cassandra nodes that are handling your real-time application needs because they can have a substantial impact on performance. To avoid this, DSE allows you to devote a portion of your cluster strictly to analytics by using multiple virtual "datacenters" (in the NetworkToplogyStrategy sense of the term). Queries performed as part of a Hadoop job will only impact those nodes, essentially leaving your normal Cassandra nodes unaffected. Additionally, you can scale each portion of the cluster up or down separately based on your performance needs.</p>
<p>There are a couple of upsides to the DSE approach. The first is that you don't need to perform any ETL prior to processing your data; Cassandra's normal replication mechanisms keep the nodes devoted to analytics up to date. Second, you don't need an external Hadoop cluster. DSE includes a drop-in replacement for HDFS called CFS (CassandraFS), so all source data, intermediate results, and final results from a Hadoop job can be stored in the Cassandra cluster.</p> |
49,423,355 | RxJS skipWhile vs filter | <p>What is the difference between skipWhile and filter operators?</p>
<pre><code>const source = interval(1000);
const example = source.pipe(skipWhile(val => val < 5));
const subscribe = example.subscribe(val => console.log(val));
const source = interval(1000);
const example = source.pipe(filter(val => val > 5));
const subscribe = example.subscribe(val => console.log(val));
</code></pre> | 49,423,487 | 3 | 0 | null | 2018-03-22 07:59:50.463 UTC | 3 | 2022-02-23 23:23:18.88 UTC | null | null | null | null | 7,330,592 | null | 1 | 34 | javascript|rxjs | 10,848 | <p>The difference is that upon its expression evaluating to <code>false</code>, skipWhile changes over to <strong>mirroring</strong> its source observable - so it will cease to filter out any further values.</p>
<p>For example:</p>
<pre><code>Observable.from([1,2,3,4,5])
.pipe(filter(val => val % 2 == 0)) // filters out odd numbers
.subscribe(val => console.log(val)); // emits 2,4
Observable.from([1,2,3,4,5])
.pipe(skipWhile(val => val % 2 == 1)) // filters odd numbers until an even number comes along
.subscribe(val => console.log(val)); // emits 2,3,4,5
</code></pre> |
35,090,883 | Remove all of x axis labels in ggplot | <p>I need to remove everything on the x-axis including the labels and tick marks so that only the y-axis is labeled. How would I do this?</p>
<p>In the image below I would like 'clarity' and all of the tick marks and labels removed so that just the axis line is there.</p>
<p><strong>Sample ggplot</strong></p>
<pre><code>data(diamonds)
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))
</code></pre>
<p><strong>ggplot Chart:</strong></p>
<p><a href="https://i.stack.imgur.com/PnUYc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PnUYc.png" alt="enter image description here"></a></p>
<p><strong>Desired chart:</strong></p>
<p><a href="https://i.stack.imgur.com/HEwbC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HEwbC.png" alt="enter image description here"></a></p> | 35,090,981 | 1 | 0 | null | 2016-01-29 17:50:22.99 UTC | 57 | 2018-05-31 04:34:07.313 UTC | 2018-05-31 04:34:07.313 UTC | null | 4,104,728 | null | 4,104,728 | null | 1 | 304 | r|ggplot2 | 631,838 | <p>You have to set to <code>element_blank()</code> in <code>theme()</code> elements you need to remove</p>
<pre><code>ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
</code></pre> |
42,922,023 | How to filter GitHub PRs with specific merge date? | <p>I use the below filter to get PRs closed above 2017-03-19; but, is there a way to filter with a specific date.</p>
<pre><code>is:pr is:closed merged:>=2017-03-19 base:master sort:updated-desc
</code></pre>
<p><a href="https://i.stack.imgur.com/yLNNR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yLNNR.png" alt="enter image description here"></a></p>
<p>The below fails:</p>
<pre><code>is:pr is:closed merged:=2017-03-19 base:master sort:updated-desc
</code></pre> | 42,929,781 | 1 | 0 | null | 2017-03-21 08:41:10.5 UTC | 5 | 2022-02-26 04:25:26.187 UTC | null | null | null | null | 1,482,709 | null | 1 | 40 | github | 17,155 | <p>Yes, you can do so by filtering as follows:</p>
<pre><code>is:pr is:closed merged:2017-03-19..2017-03-19 base:master sort:updated-desc
</code></pre>
<p>For more information concerning searching issues and pull requests in GitHub see <a href="https://help.github.com/articles/searching-issues/#search-based-on-when-an-issue-or-pull-request-was-created-or-last-updated" rel="noreferrer">Searching issues documentation</a>.</p> |
50,165,953 | Python Dataframes: Describing a single column | <p>Is there a way I can apply df.describe() to just an isolated column in a DataFrame.</p>
<p>For example if I have several columns and I use df.describe() - it returns and describes all the columns. From research, I understand I can add the following:</p>
<p>"A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit numpy.number. To limit it instead to object columns submit the numpy.object data type. <strong>Strings can also be used in the style of select_dtypes (e.g. df.describe(include=['O'])). To select pandas categorical columns, use 'category'"</strong></p>
<p>However I don't quite know how to write this out in python code.
Thanks in advance.</p> | 50,274,029 | 5 | 1 | null | 2018-05-04 01:38:48.57 UTC | 5 | 2021-05-03 05:53:10.057 UTC | 2018-05-04 01:59:03.94 UTC | null | 9,650,720 | null | 9,718,965 | null | 1 | 18 | python|dataframe|describe | 62,838 | <p>Just add column name in square braquets:</p>
<pre><code>df['column_name'].describe()
</code></pre>
<p><strong>Example:</strong></p>
<p><a href="https://i.stack.imgur.com/RvS4V.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RvS4V.png" alt="enter image description here" /></a></p>
<p>To get a <strong>single column</strong>:</p>
<pre><code>df['1']
</code></pre>
<p>To get <strong>several columns</strong>:</p>
<pre><code>df[['1','2']]
</code></pre>
<p>To get a <strong>single row</strong> by name:</p>
<pre><code>df.loc['B']
</code></pre>
<p>or by index:</p>
<pre><code>df.iloc[o]
</code></pre>
<p>To get a <strong>specific field</strong>:</p>
<pre><code>df['1']['C']
</code></pre> |
36,248,652 | Cleanest, most efficient syntax to perform DataFrame self-join in Spark | <p>In standard SQL, when you join a table to itself, you can create aliases for the tables to keep track of which columns you are referring to:</p>
<pre><code>SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;
</code></pre>
<p>There are two ways I can think of to achieve the same thing using the Spark <code>DataFrame</code> API:</p>
<p><strong>Solution #1: Rename the columns</strong></p>
<p>There are a couple of different methods for this in answer to <strong><a href="https://stackoverflow.com/questions/36206590/how-to-do-select-with-column-name-that-appears-twice-in-dataframe">this question</a></strong>. This one just renames all the columns with a specific suffix:</p>
<pre><code>df.toDF(df.columns.map(_ + "_R"):_*)
</code></pre>
<p>For example you can do:</p>
<pre><code>df.join(df.toDF(df.columns.map(_ + "_R"):_*), $"common_field" === $"common_field_R")
</code></pre>
<p><strong>Solution #2: Copy the reference to the <code>DataFrame</code></strong></p>
<p>Another simple solution is to just do this:</p>
<pre><code>val df: DataFrame = ....
val df_right = df
df.join(df_right, df("common_field") === df_right("common_field"))
</code></pre>
<p>Both of these solutions work, and I could see each being useful in certain situations. Are there any internal differences between the two I should be aware of?</p> | 36,250,953 | 1 | 0 | null | 2016-03-27 14:46:10.567 UTC | 9 | 2019-01-06 14:34:15.527 UTC | 2019-01-06 14:34:15.527 UTC | null | -1 | null | 4,856,939 | null | 1 | 42 | apache-spark|dataframe|apache-spark-sql | 37,409 | <p>There are at least two different ways you can approach this either by aliasing:</p>
<pre class="lang-scala prettyprint-override"><code>df.as("df1").join(df.as("df2"), $"df1.foo" === $"df2.foo")
</code></pre>
<p>or using name-based equality joins:</p>
<pre class="lang-scala prettyprint-override"><code>// Note that it will result in ambiguous column names
// so using aliases here could be a good idea as well.
// df.as("df1").join(df.as("df2"), Seq("foo"))
df.join(df, Seq("foo"))
</code></pre>
<p>In general column renaming, while the ugliest, is the safest practice across all the versions. There have been a few bugs related to column resolution (<a href="https://stackoverflow.com/q/36131942/1560062">we found one on SO</a> not so long ago) and some details may differ between parsers (<code>HiveContext</code> / standard <code>SQLContext</code>) if you use raw expressions.</p>
<p>Personally I prefer using aliases because their resemblance to an idiomatic SQL and ability to use outside the scope of a specific <code>DataFrame</code> objects.</p>
<p>Regarding performance unless you're interested in close-to-real-time processing there should be no performance difference whatsoever. All of these should generate the same execution plan.</p> |
31,719,451 | install HDF5 and pytables in ubuntu | <p>I am trying to install <code>tables</code> package in Ubuntu 14.04 but sems like it is complaining.</p>
<p>I am trying to install it using PyCharm and its package installer, however seems like it is complaining about <code>HDF5</code> package.</p>
<p>However, seems like I cannnot find any <code>hdf5</code> package to install before <code>tables</code>.</p>
<p>Could anyone explain the procedure to follow?</p> | 31,719,735 | 4 | 0 | null | 2015-07-30 09:02:30.41 UTC | 4 | 2018-09-17 05:42:28.273 UTC | null | null | null | null | 2,919,052 | null | 1 | 28 | python|ubuntu-14.04|hdf5|pytables | 80,503 | <p>Try to install libhdf5-7 and python-tables via apt</p> |
22,631,863 | Setting up sublimetext 3 as git commit text editor | <p>I'm having trouble setting up sublime as my git commit message editor.</p>
<p>Using:</p>
<pre><code>git config --global core.editor "subl"
</code></pre>
<p>Error:
error: cannot run subl: No such file or directory
error: unable to start editor 'subl'
Please supply the message using either -m or -F option.</p>
<p>subl work perfectly otherwise.</p> | 22,632,139 | 7 | 0 | null | 2014-03-25 10:34:33.97 UTC | 23 | 2022-05-07 13:48:30.783 UTC | 2019-03-03 18:34:14.067 UTC | null | 1,696,030 | null | 580,187 | null | 1 | 65 | git|sublimetext3 | 35,411 | <p>You can solve this by putting in a full path</p>
<pre><code>git config --global core.editor "/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl -n -w"
</code></pre>
<p>Source: <a href="http://www.sublimetext.com/docs/3/osx_command_line.html" rel="noreferrer">OS X Command Line</a></p>
<p><strong>EDIT</strong>: <em>If the name of the app is not <code>Sublime Text.app</code> you will want to replace that with the correct name.</em></p> |
27,317,296 | How to enable/disable bootstrap selectpicker by ickeck checkbox | <p>There are <code>selectpicker</code> beside <code>checkbox</code>. I want if checkbox is checked, selectpicker will be enable, if unchecked, selectpicker will be disable.
I wrote this which was not working ( <a href="http://jsfiddle.net/learner73/y6g028ay/">Here is the fiddle</a> ):</p>
<pre><code>$('.checkBox').on('ifChecked', function(event) {
$(this).parents('.clearfix').find('.selectpicker').removeAttr('disabled');
});
$('.checkBox').on('ifUnchecked', function(event) {
$(this).parents('.clearfix').find('.selectpicker').attr('disabled');
});
</code></pre> | 27,317,528 | 6 | 0 | null | 2014-12-05 13:44:56.07 UTC | 5 | 2022-07-13 20:18:55.98 UTC | 2014-12-05 13:53:46.737 UTC | null | 1,896,653 | null | 1,896,653 | null | 1 | 26 | jquery|bootstrap-select|icheck | 71,999 | <p>You should refresh the selectpicker once the change is done</p>
<p>here is a working <a href="http://jsfiddle.net/Cerlin/y6g028ay/1/" rel="noreferrer">fiddle</a></p>
<p>Code to refresh the UI is</p>
<pre><code>$('.selectpicker').selectpicker('refresh');
</code></pre>
<p>for more information refer the <a href="http://silviomoreto.github.io/bootstrap-select/" rel="noreferrer">DOCS</a></p>
<p>One more mistake i have found is, to disable you have to use</p>
<pre><code>attr('disabled',true)
</code></pre>
<p>not </p>
<pre><code>attr('disabled')
</code></pre> |
2,342,070 | How to add more details in MKAnnotation in iOS | <p>I want to add more details in MKAnnotation like location title, description, date, location name. So it will be four lines that are needed. But I found that only 2 parameters can be passed to MKAnnotation which are title and subtitle. How can I add more details on the map? Plz help me..Thanks in advance.</p> | 2,342,701 | 1 | 1 | null | 2010-02-26 13:57:08.15 UTC | 11 | 2014-01-31 17:15:25.53 UTC | 2011-10-22 09:27:23.5 UTC | null | 197,210 | null | 409,631 | null | 1 | 20 | iphone|objective-c|ios|mkannotation | 28,991 | <p>Take a look at creating a custom <code>MKAnnotationView</code> object... it is basically a <code>UIView</code> that is tailored for map annotations. In that object you could have your 4 custom labels.</p>
<p>In your <code>MKMapViewDelegate</code> class, you implement the <code>viewForAnnotation</code> method:</p>
<pre><code>- (CustomMapAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
CustomMapAnnotationView *annotationView = nil;
// determine the type of annotation, and produce the correct type of annotation view for it.
CustomMapAnnotation* myAnnotation = (CustomMapAnnotation *)annotation;
NSString* identifier = @"CustomMapAnnotation";
CustomMapAnnotationView *newAnnotationView = (CustomMapAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if(nil == newAnnotationView) {
newAnnotationView = [[[CustomMapAnnotationView alloc] initWithAnnotation:myAnnotation reuseIdentifier:identifier] autorelease];
}
annotationView = newAnnotationView;
[annotationView setEnabled:YES];
[annotationView setCanShowCallout:YES];
return annotationView;
}
</code></pre>
<p>And that will display your custom view where ever you have an annotation... if you want a step by step tutorial, <a href="http://icodeblog.com/2009/12/21/introduction-to-mapkit-in-iphone-os-3-0/" rel="nofollow noreferrer">check out this video</a>.</p>
<p>hope this helps</p>
<p><strong>EDIT</strong></p>
<p>I actually just found a new <a href="http://developer.apple.com/iphone/library/samplecode/WeatherMap/index.html" rel="nofollow noreferrer">Maps example</a> on the apple dev site... has all the source code you need to go through. They are also using a custom <code>MKAnnotationView</code> called <code>WeatherAnnotationView</code></p> |
2,662,927 | Android SQLite: nullColumnHack parameter in insert/replace methods | <p>The Android SDK has some convenience methods for manipulating data with SQLite. However both the <a href="http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert%28java.lang.String,%20java.lang.String,%20android.content.ContentValues%29" rel="noreferrer">insert</a> and <a href="http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#replace%28java.lang.String,%20java.lang.String,%20android.content.ContentValues%29" rel="noreferrer">replace</a> methods use some <code>nullColumnHack</code> parameter which usage I don't understand.</p>
<p>The documentation explains it with the following, but what if a table has multiple columns that allow <code>NULL</code>? I really don't get it :/</p>
<blockquote>
<p>SQL doesn't allow inserting a completely empty row, so if initialValues is empty, this column [<em>/row for replace</em>] will explicitly be assigned a <code>NULL</code> value.</p>
</blockquote> | 2,663,620 | 1 | 0 | null | 2010-04-18 16:17:27.473 UTC | 28 | 2015-06-27 12:18:04.98 UTC | 2015-06-27 12:18:04.98 UTC | null | 635,549 | null | 216,074 | null | 1 | 96 | android|sqlite | 27,370 | <p>Let's suppose you have a table named <code>foo</code> where all columns either allow <code>NULL</code> values or have defaults.</p>
<p>In some SQL implementations, this would be valid SQL:</p>
<pre><code>INSERT INTO foo;
</code></pre>
<p>That's not valid in SQLite. You have to have at least one column specified:</p>
<pre><code>INSERT INTO foo (somecol) VALUES (NULL);
</code></pre>
<p>Hence, in the case where you pass an empty <code>ContentValues</code> to <code>insert()</code>, Android and SQLite need some column that is safe to assign <code>NULL</code> to. If you have several such columns to choose from, pick one via the selection mechanism of your choice: roll of the dice, Magic 8-Ball(TM), coin flip, cubicle mate flip, etc.</p>
<p>Personally, I'd've just made it illegal to pass an empty <code>ContentValues</code> to <code>insert()</code>, but they didn't ask me... :-)</p> |
34,217,728 | Flask-restful API Authorization. Access current_identity inside decorator | <p>I use flask-restful to create my APIs. I have used <code>flask-jwt</code> for enabling authentication based on <code>JWT</code>. Now I need to do authorization.</p>
<p>I have tried putting my authorization decorator. </p>
<p><strong>test.py (/test api)</strong></p>
<pre><code>from flask_restful import Resource
from flask_jwt import jwt_required
from authorization_helper import authorized_api_user_type
class Test(Resource):
decorators = [jwt_required(), authorized_api_user_type()]
def get(self):
return 'GET OK'
def post(self):
return 'POST OK'
</code></pre>
<p>Basically to handle the basic authorization, I need to access <code>current_identity</code> and check it's type. Then based on it's type I am gonna decide whether the user is authorized to access the api / resources.</p>
<p>But <code>current_identity</code> appears to be <code>empty</code> in that decorator. So to get it indirectly, I had to see the code of <code>jwt_handler</code> and do the things done there. </p>
<p><strong>authorization_helper.py</strong></p>
<pre><code>from functools import wraps
from flask_jwt import _jwt, JWTError
import jwt
from models import Teacher, Student
def authorized_api_user_type(realm=None, user_type='teacher'):
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
token = _jwt.request_callback()
if token is None:
raise JWTError('Authorization Required', 'Request does not contain an access token',
headers={'WWW-Authenticate': 'JWT realm="%s"' % realm})
try:
payload = _jwt.jwt_decode_callback(token)
except jwt.InvalidTokenError as e:
raise JWTError('Invalid token', str(e))
identity = _jwt.identity_callback(payload)
if user_type == 'student' and isinstance(identity, Student):
return fn(*args, **kwargs)
elif user_type == 'teacher' and isinstance(identity, Teacher):
return fn(*args, **kwargs)
# NOTE - By default JWTError throws 401. We needed 404. Hence status_code=404
raise JWTError('Unauthorized',
'You are unauthorized to request the api or access the resource',
status_code=404)
return decorator
return wrapper
</code></pre>
<p>Why can't I just access <code>current_identity</code> in my <code>authorized_api_user_type</code> decorator? What is the RIGHT way of doing authorization in flask-restful?</p> | 36,169,320 | 3 | 0 | null | 2015-12-11 06:54:01.903 UTC | 11 | 2019-06-25 01:55:26.813 UTC | 2019-06-25 01:55:26.813 UTC | null | 1,637,867 | null | 1,637,867 | null | 1 | 27 | python|flask|flask-restful|flask-jwt | 21,104 | <p>Here is the combination of quickstarts of both <code>Flask-JWT</code> and <code>Flask-Restful</code>. </p>
<pre><code>from flask import Flask
from flask_restful import Resource, Api, abort
from functools import wraps
app = Flask(__name__)
api = Api(app)
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp
class User(object):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def __str__(self):
return "User(id='%s')" % self.id
users = [
User(1, 'user1', 'abcxyz'),
User(2, 'user2', 'abcxyz'),
]
username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
def authenticate(username, password):
user = username_table.get(username, None)
if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
return user
def identity(payload):
user_id = payload['identity']
return userid_table.get(user_id, None)
app.config['SECRET_KEY'] = 'super-secret'
jwt = JWT(app, authenticate, identity)
def checkuser(func):
@wraps(func)
def wrapper(*args, **kwargs):
if current_identity.username == 'user1':
return func(*args, **kwargs)
return abort(401)
return wrapper
class HelloWorld(Resource):
decorators = [checkuser, jwt_required()]
def get(self):
return {'hello': current_identity.username}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>POST </p>
<pre><code>{
"username": "user1",
"password": "abcxyz"
}
</code></pre>
<p>To <code>localhost:5000/auth</code> and get the <code>access_token</code> in response. </p>
<p>Then GET <code>localhost:5000/</code> with header</p>
<pre><code>Authorization: JWT `the access_token value above`
</code></pre>
<p>You would get </p>
<pre><code>{
"hello": "user1"
}
</code></pre>
<p>if you try to access <code>localhost:5000/</code> with the JWT token of user2, you would get <code>401</code>.</p>
<p>The decorators are wrapped in this way:</p>
<pre><code>for decorator in self.decorators:
resource_func = decorator(resource_func)
</code></pre>
<p><a href="https://github.com/flask-restful/flask-restful/blob/master/flask_restful/__init__.py#L445">https://github.com/flask-restful/flask-restful/blob/master/flask_restful/<strong>init</strong>.py#L445</a></p>
<p>So the later one in the decorators array gets to run earlier. </p>
<p>For more reference:</p>
<p><a href="https://github.com/rchampa/timetable/blob/master/restful/users.py">https://github.com/rchampa/timetable/blob/master/restful/users.py</a></p>
<p><a href="https://github.com/mattupstate/flask-jwt/issues/37">https://github.com/mattupstate/flask-jwt/issues/37</a></p> |
38,522,931 | Adding data to ArrayList while reading data from Excel using POI Apache | <p>I am trying to read data from Excel sheets using POI Apache. The problem I am having is that I want to read the data of all cell of a row at the same time and store it in ArrayList of Type Class but the output is only cell by cell.</p>
<p>Here is the class that open the excel sheet and read the data cell by cell.</p>
<pre><code>package testing;
import javax.swing.JFileChooser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelDemo
{
ArrayList<Data> list = new ArrayList<>();
String path;
public ReadExcelDemo(String path)
{
this.path = path;
try
{
FileInputStream file = new FileInputStream(new File(path));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
System.out.println("");
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
</code></pre>
<p>Data Class</p>
<pre><code>package testing;
public class Data {
int ID;
String F_Name,L_Name;
public Data(int ID, String F_Name, String L_Name) {
this.ID = ID;
this.F_Name = F_Name;
this.L_Name = L_Name;
}
public int getID() {
return ID;
}
public String getF_Name() {
return F_Name;
}
public String getL_Name() {
return L_Name;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/WDbKU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WDbKU.png" alt="enter image description here"></a></p>
<p>I want to add the cell data in Arraylist like this at a single time</p>
<pre><code>List.add(new Data(1,"Amit","shukla"));
</code></pre>
<p>but the data the iterator return is one by one like first it outputs <strong>1</strong> then <strong>amit</strong> and then <strong>shukla</strong> which is really difficult to add to arraylist</p>
<p>I tried so much to add data to ArrayList at a single line but I couldn't. It would be really helpful if you guy help me solve this problem.</p> | 38,523,848 | 4 | 1 | null | 2016-07-22 09:29:16.54 UTC | null | 2022-07-07 12:25:24.86 UTC | 2016-07-22 10:28:38.783 UTC | null | 6,042,824 | null | 5,165,935 | null | 1 | 4 | java|excel|arraylist|apache-poi | 46,518 | <p>this.path = path;</p>
<pre><code> try
{
FileInputStream file = new FileInputStreaHashMap<K, V>ile(path));
HashMap<Integer, Data> mp= new HashMap<Integer, Data>();
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
System.out.println("");
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
int i=0;
int j=0;
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
i=Integer.parseInt(cell.getNumericCellValue());
Data d= new Data();
d.setId(cell.getNumericCellvalue());
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
if( j==0){
Data data= mp.get(i);
data.setName(cell.getStringCellValue());
mp.put(i, data);
j=j+1;
}
else
{
Data data= mp.get(i);
data.setLastName(cell.getStringCellValue());
mp.put(i, data);
j=0;
}
break;
}
}
System.out.println("");
}
List<Data> dataList= new ArrayList<Data>();
for (Data d : mp.values()) {
dataList.add(d);
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
</code></pre> |
38,860,046 | How to initialize only few elements of an array with some values? | <p>Is it possible to assign <strong>some</strong> values to an array instead of all? To clarify what I want:</p>
<p>If I need an array like <code>{1,0,0,0,2,0,0,0,3,0,0,0}</code> I can create it like:</p>
<pre><code>int array[] = {1,0,0,0,2,0,0,0,3,0,0,0};
</code></pre>
<p>Most values of this array are '0'. Is it possible to skip this values and only assign the values 1, 2 and 3? I think of something like:</p>
<pre><code>int array[12] = {0: 1, 4: 2, 8: 3};
</code></pre> | 38,860,092 | 4 | 3 | null | 2016-08-09 20:41:17.74 UTC | 11 | 2022-04-23 08:03:57.767 UTC | 2022-04-23 08:03:57.767 UTC | null | 5,446,749 | null | 3,657,155 | null | 1 | 45 | c|arrays|initialization | 9,815 | <blockquote>
<p>Is it possible to skip this values and only assign the values 1, 2 and 3? </p>
</blockquote>
<p>In C, Yes. Use designated initializer (added in C99 and not supported in C++). </p>
<pre><code>int array[12] = {[0] = 1, [4] = 2, [8] = 3};
</code></pre>
<p>Above initializer will initialize element <code>0</code>, <code>4</code> and <code>8</code> of array <code>array</code> with values <code>1</code>, <code>2</code> and <code>3</code> respectively. Rest elements will be initialized with <code>0</code>. This will be equivalent to </p>
<pre><code> int array[12] = {1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0};
</code></pre>
<p>The best part is that the order in which elements are listed doesn't matter. One can also write like </p>
<pre><code> int array[12] = {[8] = 3, [0] = 1, [4] = 2};
</code></pre>
<p>But note that the expression inside <code>[ ]</code> shall be an <em>integer constant expression</em>.</p> |
32,205,919 | Sort array of custom objects by date swift | <p>I have a custom object "Meeting" I am adding all the objects in an array. What I want to do is sort the array from Meeting.meetingDate. </p>
<p>I'm also using Parse, I have two queries and putting the results into one array.</p>
<p>I am able to add the data to "meetingData", but not sort it.</p>
<p>Can anyone help with this?</p>
<p>So my array is:</p>
<pre><code>var meetingsData = [Meeting]()
</code></pre>
<p>The Meeting class is:</p>
<pre><code>public class Meeting: PFObject, PFSubclassing
{
@NSManaged public var meetingTitle: String?
@NSManaged public var meetingLocation: String?
@NSManaged public var meetingNotes: String?
@NSManaged public var meetingDuration: String?
@NSManaged public var createdBy: User?
@NSManaged public var meetingTime: NSDate?
@NSManaged public var meetingDate: NSDate?
}
</code></pre>
<p>The contents of the array is like so:</p>
<pre><code><Meeting: 0x125edd040, objectId: xIqx7MoRd6, localId: (null)> {
createdBy = "<PFUser: 0x125d627c0, objectId: RKCWJRj84O>";
meetingDate = "2015-08-29 17:07:12 +0000";
meetingDuration = "2 hours 2 mins";
meetingLocation = 4th Floor;
meetingNotes = With Investors;
meetingTime = "2015-08-24 09:00:17 +0000";
meetingTitle = Meeting with Investors;
}
<Meeting: 0x125ed95f0, objectId: tz4xx5p9jB, localId: (null)> {
createdBy = "<PFUser: 0x125d627c0, objectId: RKCWJRj84O>";
meetingDate = "2015-08-23 23:00:00 +0000";
meetingDuration = "1 hour";
meetingLocation = "Emirates Stadium, London";
meetingNotes = "Football";
meetingTime = "2000-01-01 20:00:00 +0000";
meetingTitle = "Liverpool V Arsenal";
}
<Meeting: 0x125ed95f0, objectId: tz4xx5p9jB, localId: (null)> {
createdBy = "<PFUser: 0x125d627c0, objectId: RKCWJRj84O>";
meetingDate = "2015-09-23 23:00:00 +0000";
meetingDuration = "1 hour";
meetingLocation = "Library";
meetingNotes = "Dev Team";
meetingTime = "2000-01-01 10:00:00 +0000";
meetingTitle = "Code Review";
}
</code></pre>
<p>I have tried to do this <a href="https://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value">Swift how to sort array of custom objects by property value</a> but it doesn't work</p>
<p>Thanks in advance</p> | 51,249,669 | 3 | 0 | null | 2015-08-25 13:53:04.94 UTC | 10 | 2021-02-03 19:46:02.767 UTC | 2017-05-23 12:10:08.013 UTC | null | -1 | null | 1,250,367 | null | 1 | 24 | arrays|swift|sorting|parse-platform|nsdate | 32,592 | <p>For <strong>Swift 4, Swift 5</strong></p>
<p>Sorting by timestamp</p>
<pre><code>values.sorted(by: { $0.meetingDateTimestamp > $1. meetingDateTimestamp })
</code></pre> |
41,997,426 | InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Missing credentials | <p>I'm trying to deploy a GitHub project to a EC2 Instance using AWS CodeDeploy. After following 2 video tutorials an a bunch of Google answer, I'm still getting the following error:</p>
<pre><code>2017-02-01 12:20:08 INFO [codedeploy-agent(1379)]: master 1379: Spawned child 1/1
2017-02-01 12:20:09 INFO [codedeploy-agent(1383)]: On Premises config file does not exist or not readable
2017-02-01 12:20:09 INFO [codedeploy-agent(1383)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandExecutor: Archives to retain is: 5}
2017-02-01 12:20:09 INFO [codedeploy-agent(1383)]: Version file found in /opt/codedeploy-agent/.version.
2017-02-01 12:20:09 ERROR [codedeploy-agent(1383)]: InstanceAgent::Plugins::CodeDeployPlugin::CommandPoller: Missing credentials - please check if this instance was started with an IAM instance profile
</code></pre>
<p>I have two IAM:</p>
<ul>
<li>CodeDeployInstanceRole</li>
<li>CodeDeployServiceRole</li>
</ul>
<h2>CodeDeployInstanceRole for the EC2 Instance</h2>
<p><strong>Policy Name</strong>: AmazonEC2RoleforAWSCodeDeploy</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:GetObject",
"s3:GetObjectVersion",
"s3:ListObjects"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
</code></pre>
<p><strong>Policy Name</strong>: AutoScalingNotificationAccessRole</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Resource": "*",
"Action": [
"sqs:SendMessage",
"sqs:GetQueueUrl",
"sns:Publish"
]
}
]
}
</code></pre>
<p>Trust Relationship</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"codedeploy.amazonaws.com",
"ec2.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
</code></pre>
<h2>CodeDeployServiceRole for CodeDeploy</h2>
<p><strong>Policy Name</strong>: AWSCodeDeployRole</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"autoscaling:CompleteLifecycleAction",
"autoscaling:DeleteLifecycleHook",
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribeLifecycleHooks",
"autoscaling:PutLifecycleHook",
"autoscaling:RecordLifecycleActionHeartbeat",
"autoscaling:CreateAutoScalingGroup",
"autoscaling:UpdateAutoScalingGroup",
"autoscaling:EnableMetricsCollection",
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribePolicies",
"autoscaling:DescribeScheduledActions",
"autoscaling:DescribeNotificationConfigurations",
"autoscaling:DescribeLifecycleHooks",
"autoscaling:SuspendProcesses",
"autoscaling:ResumeProcesses",
"autoscaling:AttachLoadBalancers",
"autoscaling:PutScalingPolicy",
"autoscaling:PutScheduledUpdateGroupAction",
"autoscaling:PutNotificationConfiguration",
"autoscaling:PutLifecycleHook",
"autoscaling:DescribeScalingActivities",
"autoscaling:DeleteAutoScalingGroup",
"ec2:DescribeInstances",
"ec2:DescribeInstanceStatus",
"ec2:TerminateInstances",
"tag:GetTags",
"tag:GetResources",
"sns:Publish",
"cloudwatch:DescribeAlarms",
"elasticloadbalancing:DescribeLoadBalancers",
"elasticloadbalancing:DescribeInstanceHealth",
"elasticloadbalancing:RegisterInstancesWithLoadBalancer",
"elasticloadbalancing:DeregisterInstancesFromLoadBalancer"
],
"Resource": "*"
}
]
}
</code></pre>
<p>Trust Relationship</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"codedeploy.amazonaws.com",
"ec2.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
</code></pre>
<h1>EC2 Instance</h1>
<p>I spin my own image that I have created based on Debian so I have NodeJS already installed. When I spin the new instance I also paste the following code in the <code>User data</code> text area to make sure CodeDeploy is installed.</p>
<pre><code>#!/bin/bash -x
REGION=$(curl 169.254.169.254/latest/meta-data/placement/availability-zone/ | sed 's/[a-z]$//') &&
sudo apt-get update -y &&
sudo apt-get install -y python-pip &&
sudo apt-get install -y ruby &&
sudo apt-get install -y wget &&
cd /home/admin &&
wget https://aws-codedeploy-$REGION.s3.amazonaws.com/latest/install &&
chmod +x ./install &&
sudo ./install auto &&
sudo apt-get remove -y wget &&
sudo service codedeploy-agent start
</code></pre>
<h1>Debugging</h1>
<p>If I log in in the EC2 instance that I have create, and execute the following command:</p>
<pre><code>echo $(curl http://169.254.169.254/latest/meta-data/iam/security-credentials/)
</code></pre>
<p>I get the following response <code>CodeDeployInstanceRole</code></p>
<p>When I then execute </p>
<pre><code>curl http://169.254.169.254/latest/meta-data/iam/security-credentials/CodeDeployInstanceRole
</code></pre>
<p>I get the following response </p>
<pre><code>{
"Code" : "Success",
"LastUpdated" : "2017-02-01T12:38:07Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "THE_KEY",
"SecretAccessKey" : "SECRET",
"Token" : "TOKEN",
"Expiration" : "2017-02-01T19:08:43Z"
}
</code></pre>
<p>On GitHub I see that CodeDeploy never accesses my repo even when I select deployment using GitHub, I set the right repo name, and commit ID.</p>
<p><a href="https://i.stack.imgur.com/VYE7X.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VYE7X.png" alt="enter image description here"></a></p>
<h1>Question</h1>
<p>What am I missing?</p> | 44,217,101 | 5 | 0 | null | 2017-02-02 08:30:07.917 UTC | 7 | 2021-02-24 17:40:06.97 UTC | 2017-03-09 14:09:56.517 UTC | null | 1,049,894 | null | 1,049,894 | null | 1 | 32 | amazon-web-services|github|amazon-ec2|amazon-iam|aws-code-deploy | 15,209 | <p>Turns out that by default Debian doesn't have <code>curl</code> installed. Installing <code>curl</code> before making the curl request to get the region the server is running on was the missing part in the Bash script. </p> |
24,815,952 | Git pull from another repository | <p>I have a repository called <code>Generic</code>, which is a generic application. I have forked it into a repository called <code>Acme</code>, which just builds upon the application stored <code>Generic</code> repository and adds Acme Co branding to it.</p>
<p>If I make changes to the core functionality in <code>Generic</code>, I want to update the <code>Acme</code> repository with the latest changes I have made to the core functionality in <code>Generic</code>. How would I do that?</p>
<p>As far as I can tell, I am essentially trying to merge the changes made in an upstream repository into the current fork.</p>
<p>If it means anything, I'm trying to do this because I have a generic application that I then build upon and brand for individual clients (like <code>Acme</code> in this example). If there is a cleaner way of doing this, let me know.</p> | 24,816,134 | 3 | 0 | null | 2014-07-18 01:17:13.707 UTC | 52 | 2021-08-04 19:30:41.937 UTC | 2018-03-19 15:44:41.553 UTC | null | 1,654,736 | null | 1,775,780 | null | 1 | 134 | git|version-control|repository|dvcs | 92,206 | <p>Issue the following command in your <code>Acme</code> repo. It adds a new remote repository named <code>upstream</code> that points to the <code>Generic</code> repo.</p>
<pre><code>git remote add upstream https://location/of/generic.git
</code></pre>
<p>You can then merge any changes made to <code>Generic</code> into the current branch in <code>Acme</code> with the following command:</p>
<pre><code>git pull upstream
</code></pre>
<p>If you just want it to download the changes without automatically merging, use <code>git fetch</code> instead of <code>git pull</code>.</p>
<p>If you want to disable pushing to that repository, set the push URL to an invalid URL using something like</p>
<pre><code>git config remote.upstream.pushurl "NEVER GONNA GIVE YOU UP"
</code></pre>
<p>Git will now yell at you about not being able to find a repo if you try to push to <code>upstream</code> (and sorry about the Rickroll, but it was the first random string that popped into my head).</p> |
35,508,635 | AllowOverride not allowed here | <p>I have setup a virtualhost like following</p>
<pre><code><VirtualHost *:80>
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Options Includes
AllowOverride All
</VirtualHost>
</code></pre>
<p>But always throws me</p>
<pre><code>AH00526: Syntax error on line 6 of /etc/apache2/sites-enabled/000-my-site.conf:
AllowOverride not allowed here
</code></pre>
<p>I'm a bit confused because I understand that is the right place to do it</p> | 35,508,691 | 1 | 0 | null | 2016-02-19 15:16:17.273 UTC | 4 | 2019-04-07 19:50:44.07 UTC | null | null | null | null | 816,721 | null | 1 | 31 | apache | 42,507 | <p>It's because you have to put it in <code><Directory></code> directive.' .htaccess is per directory context, so you have to explicitly tell apache where .htaccess is allowed to be used. </p>
<pre><code><VirtualHost *:80>
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Options Includes
<Directory "/var/www/html">
AllowOverride All
</Directory>
</VirtualHost>
</code></pre> |
18,706,665 | extracting value based on another column | <p>I have a function that spits out a matrix, such as:</p>
<pre><code> x freq
1 FALSE 40
2 TRUE 6
</code></pre>
<p>but when there are no FALSE values, I get</p>
<pre><code> x freq
1 TRUE 46
</code></pre>
<p>I want to extract the freq value when x=TRUE.
If there are are always both FALSE and TRUE values, I can do</p>
<pre><code>> matrix [2,2]
[1] 6
</code></pre>
<p>But I would like to be able to extract the TRUE value whether or not there are FALSE values. Does anyone know how I can do that? Thanks in advance!</p> | 18,706,926 | 1 | 2 | null | 2013-09-09 20:40:40.563 UTC | 6 | 2013-09-10 14:39:57.997 UTC | null | null | null | null | 2,113,323 | null | 1 | 7 | r|extract | 63,320 | <p>As @Justin said, you might be working with a <code>data.frame</code> instead of a <code>matrix</code>. All the better. Using your example above, if your data.frame looks as follows:</p>
<pre><code>df <- data.frame(x=c(FALSE,TRUE), freq=c(40, 6))
> df
x freq
1 FALSE 40
2 TRUE 6
</code></pre>
<p>The following will get you what you want irrespective of whether there are <code>FALSE</code> values or not.</p>
<pre><code>df$freq[df$x==TRUE]
[1] 6
</code></pre>
<p><strong>EDIT</strong>: As @DWin points out, you can simplify further by using the fact that <code>df$x</code> is logical:</p>
<pre><code>> df$freq[df$x]
[1] 6
> df$freq[!df$x]
[1] 40
</code></pre>
<p>For example:</p>
<pre><code>> df2 <- data.frame(x=TRUE, freq=46)
> df2
x freq
1 TRUE 46
</code></pre>
<p>Still works:</p>
<pre><code>> df2$freq[df2$x==TRUE]
[1] 46
</code></pre> |
53,735,009 | Including Async Function Within Firebase Cloud Functions (eslint "Parsing error: Unexpected token function") | <h1>Issue</h1>
<p>How can an <code>async</code> helper method be added to a <em>Cloud Functions'</em> <em>index.js</em> file? An <code>async</code> function is required in order to use <code>await</code> when converting <code>fs.writefile</code> into a <strong>Promise</strong> as explained in this StackOverflow post: <a href="https://stackoverflow.com/questions/31978347/fs-writefile-in-a-promise-asynchronous-synchronous-stuff/53689011#53689011">fs.writeFile in a promise, asynchronous-synchronous stuff</a>. However, <em>lint</em> does not approve of adding an additional method outside of the <code>exports</code> functions to the <em>index.js</em> file.</p>
<h1>Error</h1>
<p>Line <strong>84</strong> refers to the helper function <code>async function writeFile</code>.</p>
<blockquote>
<p>Users/adamhurwitz/coinverse/coinverse-cloud-functions/functions/index.js
84:7 error Parsing error: Unexpected token function</p>
<p>✖ 1 problem (1 error, 0 warnings)</p>
<p>npm ERR! code ELIFECYCLE</p>
<p>npm ERR! errno 1</p>
<p>npm ERR! functions@ lint: <code>eslint .</code></p>
<p>npm ERR! Exit status 1</p>
<p>npm ERR!</p>
<p>npm ERR! Failed at the functions@ lint script.</p>
<p>npm ERR! This is probably not a problem with npm. There is likely additional logging output above.</p>
<p>npm ERR! A complete log of this run can be found in:</p>
<p>npm ERR! /Users/adamhurwitz/.npm/_logs/2018-12-12T01_47_50_684Z-debug.log</p>
<p>Error: functions predeploy error: Command terminated with non-zero exit code1</p>
</blockquote>
<h1>Setup</h1>
<p><em>index.js</em></p>
<pre><code>const path = require('path');
const os = require('os');
const fs = require('fs');
const fsPromises = require('fs').promises;
const util = require('util');
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const {Storage} = require('@google-cloud/storage');
const textToSpeech = require('@google-cloud/text-to-speech');
const storage = new Storage({
projectId: 'project-id',
});
const client = new textToSpeech.TextToSpeechClient();
admin.initializeApp();
exports.getAudiocast = functions.https.onCall((data, context) => {
const bucket = storage.bucket('gs://[bucket-name].appspot.com');
var fileName;
var tempFile;
var filePath;
return client.synthesizeSpeech({
input: {text: data.text },
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
audioConfig: {audioEncoding: 'MP3'},
})
.then(responses => {
var response = responses[0];
fileName = data.id + '.mp3'
tempFile = path.join(os.tmpdir(), fileName);
return writeFile(tempFile, response.audioContent)
})
.catch(err => {
console.error("Synthesize Speech Error: " + err);
})
.then(() => {
filePath = "filePath/" + fileName;
return bucket.upload(tempFile, { destination: filePath })
})
.catch(err => {
console.error("Write Temporary Audio File Error: " + err);
})
.then(() => {
return { filePath: filePath }
})
.catch(err => {
console.error('Upload Audio to GCS ERROR: ' + err);
});
});
</code></pre>
<p>Helper method:</p>
<pre><code>async function writeFile(tempFile, audioContent) {
await fs.writeFile(tempFile, audioContent, 'binary');
}
</code></pre>
<h1>Attempted Solution</h1>
<p>Enabling Node.js <strong>8</strong> as recommended in the post <a href="https://stackoverflow.com/questions/44444273/cloud-functions-for-firebase-async-await-style">Cloud Functions for Firebase Async Await style</a>.</p>
<ol>
<li><p><a href="https://firebase.google.com/docs/functions/manage-functions#set_nodejs_version" rel="noreferrer">Set Node.js version</a>
<code>"engines": {"node": "8"}</code></p></li>
<li><p><code>return await fs.writeFile(tempFile, audioContent, 'binary');</code></p></li>
</ol>
<p>Lint does not like this solution.</p> | 53,735,102 | 7 | 0 | null | 2018-12-12 01:59:03.087 UTC | 10 | 2021-11-15 19:24:11.617 UTC | 2018-12-12 07:53:09.797 UTC | null | 7,967,164 | null | 2,253,682 | null | 1 | 19 | javascript|node.js|firebase|google-cloud-functions|firebase-cli | 14,812 | <h1>Node.js 8 - Promisify</h1>
<p>Enabling Node.js <strong>8</strong> as recommended in the post <a href="https://stackoverflow.com/questions/44444273/cloud-functions-for-firebase-async-await-style">Cloud Functions for Firebase Async Await style</a>.</p>
<ol>
<li><a href="https://firebase.google.com/docs/functions/manage-functions#set_nodejs_version" rel="nofollow noreferrer">Set Node.js version</a>
<code>"engines": {"node": "8"}</code></li>
<li><p>Use <code>promisify</code></p>
<p><code>const writeFile = util.promisify(fs.writeFile);</code></p>
<p><code>return writeFile(tempFile, response.audioContent, 'binary')</code></p></li>
</ol>
<h1>Pre Node.js 8 - Manual Conversion</h1>
<p>This is an older approach to convert Callbacks to Promises as outlined by this <a href="https://stackoverflow.com/a/52509361/2253682">answer</a> regarding a more specific question about Google Text To Speech (<em>TTS</em>).</p>
<pre><code>const writeFilePromise = (file, data, option) => {
return new Promise((resolve, reject) => {
fs.writeFile(file, data, option, error => {
if (error) reject(error);
resolve("File created! Time for the next step!");
});
});
};
return writeFilePromise(tempFile, response.audioContent, 'binary');
</code></pre> |
44,647,924 | How do networking and load balancer work in docker swarm mode? | <p>I am new to Dockers and containers. I was going through the tutorials for docker and came across this information.
<a href="https://docs.docker.com/get-started/part3/#docker-composeyml" rel="noreferrer">https://docs.docker.com/get-started/part3/#docker-composeyml</a></p>
<pre><code> networks:
- webnet
networks:
webnet:
</code></pre>
<p>What is webnet? The document says</p>
<blockquote>
<p>Instruct web’s containers to share port 80 via a load-balanced network called webnet. (Internally, the containers themselves will publish to web’s port 80 at an ephemeral port.)</p>
</blockquote>
<p>So, by default, the overlay network is load balanced in docker cluster? What is load balancing algo used? </p>
<p>Actually, it is not clear to me why do we have load balancing on the overlay network.</p> | 44,649,746 | 1 | 0 | null | 2017-06-20 08:37:18.703 UTC | 9 | 2018-12-22 22:34:05.813 UTC | 2018-12-22 22:34:05.813 UTC | null | 4,922,375 | null | 1,768,610 | null | 1 | 25 | networking|docker|load-balancing|docker-swarm-mode | 5,369 | <p>Not sure I can be clearer than the docs, but maybe rephrasing will help.</p>
<p>First, the doc you're following here uses what is called the <a href="https://docs.docker.com/engine/swarm/#feature-highlights" rel="noreferrer"><code>swarm mode</code></a> of docker.</p>
<p>What is <a href="https://docs.docker.com/engine/swarm/key-concepts/" rel="noreferrer"><code>swarm mode</code></a>?</p>
<blockquote>
<p>A swarm is a cluster of Docker engines, or nodes, where you deploy services. The Docker Engine CLI and API include commands to manage swarm nodes (e.g., add or remove nodes), and deploy and orchestrate services across the swarm.</p>
</blockquote>
<p>From SO Documentation:</p>
<blockquote>
<p>A swarm is a number of Docker Engines (or nodes) that deploy services collectively. Swarm is used to distribute processing across many physical, virtual or cloud machines.</p>
</blockquote>
<p>So, with swarm mode you have a multi host (vms and/or physical) cluster a machines that communicate with each other through their <a href="https://docs.docker.com/engine/userguide/" rel="noreferrer"><code>docker engine</code></a>.</p>
<p><strong>Q1. What is webnet?</strong></p>
<p><code>webnet</code> is the name of an <a href="https://docs.docker.com/engine/swarm/networking/" rel="noreferrer">overlay network</a> that is created when your stack is launched.</p>
<blockquote>
<p>Overlay networks manage communications among the Docker daemons participating in the swarm</p>
</blockquote>
<p>In your cluster of machines, a virtual network is the created, where each service has an ip - mapped to an internal DNS entry (which is service name), and allowing docker to route incoming packets to the right container, everywhere in the swarm (cluster).</p>
<p><strong>Q2. So, by default, overlay network is load balanced in docker cluster ?</strong></p>
<p>Yes, if you use the overlay network, but you could also remove the service <code>networks</code> configuration to bypass that. Then you would have to <a href="https://docs.docker.com/engine/swarm/services/#publish-ports" rel="noreferrer">publish</a> the port of the service you want to expose.</p>
<p><strong>Q3. What is load balancing algo used ?</strong></p>
<p>From this <a href="https://stackoverflow.com/questions/41945482/how-docker-swarm-mode-does-load-balancing">SO question</a> answered by swarm master <a href="https://stackoverflow.com/users/596285/bmitch">bmitch</a> ;):</p>
<blockquote>
<p>The algorithm is currently round-robin and I've seen no indication that it's pluginable yet. A higher level load balancer would allow swarm nodes to be taken down for maintenance, but any sticky sessions or other routing features will be undone by the round-robin algorithm in swarm mode.</p>
</blockquote>
<p><strong>Q4. Actually it is not clear to me why do we have load balancing on overlay network</strong></p>
<p>Purpose of docker swarm mode / services is to allow orchestration of <strong>replicated</strong> services, meaning that we can scale up / down containers deployed in the swarm.</p>
<p>From the <a href="https://docs.docker.com/engine/swarm/key-concepts/" rel="noreferrer">docs</a> again:</p>
<blockquote>
<p>Swarm mode has an internal DNS component that automatically assigns each service in the swarm a DNS entry. The swarm manager uses internal load balancing to distribute requests among services within the cluster based upon the DNS name of the service.</p>
</blockquote>
<p>So you can have deployed like 10 exact same container (let's say nginx with you app html/js), without dealing with private network DNS entries, port configuration, etc... Any incoming request will be automatically load balanced to hosts participating in the swarm.</p>
<p>Hope this helps!</p> |
3,101,215 | change background image of li on an a:hover | <p>I have a menu:</p>
<pre><code><div id=menu>
<ul=navigation>
<li><a href=>Home</a></li>
</ul>
</div>
</code></pre>
<p>With the sliding doors technique I want to create my button (containing rounded corners at the bottom.)</p>
<p>I can get this to work, by hovering the a and the li. But the li is bigger, and if I hover over the li, without hovering the a, only the background image for the li shows. </p>
<p>Now I'm wondering if there is a way to connect the hover of the li and the hover of the a within css. I rather fix this problem without using javascript. </p>
<p>Googleing didn't helped me further. I'm guessing this isn't possible, but I wanted to be sure before trying other options.</p>
<p>Thanks in advance for any advice/help/suggestions.</p> | 3,101,292 | 3 | 0 | null | 2010-06-23 11:40:25.747 UTC | 2 | 2010-06-28 10:13:54.663 UTC | null | null | null | null | 317,326 | null | 1 | 5 | css|sliding-doors | 83,295 | <p>From what I gather you cannot do what you are after in the way you have described it.</p>
<p>However what I would do is make the "a tag" display as block and set the width and height to fill the "LI" that way you can use a:hover and change the whole bg which makes it look like the LI is changing</p>
<pre>
<code>
li a {
background:#000 url(images/bg.png) no-repeat 0 0;
display:block;
height:20px;
width:100px;
}
li a:hover {
background:#fff url(images/bg.png) no-repeat 0 -20px;
}
</code>
</pre>
<p>also use some padding to sit the text in the right place within the "LI" and remove any padding from the "LI"</p>
<p>li:hover is not supported without JS in older versions of IE so using a:hover instead provides better cross browser compatability</p> |
49,510,832 | How to map over union array type? | <p>I have the following structure:</p>
<pre><code>interface Test1 {
number: number;
}
interface Test2 extends Test1 {
text: string;
}
let test: Test1[] | Test2[] = [];
test.map(obj => {}); // does not work
</code></pre>
<p>I am getting the error:</p>
<blockquote>
<p>Cannot invoke an expression whose type lacks a call signature. Type '{ (this: [Test1, Test1, Test1, Test1, Test1], callbackfn: (this: void, value: Test1, index: nu...' has no compatible call signatures</p>
</blockquote>
<p>How can I <code>map</code> over the test variable?</p> | 49,511,416 | 1 | 1 | null | 2018-03-27 10:44:38.27 UTC | 17 | 2021-08-16 11:42:22.347 UTC | 2021-08-16 11:42:22.347 UTC | null | 11,407,695 | null | 4,467,208 | null | 1 | 92 | typescript|union-types | 45,455 | <p><strong>Edit for 4.2</strong></p>
<p><code>map</code> has become callable now, but you still need an explicit type annotation on its argument to get it to work as expected (the type parameter is no contextually typed)</p>
<pre><code>let test: Test1[] | Test2[] = [];
test.map((obj: Test1 | Test2) => {});
</code></pre>
<p><a href="https://www.typescriptlang.org/play?ts=4.2.0-beta#code/JYOwLgpgTgZghgYwgAgCoQM5gIzIN4CwAUMqciAK4C2ARtAFznV1QDcxAvsaJLIiuiwAmZBAAekEABMMaTDnzEyySBMZYooAObsiXIsQA2EMCvmNBOANoBdZAB85w28gC8yW7shYAdFTgADgAUQQD2NABWFvK4jpZCAJRuAHz4HAmsQA" rel="noreferrer">Playground Link</a></p>
<p>This situation is likely to improve in future versions making this answer mostly obsolete (see <a href="https://github.com/microsoft/TypeScript/pull/42620" rel="noreferrer">PR</a> that will correctly synthesize contextual types for parameters)</p>
<p><strong>Original answer pre 4.2</strong></p>
<p>The problem is that for union types, members which are functions will also be typed as union types, so the type of <code>map</code> will be <code>(<U>(callbackfn: (value: Test1, index: number, array: Test1[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: Test2, index: number, array: Test2[]) => U)</code> Which as far as typescript is concerned is not callable.</p>
<p>You can either declare an array of the union of <code>Test1</code> and <code>Test2</code></p>
<pre><code>let test: (Test1 | Test2)[] = [];
test.map(obj => {});
</code></pre>
<p>Or you can use a type assertion when you make the call:</p>
<pre><code>let test: Test1[] | Test2[] = [];
(test as Array<Test1|Test2>).map(o=> {});
</code></pre> |
47,809,666 | Lodash debounce not working in React | <p>it would be best to first look at my code: </p>
<pre><code>import React, { Component } from 'react';
import _ from 'lodash';
import Services from 'Services'; // Webservice calls
export default class componentName extends Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value || null
}
}
onChange(value) {
this.setState({ value });
// This doesn't call Services.setValue at all
_.debounce(() => Services.setValue(value), 1000);
}
render() {
return (
<div>
<input
onChange={(event, value) => this.onChange(value)}
value={this.state.value}
/>
</div>
)
}
}
</code></pre>
<p>Just a simple input. In the contructor it grabs <code>value</code> from the props (if available) at sets a local state for the component.</p>
<p>Then in the <code>onChange</code> function of the <code>input</code> I update the state and then try to call the webservice endpoint to set the new value with <code>Services.setValue()</code>. </p>
<p>What does work is if I set the <code>debounce</code> directly by the <code>onChange</code> of the input like so:</p>
<pre><code><input
value={this.state.value}
onChange={_.debounce((event, value) => this.onChange(value), 1000)}
/>
</code></pre>
<p>But then <code>this.setState</code> gets called only every 1000 milliseconds and update the view. So typing in a textfield ends up looking weird since what you typed only shows a second later.</p>
<p>What do I do in a situation like this?</p> | 47,809,802 | 5 | 0 | null | 2017-12-14 09:14:26.15 UTC | 8 | 2022-09-19 08:17:00.19 UTC | null | null | null | user818700 | null | null | 1 | 35 | javascript|reactjs|ecmascript-6|lodash|debounce | 33,486 | <p>The problem occurs because you aren't calling the debounce function, you could do in the following manner</p>
<pre><code>export default class componentName extends Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value || null
}
this.servicesValue = _.debounce(this.servicesValue, 1000);
}
onChange(value) {
this.setState({ value });
this.servicesValue(value);
}
servicesValue = (value) => {
Services.setValue(value)
}
render() {
return (
<div>
<input
onChange={(event, value) => this.onChange(value)}
value={this.state.value}
/>
</div>
)
}
}
</code></pre> |
38,884,522 | Why is my asynchronous function returning Promise { <pending> } instead of a value? | <p>My code:</p>
<pre><code>let AuthUser = data => {
return google.login(data.username, data.password).then(token => { return token } )
}
</code></pre>
<p>And when i try to run something like this:</p>
<pre><code>let userToken = AuthUser(data)
console.log(userToken)
</code></pre>
<p>I'm getting:</p>
<pre><code>Promise { <pending> }
</code></pre>
<p>But why?</p>
<p>My main goal is to get token from <code>google.login(data.username, data.password)</code> which returns a promise, into a variable. And only then preform some actions.</p> | 38,884,856 | 8 | 10 | null | 2016-08-10 22:24:25.66 UTC | 110 | 2021-08-10 09:44:49.007 UTC | 2019-04-27 08:21:09.723 UTC | null | 1,945,651 | null | 4,829,408 | null | 1 | 239 | javascript|node.js|promise | 507,112 | <p>The promise will always log pending as long as its results are not resolved yet. You must call <code>.then</code> on the promise to capture the results regardless of the promise state (resolved or still pending):</p>
<pre><code>let AuthUser = function(data) {
return google.login(data.username, data.password).then(token => { return token } )
}
let userToken = AuthUser(data)
console.log(userToken) // Promise { <pending> }
userToken.then(function(result) {
console.log(result) // "Some User token"
})
</code></pre>
<p>Why is that?</p>
<p>Promises are forward direction only; You can only resolve them once. The resolved value of a <code>Promise</code> is passed to its <code>.then</code> or <code>.catch</code> methods.</p>
<h1>Details</h1>
<p>According to the Promises/A+ spec:</p>
<blockquote>
<p>The promise resolution procedure is an abstract operation taking as
input a promise and a value, which we denote as [[Resolve]](promise,
x). If x is a thenable, it attempts to make promise adopt the state of
x, under the assumption that x behaves at least somewhat like a
promise. Otherwise, it fulfills promise with the value x.</p>
<p>This treatment of thenables allows promise implementations to
interoperate, as long as they expose a Promises/A+-compliant then
method. It also allows Promises/A+ implementations to “assimilate”
nonconformant implementations with reasonable then methods.</p>
</blockquote>
<p>This spec is a little hard to parse, so let's break it down. The rule is:</p>
<p>If the function in the <code>.then</code> handler returns a value, then the <code>Promise</code> resolves with that value. If the handler returns another <code>Promise</code>, then the original <code>Promise</code> resolves with the resolved value of the chained <code>Promise</code>. The next <code>.then</code> handler will always contain the resolved value of the chained promise returned in the preceding <code>.then</code>.</p>
<p>The way it actually works is described below in more detail:</p>
<p><strong>1. The return of the <code>.then</code> function will be the resolved value of the promise.</strong></p>
<pre><code>function initPromise() {
return new Promise(function(res, rej) {
res("initResolve");
})
}
initPromise()
.then(function(result) {
console.log(result); // "initResolve"
return "normalReturn";
})
.then(function(result) {
console.log(result); // "normalReturn"
});
</code></pre>
<p><strong>2. If the <code>.then</code> function returns a <code>Promise</code>, then the resolved value of that chained promise is passed to the following <code>.then</code>.</strong></p>
<pre><code>function initPromise() {
return new Promise(function(res, rej) {
res("initResolve");
})
}
initPromise()
.then(function(result) {
console.log(result); // "initResolve"
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("secondPromise");
}, 1000)
})
})
.then(function(result) {
console.log(result); // "secondPromise"
});
</code></pre> |
7,246,513 | Zeroing Weak References in ARC | <p>If my reading of Mike Ash's <a href="http://www.mikeash.com/pyblog/friday-qa-2010-07-16-zeroing-weak-references-in-objective-c.html">"Zeroing Weak References" writeup</a> is correct, weak references are like <code>assign</code> references without ARC. However, if the referenced object is deallocated, instead of getting a "dangling pointer" (meaning a pointer that points to a deallocated object), the pointer gets set to <code>nil</code>. </p>
<p>Is this right, and <strong>does this happen with any property marked <code>weak</code> or <code>assign</code> (when ARC is active)?</strong></p>
<p>If this is correct, this would eliminate a lot of SIGABRTs.</p> | 7,246,584 | 1 | 0 | null | 2011-08-30 16:26:18.143 UTC | 9 | 2011-12-29 17:26:17.19 UTC | 2011-12-29 17:26:17.19 UTC | null | 165,050 | null | 8,047 | null | 1 | 45 | objective-c|clang|automatic-ref-counting | 11,389 | <p>It's mostly right, but <code>assign</code> properties are still treated the same as they ever were, only <code>weak</code> ones are zeroing. Another caveat is that zeroing weak references are only available in Mac OS X ≥ 10.7 and iOS ≥ 5. While the rest of ARC was backported to 10.6 and iOS 4, weak references cannot be used at all on these OS's.</p> |
2,688,986 | How are lists implemented in Haskell (GHC)? | <p>I was just curious about some exact implementation details of lists in Haskell (GHC-specific answers are fine)--are they naive linked lists, or do they have any special optimizations? More specifically:</p>
<ol>
<li>Do <code>length</code> and <code>(!!)</code> (for instance) have to iterate through the list?</li>
<li>If so, are their values cached in any way (i.e., if I call <code>length</code> twice, will it have to iterate both times)?</li>
<li>Does access to the back of the list involve iterating through the whole list?</li>
<li>Are infinite lists and list comprehensions memoized? (i.e., for <code>fib = 1:1:zipWith (+) fib (tail fib)</code>, will each value be computed recursively, or will it rely on the previous computed value?)</li>
</ol>
<p>Any other interesting implementation details would be much appreciated. Thanks in advance!</p> | 2,689,376 | 3 | 1 | null | 2010-04-22 07:35:17.527 UTC | 11 | 2017-05-30 22:13:09.35 UTC | null | null | null | null | 294,505 | null | 1 | 50 | haskell|linked-list|ghc | 12,890 | <p>Lists have no special operational treatment in Haskell. They are defined just like:</p>
<pre><code>data List a = Nil | Cons a (List a)
</code></pre>
<p>Just with some special notation: <code>[a]</code> for <code>List a</code>, <code>[]</code> for <code>Nil</code> and <code>(:)</code> for <code>Cons</code>. If you defined the same and redefined all the operations, you would get the exact same performance.</p>
<p>Thus, Haskell lists are singly-linked. Because of laziness, they are often used as iterators. <code>sum [1..n]</code> runs in constant space, because the unused prefixes of this list are garbage collected as the sum progresses, and the tails aren't generated until they are needed.</p>
<p>As for #4: <em>all</em> values in Haskell are memoized, with the exception that functions do not keep a memo table for their arguments. So when you define <code>fib</code> like you did, the results will be cached and the nth fibonacci number will be accessed in O(n) time. However, if you defined it in this apparently equivalent way:</p>
<pre><code>-- Simulate infinite lists as functions from Integer
type List a = Int -> a
cons :: a -> List a -> List a
cons x xs n | n == 0 = x
| otherwise = xs (n-1)
tailF :: List a -> List a
tailF xs n = xs (n+1)
fib :: List Integer
fib = 1 `cons` (1 `cons` (\n -> fib n + tailF fib n))
</code></pre>
<p>(Take a moment to note the similarity to your definition)</p>
<p>Then the results are not shared and the nth fibonacci number will be accessed in O(fib n) (which is exponential) time. You can convince functions to be shared with a memoization library like <a href="http://hackage.haskell.org/package/data-memocombinators" rel="noreferrer">data-memocombinators</a>.</p> |
2,583,966 | How do I use PackageManager.addPreferredActivity()? | <p>In SDK 1.5 I was using the PackageManager class to set the preferred home screen to be my app using PackageManager.addPackageToPreferred(). In the new SDK (using 2.1) this has been deprecated so I'm trying to use addPreferredActivity() for the same result but it's not working as expected.</p>
<p>Some necessary background. I'm writing a lock screen replacement app so I want the home key to launch my app (which will already be running, hence having the effect of disabling the key). When the user "unlocks" the screen I intend to restore the mapping so everything works as normal.</p>
<p>In my AndroidManifest.xml I have:</p>
<pre><code><intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.HOME"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<uses-permission android:name="android.permission.SET_PREFERRED_APPLICATIONS">
</uses-permission>
</code></pre>
<p>In my code I have the following snippet:</p>
<pre><code>// Set as home activity
// This is done so we can appear to disable the Home key.
PackageManager pm = getPackageManager();
//pm.addPackageToPreferred(getPackageName());
IntentFilter filter = new IntentFilter("android.intent.action.MAIN");
filter.addCategory("android.intent.category.HOME");
filter.addCategory("android.intent.category.DEFAULT");
ComponentName[] components = new ComponentName[]
{
new ComponentName("com.android.launcher", ".Launcher")
};
Context context = getApplicationContext();
ComponentName component = new ComponentName(context.getPackageName(),
MyApp.class.getName());
pm.clearPackagePreferredActivities("com.android.launcher");
pm.addPreferredActivity(filter, IntentFilter.MATCH_CATEGORY_EMPTY,
components, component);
</code></pre>
<p>The resulting behavior is that the app chooser comes up when I press the Home key, which indicates that the clearPackagePreferredActivities() call worked but my app did not get added as the preferred. Also, the first line in the log below says something about "dropping preferred activity for Intent":</p>
<blockquote>
<p>04-06 02:34:42.379: INFO/PackageManager(1017): Result set changed, dropping preferred activity for Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 } type null</p>
<p>04-06 02:34:42.379: INFO/ActivityManager(1017): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=android/com.android.internal.app.ResolverActivity }</p>
</blockquote>
<p>Does anyone know what this first log message means? Maybe I'm not using the API correctly, any ideas? Any help would be greatly appreciated.</p> | 2,788,780 | 4 | 1 | null | 2010-04-06 10:02:57.42 UTC | 11 | 2014-08-28 07:17:52.99 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 309,885 | null | 1 | 19 | android|android-sdk-2.1 | 33,978 | <p>@afonseca: I was dealing with the same problem. Thanks for the code, I used it to start with. Also thanks Shimon. I merged his answer into mine. I've got the code working (on 1.6 and 2.1 update 1). It has been adjusted a little bit, but the 2 main change seem to be Shimons suggestion and: ".Launcher" was changed to "com.android.launcher.Launcher". The working code is posted below. </p>
<p>Ciao, a2ronus</p>
<pre><code>PackageManager pm = getPackageManager();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.MAIN");
filter.addCategory("android.intent.category.HOME");
filter.addCategory("android.intent.category.DEFAULT");
Context context = getApplicationContext();
ComponentName component = new ComponentName(context.getPackageName(), TestReplaceHomeAppActivity.class.getName());
ComponentName[] components = new ComponentName[] {new ComponentName("com.android.launcher", "com.android.launcher.Launcher"), component};
pm.clearPackagePreferredActivities("com.android.launcher");
pm.addPreferredActivity(filter, IntentFilter.MATCH_CATEGORY_EMPTY, components, component);
</code></pre> |
2,789,741 | How can I set the background color of <option> in a <select> element? | <p>How do you set the background color of an item in an HTML list?</p> | 2,789,768 | 4 | 0 | null | 2010-05-07 15:33:49.737 UTC | 2 | 2020-07-08 12:39:10.763 UTC | 2020-07-08 12:37:09.96 UTC | null | 247,696 | null | 335,589 | null | 1 | 39 | html|select|background-color | 154,504 | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>select.list1 option.option2
{
background-color: #007700;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select class="list1">
<option value="1">Option 1</option>
<option value="2" class="option2">Option 2</option>
</select></code></pre>
</div>
</div>
</p> |
37,286,574 | How can configure my y-axis on chart.js? | <p>I am trying to build graph.</p>
<p>My y-axis start with 0 here, I dont know how to configure it and why it is talking 0 - I see other post which mentioned scaleOverride:true, scaleStartValue:0.1, scaleStepWidth:5 - I dont know how to use that in my below code , how can configure y-axis in chart.js.</p>
<p>Any pointer would be </p>
<p>I have following code </p>
<pre><code>var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
backgroundColor: "rgba(220,220,220,0.5)",
data: [6, 6, 6, 8, 6, 9, 8]
}]
};
function barChart() {
var context = document.getElementById('stacked').getContext('2d');
var myBar = new Chart(context, {
type: 'bar',
data: barChartData,
options: {
title:{
display:true,
text:"Chart.js Bar Chart - Stacked"
},
tooltips: {
mode: 'label'
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
};
$(document).ready(function() {
$(document).ready(barChart);
});
</code></pre> | 37,394,468 | 2 | 0 | null | 2016-05-17 21:31:53.79 UTC | 2 | 2018-02-27 19:50:16.28 UTC | 2018-02-27 19:50:16.28 UTC | user8280225 | null | null | 5,199,120 | null | 1 | 5 | charts|chart.js | 39,908 | <p>Thank you guys for helping, I observed that chart.js will automatically take value for y-axis based on your data, you can change y/x-axis setting under Options > Scales , I also needed to change step size of y-axis and get rid of x-axis grid line,"ticks" is something I was looking for, here is my sample code and steps to achieved all these.</p>
<p>Step 1) Canvas this is place holder where your chart will display on JSP </p>
<pre><code><canvas width="1393px;" height="500px;" id="stacked"></canvas>
</code></pre>
<p>Step 2) Create sample datasets (this is JSON you need to create based on your requirement but make sure you provide exact the same formated JSON response as given below along with your data.</p>
<pre><code>var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
backgroundColor: "red",
data: [9, 6, 6, 8, 6, 9, 8]
},
{
label: 'Dataset 1',
backgroundColor: "rgba(225,226,228,0.5)",
data: [9, 6, 6, 8, 6, 9, 8]
}]
};
or you can call JSON from controller inside script as below
var jsonArry = <%=request.getAttribute("jsonArry")%>;
</code></pre>
<p>Step 3) call that JSON which you have created at step 2 </p>
<pre><code> function barChart(){
var context = document.getElementById('stacked').getContext('2d');
var myBar = new Chart(context, {
type: 'bar',
data: jsonArry,
options: {
tooltips: {
mode: 'label'
},
responsive: true,
scales: {
xAxes: [{
ticks:{
stepSize : 10,
},
stacked: true,
gridLines: {
lineWidth: 0,
color: "rgba(255,255,255,0)"
}
}],
yAxes: [{
stacked: true,
ticks: {
min: 0,
stepSize: 1,
}
}]
}
}
});
};
</code></pre>
<p>Hope this will help , for reference I have used following documentation <a href="http://www.chartjs.org/docs/" rel="noreferrer">Chart JS</a></p>
<p>Thanks.</p> |
38,161,697 | How to remove one track from video file using ffmpeg? | <p>How to remove only one track (not all) from video file container (.vob or .mkv) using ffmpeg?</p>
<p>I know I can just copy video (<code>-c:v copy -an</code>) and specific audio track from container into two separated files and then join them. </p>
<p>But is there an easier way? Can I just remove specific audio track from container? ffmpeg command?</p> | 38,162,168 | 4 | 1 | null | 2016-07-02 15:28:44.737 UTC | 32 | 2021-12-13 00:09:45.397 UTC | 2016-07-02 16:46:53.4 UTC | null | 4,548,520 | null | 4,548,520 | null | 1 | 64 | video|ffmpeg | 62,772 | <p>The most efficient method is to use <a href="https://ffmpeg.org/ffmpeg.html#Advanced-options" rel="noreferrer">negative mapping</a> in the <code>-map</code> option to exclude specific stream(s) ("tracks") while keeping all other streams.</p>
<h1>Remove a specific audio stream / track</h1>
<pre><code>ffmpeg -i input -map 0 -map -0:a:2 -c copy output
</code></pre>
<ul>
<li><code>-map 0</code> selects all streams from the input.</li>
<li><code>-map -0:a:2</code> then deselects audio stream 3. The stream index starts counting from 0, so audio stream 10 would be <code>0:a:9</code>.</li>
</ul>
<h1>Remove all audio streams / tracks</h1>
<pre><code>ffmpeg -i input -map 0 -map -0:a -c copy output
</code></pre>
<ul>
<li><code>-map 0</code> selects all streams from the input.</li>
<li><code>-map -0:a</code> then deselects all audio streams from the input.</li>
</ul>
<h1>Remove specific audio streams / tracks</h1>
<p>Keep everything except audio streams #4 (at offset 3) and #7 (at offset 6):</p>
<pre><code>ffmpeg -i input -map 0 -map -0:a:3 -map -0:a:6 -c copy output
</code></pre>
<h1>Remove all subtitles and data</h1>
<pre><code>ffmpeg -i input -map 0 -map -0:s -map -0:d -c copy output
</code></pre>
<h1>Only include video and audio</h1>
<p>This example does not need to use any negative mapping.</p>
<pre><code>ffmpeg -i input -map 0:v -map 0:a -c copy output
</code></pre>
<h1>Removing other stream / track types</h1>
<p>If you want to remove other stream types you can use the appropriate <a href="https://ffmpeg.org/ffmpeg.html#Stream-specifiers-1" rel="noreferrer">stream specifier</a>.</p>
<ul>
<li><code>v</code> - video, such as <code>-map -0:v</code></li>
<li><code>a</code> - audio, such as <code>-map -0:a</code> (as shown above)</li>
<li><code>s</code> - subtitles, such as <code>-map -0:s</code></li>
<li><code>d</code> - data, such as <code>-map -0:d</code></li>
<li><code>t</code> - attachments, such as <code>-map -0:t</code></li>
</ul>
<h1>Extract or remove a specific audio channel</h1>
<p>Using a stereo input and <a href="https://ffmpeg.org/ffmpeg-filters.html#channelsplit" rel="noreferrer">channelsplit</a> filter. Example to get the right channel only and output a mono audio file:</p>
<pre><code>ffmpeg -i stereo.wav -filter_complex "[0:a]channelsplit=channel_layout=stereo:channels=FR[right]" -map "[right]" front_right.wav
</code></pre>
<ul>
<li><p><code>channel_layout</code> is the channel layout of the input stream. The default is <code>stereo</code>.</p>
</li>
<li><p><code>channels</code> lists the channels to be extracted as separate output streams. The default is <code>all</code> which extracts each input channel as a separate, individual stream.</p>
</li>
<li><p>See <code>ffmpeg -layouts</code> for a list of accepted channel layouts (for <code>channel_layout</code> option) and channel names (for <code>channels</code> option).</p>
</li>
<li><p>See <a href="https://trac.ffmpeg.org/wiki/AudioChannelManipulation" rel="noreferrer">FFmpeg Wiki: Audio Channels</a> for more examples.</p>
</li>
</ul>
<h1>More info</h1>
<ul>
<li><a href="https://ffmpeg.org/ffmpeg.html#Advanced-options" rel="noreferrer"><code>-map</code> option documentation</a></li>
<li><a href="https://trac.ffmpeg.org/wiki/Map" rel="noreferrer">FFmpeg Wiki: Map</a></li>
</ul> |
1,070,828 | jQuery add blank option to top of list and make selected to existing dropdown | <p>So I have a dropdown list</p>
<pre><code><select id="theSelectId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</code></pre>
<p>This is what I would like</p>
<pre><code><select id="theSelectId">
<option value="" selected="selected"></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</code></pre>
<p>Trying to add a blank option before and set it to this, want to enforce the user to select a value from the original list but would like it to be blank when they see the option they have to choose.</p>
<p>Trying this but not working</p>
<pre><code>// Add blank option
var blankOption = {optVal : ''};
$.each(blankOption, function(optVal, text) {
$('<option></option>').val(optVal).html(text).preprendTo('#theSelectId');
});
</code></pre>
<p>and I have tried this but is clears out the other values</p>
<pre><code>$('#theSelectId option').prependTo('<option value=""></option>');
</code></pre> | 1,070,841 | 2 | 0 | null | 2009-07-01 19:12:43.58 UTC | 12 | 2019-05-07 07:22:28.657 UTC | null | null | null | null | 93,966 | null | 1 | 67 | jquery|select|drop-down-menu | 130,668 | <p>This worked:</p>
<pre><code>$("#theSelectId").prepend("<option value='' selected='selected'></option>");
</code></pre>
<p>Firebug Output:</p>
<pre><code><select id="theSelectId">
<option selected="selected" value=""/>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</code></pre>
<p>You could also use <code>.prependTo</code> if you wanted to reverse the order:</p>
<pre><code>$("<option>", { value: '', selected: true }).prependTo("#theSelectId");
</code></pre> |
1,306,869 | Are nested transactions allowed in MySQL? | <p>Does MySQL allow the use of nested transactions?</p> | 1,306,880 | 2 | 1 | null | 2009-08-20 15:14:23.14 UTC | 27 | 2021-12-28 19:48:04.38 UTC | 2011-07-01 03:09:41.913 UTC | null | 9,314 | null | 89,771 | null | 1 | 107 | mysql|transactions|nested-transactions | 47,580 | <h3>No, but</h3>
<p><code>InnoDB</code> supports <code>SAVEPOINTS</code>.</p>
<p>You can do the following:</p>
<pre><code>CREATE TABLE t_test (id INT NOT NULL PRIMARY KEY) ENGINE=InnoDB;
START TRANSACTION;
INSERT
INTO t_test
VALUES (1);
SELECT *
FROM t_test;
id
---
1
SAVEPOINT tran2;
INSERT
INTO t_test
VALUES (2);
SELECT *
FROM t_test;
id
---
1
2
ROLLBACK TO tran2;
SELECT *
FROM t_test;
id
---
1
ROLLBACK;
SELECT *
FROM t_test;
id
---
</code></pre> |
2,873,254 | Difference between a deprecated and a legacy API? | <p>I was studying the legacy API's in the Java's <code>Collection Framework</code> and I learnt that classes such as <code>Vector</code> and <code>HashTable</code> have been superseded by <code>ArrayList</code> and <code>HashMap</code>.</p>
<p>However still they are NOT deprecated, and deemed as legacy when essentially, deprecation is applied to software features that are superseded and should be avoided, so, I am not sure when is a API deemed legacy and when it is deprecated.</p> | 2,873,340 | 7 | 3 | null | 2010-05-20 11:36:19.603 UTC | 11 | 2011-07-31 06:13:08.617 UTC | 2011-07-31 06:13:08.617 UTC | null | 1,140,524 | null | 1,140,524 | null | 1 | 34 | java|collections|terminology | 12,503 | <p>From the official Sun glossary:</p>
<blockquote>
<p><strong>deprecation</strong>: Refers to a class, interface, constructor, method or field that is no longer recommended, and may cease to exist in a future version.</p>
</blockquote>
<p>From the how-and-when to deprecate guide:</p>
<blockquote>
<p>You may have heard the term, "self-deprecating humor," or humor that minimizes the speaker's importance. A deprecated class or method is like that. It is no longer important. It is so unimportant, in fact, that you should no longer use it, since it has been superseded and may cease to exist in the future.</p>
</blockquote>
<p>The <code>@Deprecated</code> annotation went a step further and warn of danger:</p>
<blockquote>
<p>A program element annotated <code>@Deprecated</code> is one that programmers are discouraged from using, typically because it is <em>dangerous</em>, or because a better alternative exists.</p>
</blockquote>
<h3>References</h3>
<ul>
<li><a href="http://java.sun.com/docs/glossary.html" rel="noreferrer">java.sun.com Glossary</a></li>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/deprecation/deprecation.html" rel="noreferrer">Language guide/How and When to Deprecate APIs</a></li>
<li><a href="http://java.sun.com/javase/6/docs/api/java/lang/Deprecated.html" rel="noreferrer">Annotation Type Deprecated API</a></li>
</ul>
<hr />
<p>Note that the official glossary does not define what "legacy" means. In all likelihood, it may be a term that Josh Bloch used without an exact definition. The implication, though, is always that a legacy class should never be used in new code, and better replacement exists.</p>
<p>Perhaps an old code using legacy but non-deprecated class requires no action, since for now at least, they aren't in danger of ceasing to exist in future version.</p>
<p>In contrast, deprecation explicitly warns that they may cease to exist, so action should be taken to migrate to the replacement.</p>
<hr />
<h3>Quotes from Effective Java 2nd Edition</h3>
<p>For comparison on how these terms are used in context, these are quotes from the book where the word <em>"deprecated"</em> appears:</p>
<blockquote>
<p><strong>Item 7: Avoid finalizers</strong>: The only methods that claim to guarantee finalization are <code>System.runFinalizersOnExit</code> and its evil twin <code>Runtime.runFinalizersOnExit</code>. These methods are fatally flawed and have been deprecated.</p>
<p><strong>Item 66: Synchronize access to shared mutable data</strong>: The libraries provide the <code>Thread.stop</code> method, but this method was deprecated long ago because it's inherently <em>unsafe</em> -- its use can result in data corruption.</p>
<p><strong>Item 70: Document thread safety</strong>: The <code>System.runFinalizersOnExit</code> method is thread-hostile and has been deprecated.</p>
<p><strong>Item 73: Avoid thread groups</strong>: They allow you to apply certain <code>Thread</code> primitives to a bunch of threads at once. Several of these primitives have been deprecated, and the remainder are infrequently used. [...] thread groups are obsolete.</p>
</blockquote>
<p>By contrast, these are the quotes where the word <em>"legacy"</em> appears:</p>
<blockquote>
<p><strong>Item 23: Don't use raw types in new code</strong>: They are provided for compatibility and interoperability with legacy code that predates the introduction of generics.</p>
<p><strong>Item 25: Prefer lists to arrays</strong>: Erasure is what allows generic types to interoperate freely with legacy code that does not use generics.</p>
<p><strong>Item 29: Consider typesafe heterogeneous containers</strong>: These wrappers are useful for tracking down who adds an incorrectly typed element to a collection in an application that mixes generic and legacy code.</p>
<p><strong>Item 54: Use native methods judiciously</strong>: They provide access to libraries of legacy code, which could in turn provide access to legacy data. [...] It is also legitimate to use native methods to access legacy code. [...] If you must use native methods to access low-level resources or legacy libraries, use as little native code as possible and test it thoroughly.</p>
<p><strong>Item 69: Prefer concurrency utilities to wait and notify</strong>: While you should always use the concurrency utilities in preference to <code>wait</code> and <code>notify</code>, you might have to maintain legacy code that uses <code>wait</code> and <code>notify</code>.</p>
</blockquote>
<p>These quotes were not carefully selected: they're ALL instances where the word <em>"deprecated"</em> and <em>"legacy"</em> appear in the book. Bloch's message is clear here:</p>
<ul>
<li>Deprecated methods, e.g. <code>Thread.stop</code>, are dangerous, and should <em>never</em> be used at all.</li>
<li>On the other hand, e.g. <code>wait/notify</code> can stay in legacy code, but should not be used in new code.</li>
</ul>
<hr />
<h3>My own subjective opinion</h3>
<p>My interpretation is that deprecating something is admitting that it is a mistake, and was never good to begin with. On the other hand, classifying that something is a legacy is admitting that it was good enough in the past, but it has served its purpose and is no longer good enough for the present and the future.</p> |
2,539,021 | How to set the width of a cell in a UITableView in grouped style | <p>I have been working on this for about 2 days, so i thought i share my learnings with you.</p>
<p>The question is: Is it possible to make the width of a cell in a grouped UITableView smaller?</p>
<p>The answer is: No.</p>
<p>But there are two ways you can get around this problem.</p>
<p><strong>Solution #1: A thinner table</strong>
It is possible to change the frame of the tableView, so that the table will be smaller. This will result in UITableView rendering the cell inside with the reduced width.</p>
<p>A solution for this can look like this:</p>
<pre><code>-(void)viewWillAppear:(BOOL)animated
{
CGFloat tableBorderLeft = 20;
CGFloat tableBorderRight = 20;
CGRect tableRect = self.view.frame;
tableRect.origin.x += tableBorderLeft; // make the table begin a few pixels right from its origin
tableRect.size.width -= tableBorderLeft + tableBorderRight; // reduce the width of the table
tableView.frame = tableRect;
}
</code></pre>
<p><strong>Solution #2: Having cells rendered by images</strong></p>
<p>This solution is described here: <a href="http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html" rel="noreferrer">http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html</a></p>
<p>I hope this information is helpful to you. It took me about 2 days to try a lot of possibilities. This is what was left.</p> | 7,321,461 | 7 | 1 | 2010-03-29 15:15:18.52 UTC | 2010-03-29 15:14:19.413 UTC | 64 | 2019-05-20 20:09:37.76 UTC | 2019-05-20 20:09:37.76 UTC | null | 2,272,431 | null | 170,176 | null | 1 | 108 | ios|iphone|uitableview|width | 96,634 | <p>A better and cleaner way to achieve this is subclassing UITableViewCell and overriding its <code>-setFrame:</code> method like this:</p>
<pre><code>- (void)setFrame:(CGRect)frame {
frame.origin.x += inset;
frame.size.width -= 2 * inset;
[super setFrame:frame];
}
</code></pre>
<p>Why is it better? Because the other two are worse.</p>
<ol>
<li><p>Adjust table view width in <code>-viewWillAppear:</code></p>
<p>First of all, this is unreliable, the superview or parent view controller may adjust table view frame further after <code>-viewWillAppear:</code> is called. Of course, you can subclass and override <code>-setFrame:</code> for your UITableView just like what I do here for UITableViewCells. However, subclassing UITableViewCells is a much common, light, and Apple way.</p>
<p>Secondly, if your UITableView have backgroundView, you don't want its backgroundView be narrowed down together. Keeping backgroundView width while narrow down UITableView width is not trivial work, not to mention that expanding subviews beyond its superview is not a very elegant thing to do in the first place.</p></li>
<li><p>Custom cell rendering to fake a narrower width</p>
<p>To do this, you have to prepare special background images with horizontal margins, and you have to layout subviews of cells yourself to accommodate the margins.
In comparison, if you simply adjust the width of the whole cell, autoresizing will do all the works for you.</p></li>
</ol> |
2,362,186 | Debugger for OpenCL | <p>I am working on OpenCL. Does anyone know of a good debugger for OpenCL so that I can step into the OpenCL code and trace?</p> | 2,371,691 | 8 | 0 | null | 2010-03-02 09:49:45.01 UTC | 17 | 2017-09-19 22:19:30.987 UTC | 2016-04-20 22:49:19.24 UTC | null | 41,071 | null | 236,555 | null | 1 | 42 | opencl | 25,302 | <p>Perhaps Gremedy's OpenCL debugger would be helpful?
<a href="http://www.gremedy.com/gDEBuggerCL.php" rel="noreferrer">http://www.gremedy.com/gDEBuggerCL.php</a></p> |
2,636,153 | How can I get TFS2010 to run MSDEPLOY for me through MSBUILD? | <p>There is an excellent PDC talk <a href="http://microsoftpdc.com/Sessions/FT56?type=wmv" rel="noreferrer">available here</a> from Vishal Joshi which describes the new MSDEPLOY features in Visual Studio 2010 - as well as how to deploy an application within TFS. (There's also a great talk from <a href="http://www.hanselman.com/blog/WebDeploymentMadeAwesomeIfYoureUsingXCopyYoureDoingItWrong.aspx" rel="noreferrer">Scott</a> Hanselman but he doesn't go into TFS).</p>
<p>You can use MSBUILD within TFS2010 to call through to MSDEPLOY to deploy your package to IIS. This is done by means of parameters to MSBUILD.</p>
<p>The talk explains some of the command line parameters such as :</p>
<pre><code>/p:DeployOnBuild
/p:DeployTarget=MsDeployPublish
/p:CreatePackageOnPublish=True
/p:MSDeployPublishMethod=InProc
/p:MSDeployServiceURL=localhost
/p:DeployIISAppPath="Default Web Site"
</code></pre>
<p><strong>But where is the documentation for this - I can't find any?</strong></p>
<p>I've been spending all day trying to get this to work and can't quite get it right and keep ending up with various errors. If I run the package's <code>cmd</code> file it deploys perfectly. If I run WebDeploy through Visual Studio it also works perfectly.</p>
<p>But I want to get the whole deployment running through <code>msbuild</code> using these arguments and not a separate call to <code>msdeploy</code> or running the package <code>.cmd</code> file. How can I do this?</p>
<p>PS. Yes I do have the <code>Web Deployment Agent Service</code> running. I also have the management service running under IIS. I've tried using both.</p>
<hr>
<p>Args I'm using :</p>
<pre><code>/p:DeployOnBuild=True
/p:DeployTarget=MsDeployPublish
/p:Configuration=Release
/p:CreatePackageOnPublish=True
/p:DeployIisAppPath=staging.example.com
/p:MsDeployServiceUrl=https://staging.example.com:8172/msdeploy.axd
/p:AllowUntrustedCertificate=True
</code></pre>
<p>giving me :</p>
<p>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets (2660): VsMsdeploy failed.(Remote agent (URL <a href="https://staging.example.com:8172/msdeploy.axd?site=staging.example.com" rel="noreferrer">https://staging.example.com:8172/msdeploy.axd?site=staging.example.com</a>) could not be contacted. Make sure the remote agent service is installed and started on the target computer.) Error detail: Remote agent (URL <a href="https://staging.example.com:8172/msdeploy.axd?site=staging.example.com" rel="noreferrer">https://staging.example.com:8172/msdeploy.axd?site=staging.example.com</a>) could not be contacted. Make sure the remote agent service is installed and started on the target computer. An unsupported response was received. The response header 'MSDeploy.Response' was '' but 'v1' was expected. The remote server returned an error: (401) Unauthorized.</p> | 5,867,846 | 8 | 5 | null | 2010-04-14 09:11:24 UTC | 66 | 2012-02-02 14:18:39.057 UTC | 2010-04-17 02:33:45.007 UTC | null | 77,914 | null | 16,940 | null | 1 | 78 | visual-studio-2010|msbuild|msdeploy | 38,491 | <h3>IIS7 + related answer ....</h3>
<p>Ok - here's what I ended up doing. More or less, following the post by <a href="https://stackoverflow.com/users/16940/simon-weaver">Simon Weaver</a> in this thread/question.</p>
<p>But when it comes to the MSBuild settings .. most people here are using following setting: <code>/p:MSDeployPublishMethod=RemoteAgent</code> which is <strong>NOT RIGHT</strong> for IIS7. Using this setting means TFS tries to connect to the url: <code>https://your-server-name/MSDEPLOYAGENTSERVICE</code> But to access that url, the user to authenticate needs to be an Admin. Which is fraked. (And you need to have the Admin-override rule thingy ticked). This url is for IIS6 I think.</p>
<p>Here's the standard error message when you try to connect using RemoteAgent :-</p>
<h3>Standard 401 Frak Off u suck RemoteAgent, error</h3>
<blockquote>
<p>C:\Program Files
(x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets
(3588): Web deployment task
failed.(Remote agent (URL
<a href="http://your-web-server/MSDEPLOYAGENTSERVICE" rel="nofollow noreferrer">http://your-web-server/MSDEPLOYAGENTSERVICE</a>)
could not be contacted. Make sure the
remote agent service is installed and
started on the target computer.) Make
sure the site name, user name, and
password are correct. If the issue is
not resolved, please contact your
local or server administrator. Error
details: Remote agent (URL
<a href="http://your-web-server/MSDEPLOYAGENTSERVICE" rel="nofollow noreferrer">http://your-web-server/MSDEPLOYAGENTSERVICE</a>)
could not be contacted. Make sure the
remote agent service is installed and
started on the target computer. An
unsupported response was received. The
response header 'MSDeploy.Response'
was 'V1' but 'v1' was expected. The
remote server returned an error: (401)
Unauthorized.</p>
</blockquote>
<p>So .. you need to change your <code>MSDeployPublishMethod</code> to this:</p>
<pre><code>/p:MSDeployPublishMethod=WMSVC
</code></pre>
<p>The <code>WMSVC</code> stands for Windows Manager Service. It's basically a newer wrapper over the Remote Agent but now allows us to correct provide a user name and password .. where the user does NOT have to be an admin! (joy!) So now you can correct set which users u want to have access to .. per WebSite ..</p>
<p><img src="https://i.stack.imgur.com/QxD1j.png" alt="enter image description here"></p>
<p>It also now tries to hit the the url: <code>https://your-web-server:8172/MsDeploy.axd</code> <-- which is EXACTLY what the Visual Studio 2010 <code>Publish</code> window does! <strong>(OMG -> PENNY DROPS!! BOOM!)</strong></p>
<p><img src="https://i.stack.imgur.com/rpow7.png" alt="enter image description here"></p>
<p>And here's my final MSBuild settings:</p>
<pre><code>/p:DeployOnBuild=True
/p:DeployTarget=MSDeployPublish
/p:MSDeployPublishMethod=WMSVC
/p:MsDeployServiceUrl=your-server-name
/p:DeployIISAppPath=name-of-the-website-in-iis7
/p:username=AppianMedia\some-domain-user
/p:password=JonSkeet<3<3<3
/p:AllowUntrustedCertificate=True
</code></pre>
<p>Notice the username has the domain name in it? Ya need that, there. Also, in my picture, I've allowed our DOMAIN USERS access to the website for managament. As such, my new user account i added (TFSBuildService) has Membership to the <code>Domain Users</code> group ... so that's how it all works.</p>
<p>Now - if u've read all this, have a lolcat (cause they are SOOOOOOOO 2007)....</p>
<p><img src="https://i.stack.imgur.com/g2FpH.jpg" alt="enter image description here"></p> |
3,200,211 | What does immutable mean? | <p>If a string is immutable, does that mean that....
(let's assume JavaScript)</p>
<pre><code>var str = 'foo';
alert(str.substr(1)); // oo
alert(str); // foo
</code></pre>
<p>Does it mean, when calling methods on a string, it will return the modified string, but it won't change the initial string?</p>
<p>If the string was mutable, does that mean the 2nd <code>alert()</code> would return <code>oo</code> as well?</p> | 3,200,221 | 10 | 0 | null | 2010-07-08 01:54:27.197 UTC | 48 | 2022-05-08 11:57:05.71 UTC | 2010-07-08 10:32:42.13 UTC | null | 31,671 | null | 31,671 | null | 1 | 110 | javascript|variables|immutability | 40,066 | <p>It means that once you instantiate the object, you can't change its properties. In your first alert you aren't changing foo. You're creating a new string. This is why in your second alert it will show "foo" instead of oo.</p>
<blockquote>
<p>Does it mean, when calling methods on
a string, it will return the modified
string, but it won't change the
initial string?</p>
</blockquote>
<p>Yes. Nothing can change the string once it is created. Now this doesn't mean that you can't assign a new string object to the <code>str</code> variable. You just can't change the current object that str references.</p>
<blockquote>
<p>If the string was mutable, does that
mean the 2nd alert() would return oo
as well?</p>
</blockquote>
<p>Technically, no, because the substring method returns a new string. Making an object mutable, wouldn't change the method. Making it mutable means that technically, you could make it so that substring would change the original string instead of creating a new one.</p> |
3,168,484 | PendingIntent works correctly for the first notification but incorrectly for the rest | <pre><code> protected void displayNotification(String response) {
Intent intent = new Intent(context, testActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification = new Notification(R.drawable.icon, "Upload Started", System.currentTimeMillis());
notification.setLatestEventInfo(context, "Upload", response, pendingIntent);
nManager.notify((int)System.currentTimeMillis(), notification);
}
</code></pre>
<p>This function will be called multiple times. I would like for each <code>notification</code> to launch testActivity when clicked. Unfortunately, only the first notification launches testActivity. Clicking on the rest cause the notification window to minimize.</p>
<p>Extra information: Function <code>displayNotification()</code> is in a class called <code>UploadManager</code>. <code>Context</code> is passed into <code>UploadManager</code> from the <code>activity</code> that instantiates. Function <code>displayNotification()</code> is called multiple times from a function, also in UploadManager, that is running in an <code>AsyncTask</code>.</p>
<p>Edit 1: I forgot to mention that I am passing String response into <code>Intent intent</code> as an <code>extra</code>.</p>
<pre><code> protected void displayNotification(String response) {
Intent intent = new Intent(context, testActivity.class);
intent.putExtra("response", response);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
</code></pre>
<p>This makes a big difference because I need the extra "response" to reflect what String response was when the notification was created. Instead, using <code>PendingIntent.FLAG_UPDATE_CURRENT</code>, the extra "response" reflects what String response was on the last call to <code>displayNotification()</code>.</p>
<p>I know why this is from reading the documentation on <code>FLAG_UPDATE_CURRENT</code>. However, I am not sure how to work around it at the moment.</p> | 3,168,653 | 14 | 0 | null | 2010-07-02 19:11:29.127 UTC | 38 | 2021-07-07 16:11:14.433 UTC | 2017-03-30 08:51:50.393 UTC | user350617 | 4,286,992 | user350617 | null | null | 1 | 95 | android|notifications|android-pendingintent | 86,514 | <p>Don't use <code>Intent.FLAG_ACTIVITY_NEW_TASK</code> for PendingIntent.getActivity, use <a href="http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_ONE_SHOT" rel="noreferrer">FLAG_ONE_SHOT</a> instead</p>
<hr>
<p><strong>Copied from comments:</strong></p>
<p>Then set some dummy action on the Intent, otherwise extras are dropped. For example</p>
<pre><code>intent.setAction(Long.toString(System.currentTimeMillis()))
</code></pre> |
23,584,325 | Cannot use geometry manager pack inside | <p>So I'm making an rss reader using the tkinter library, and in one of my methods I create a text widget. It displays fine until I try to add scrollbars to it.</p>
<p>Here is my code before the scrollbars: </p>
<pre><code> def create_text(self, root):
self.textbox = Text(root, height = 10, width = 79, wrap = 'word')
self.textbox.grid(column = 0, row = 0)
</code></pre>
<p>Here is my code after:</p>
<pre><code>def create_text(self, root):
self.textbox = Text(root, height = 10, width = 79, wrap = 'word')
vertscroll = ttk.Scrollbar(root)
vertscroll.config(command=self.textbox.yview)
vertscroll.pack(side="right", fill="y", expand=False)
self.textbox.config(yscrllcommand=vertscroll.set)
self.textbox.pack(side="left", fill="both", expand=True)
self.textbox.grid(column = 0, row = 0)
</code></pre>
<p>This gives me the error </p>
<blockquote>
<p>_tkinter.TclError: cannot use geometry manager pack inside .56155888 which already has slaves managed by grid on the line
vertscroll.pack(side="right", fill="y", expand=False)</p>
</blockquote>
<p>Any ideas how to fix this?</p> | 23,584,607 | 3 | 0 | null | 2014-05-10 17:40:16.233 UTC | 11 | 2022-06-30 08:47:10.287 UTC | 2014-09-17 19:10:29.24 UTC | null | 3,489,230 | null | 3,623,888 | null | 1 | 37 | python|tkinter|geometry|scrollbar | 150,677 | <p>Per <a href="http://www.effbot.org/tkinterbook/grid.htm" rel="noreferrer">the docs</a>, don't mix <code>pack</code> and <code>grid</code> in the same master window:</p>
<blockquote>
<p>Warning: Never mix grid and pack in the same master window. Tkinter
will happily spend the rest of your lifetime trying to negotiate a
solution that both managers are happy with. Instead of waiting, kill
the application, and take another look at your code. A common mistake
is to use the wrong parent for some of the widgets.</p>
</blockquote>
<p>Thus, if you call <code>grid</code> on the textbox, do not call <code>pack</code> on the scrollbar.</p>
<hr>
<pre><code>import Tkinter as tk
import ttk
class App(object):
def __init__(self, master, **kwargs):
self.master = master
self.create_text()
def create_text(self):
self.textbox = tk.Text(self.master, height = 10, width = 79, wrap = 'word')
vertscroll = ttk.Scrollbar(self.master)
vertscroll.config(command=self.textbox.yview)
self.textbox.config(yscrollcommand=vertscroll.set)
self.textbox.grid(column=0, row=0)
vertscroll.grid(column=1, row=0, sticky='NS')
root = tk.Tk()
app = App(root)
root.mainloop()
</code></pre> |
33,550,983 | How to add a Spark Dataframe to the bottom of another dataframe? | <p>I can use <code>withcolumn</code>to add new columns to a Dataframe. But in scala how can I add new rows to a DataFrame? </p>
<p>I'm trying to add a dataframe to the bottom of another one. So either how to add rows in scala or how to add a DataFrame to the bottom of another one will help. Thanks</p> | 33,551,141 | 1 | 2 | null | 2015-11-05 17:26:16.167 UTC | 5 | 2017-02-01 13:55:15.763 UTC | null | null | null | null | 5,390,309 | null | 1 | 28 | scala|apache-spark|dataframe | 46,250 | <p>If they have the same schema, simply use <a href="http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.Dataset@union(other:org.apache.spark.sql.Dataset[T]):org.apache.spark.sql.Dataset[T]" rel="noreferrer"><code>union</code></a> for spark 2+:</p>
<pre><code>val dfUnion = df1.union(df2)
</code></pre>
<p>Or <code>unionAll</code> for spark 1+:</p>
<pre><code>val dfUnion = df1.unionAll(df2)
</code></pre> |
10,452,905 | How to run a PowerShell script as a job in Jenkins | <p>This sounds like a simple question, but I haven't been able to work it out after looking online. I basically want to execute a PowerShell script (e.g. script.ps1) in Jenkins and report success/failure.</p>
<p><strong>Try 1:</strong> Run following as "Execute Windows Batch Command"</p>
<pre><code>powershell -File c:\scripts\script.ps1
</code></pre>
<p>This starts up as expected, but it quits after a few seconds.</p>
<p><strong>Try 2:</strong> Run following as "Execute Windows Batch Command"</p>
<pre><code>powershell -NoExit -File c:\scripts\script.ps1
</code></pre>
<p>This runs the whole script successfully, but it never stops. I had to manually abort the script.</p> | 10,457,678 | 3 | 0 | null | 2012-05-04 16:44:55.84 UTC | 8 | 2022-03-23 20:17:02.843 UTC | 2019-06-17 07:12:08.707 UTC | null | 63,550 | null | 540,981 | null | 1 | 27 | powershell|jenkins|powershell-2.0 | 54,841 | <p>Well, there is a <a href="https://wiki.jenkins-ci.org/display/JENKINS/PowerShell+Plugin" rel="noreferrer">PowerShell</a> plugin, which is wrapping the shell anyway. I use this on my server, executing scripts in standard notation:</p>
<pre><code>powershell -File test001.ps1
</code></pre>
<p>It works without any quirks.</p> |
23,111,031 | What actually happens when using async/await inside a LINQ statement? | <p>The following snippet compiles, but I'd expect it to await the task result instead of giving me a <code>List<Task<T>></code>.</p>
<pre><code>var foo = bars.Select(async bar => await Baz(bar)).ToList()
</code></pre>
<p>As pointed out <a href="https://stackoverflow.com/a/21868161/247702">here</a>, you need to use <code>Task.WhenAll</code>:</p>
<pre><code>var tasks = foos.Select(async foo => await DoSomethingAsync(foo)).ToList();
await Task.WhenAll(tasks);
</code></pre>
<p>But <a href="https://stackoverflow.com/questions/21868087/how-to-await-a-list-of-tasks-asynchronously-using-linq#comment33110750_21868161">a comment</a> points out that the <code>async</code> and <code>await</code> inside the <code>Select()</code> is not needed:</p>
<pre><code>var tasks = foos.Select(foo => DoSomethingAsync(foo)).ToList();
</code></pre>
<p>A similar question <a href="https://codereview.stackexchange.com/questions/32160/filtering-a-collection-by-an-async-result">here</a> where someone tries to use an async method inside a <code>Where()</code>.</p>
<p>So <code>async</code> and <code>await</code> inside a LINQ statement is legal syntax, but does it do nothing at all or does it have a certain use?</p> | 23,113,336 | 2 | 0 | null | 2014-04-16 13:32:52.687 UTC | 11 | 2014-04-16 15:08:38.55 UTC | 2017-05-23 11:46:45.043 UTC | null | -1 | null | 247,702 | null | 1 | 28 | c#|linq|asynchronous|c#-5.0 | 13,955 | <p>I recommend that you not think of this as "using <code>async</code> within LINQ". Keep in mind what's in-between the two: delegates. Several LINQ operators take delegates, and <code>async</code> can be used to create an asynchronous delegate.</p>
<p>So, when you have an asynchronous method <code>BazAsync</code> that returns a <code>Task</code>:</p>
<pre><code>Task BazAsync(TBar bar);
</code></pre>
<p>then this code results in a sequence of tasks:</p>
<pre><code>IEnumerable<Task> tasks = bars.Select(bar => BazAsync(bar));
</code></pre>
<p>Similarly, if you use <code>async</code> and <code>await</code> within the delegate, you're creating an asynchronous delegate that returns a <code>Task</code>:</p>
<pre><code>IEnumerable<Task> tasks = bars.Select(async bar => await BazAsync(bar));
</code></pre>
<p>These two LINQ expressions are functionally equivalent. There are no important differences.</p>
<p>Just like regular LINQ expressions, the <code>IEnumerable<Task></code> is lazy-evaluated. Only, with asynchronous methods like <code>BazAsync</code>, you usually do <em>not</em> want accidental double-evaluation or anything like that. So, when you project to a sequence of tasks, it's usually a good idea to immediately reify the sequence. This calls <code>BazAsync</code> for all the elements in the source sequence, starting all the tasks going:</p>
<pre><code>Task[] tasks = bars.Select(bar => BazAsync(bar)).ToArray();
</code></pre>
<p>Of course, all we've done with <code>Select</code> is <em>start</em> an asynchronous operation for each element. If you want to wait for them all to complete, then use <code>Task.WhenAll</code>:</p>
<pre><code>await Task.WhenAll(tasks);
</code></pre>
<p>Most other LINQ operators do not work as cleanly with asynchronous delegates. <code>Select</code> is pretty straightforward: you're just starting an asynchronous operation for each element.</p> |
23,342,558 | Why can't I delete a mongoose model's object properties? | <p>When a user registers with my API they are returned a user object. Before returning the object I remove the hashed password and salt properties. I have to use</p>
<pre><code>user.salt = undefined;
user.pass = undefined;
</code></pre>
<p>Because when I try</p>
<pre><code>delete user.salt;
delete user.pass;
</code></pre>
<p>the object properties still exist and are returned.</p>
<p>Why is that?</p> | 23,372,028 | 7 | 0 | null | 2014-04-28 13:33:32.913 UTC | 6 | 2022-04-27 21:12:22.597 UTC | null | null | null | null | 1,370,927 | null | 1 | 37 | javascript|node.js|mongoose | 11,950 | <p>To use <code>delete</code> you would need to convert the model document into a plain JavaScript object by calling <a href="http://mongoosejs.com/docs/api.html#document_Document-toObject"><code>toObject</code></a> so that you can freely manipulate it:</p>
<pre><code>user = user.toObject();
delete user.salt;
delete user.pass;
</code></pre> |
19,826,832 | Why reshape2's Melt cannot capture rownames in the transformation? | <p>I have the following data:</p>
<pre><code>Cubn 3.71455160837536 0.237454645363458
Gm9779 2.56051657980096 0.20850752817264
Apod 3.51796703048962 0.195999214485821
</code></pre>
<p>What I want to do is to create the 'melted' data such that it gives this</p>
<pre><code> var1 var2 value
1 FOO Cubn 3.7145516
2 FOO Gm9779 2.5605166
3 FOO Apod 3.5179670
4 BAR Cubn 0.2374546
5 BAR Gm9779 0.2085075
6 BAR Apod 0.1959992
</code></pre>
<p>But why this failed?</p>
<pre><code> library("reshape2");
dat <-read.table("http://dpaste.com/1446132/plain/",header=FALSE)
rownames(dat) <- dat[,1]
dat[,1] <- NULL
colnames(dat) <- c("FOO","BAR");
head(dat)
longData <- melt(dat);
head(longData)
</code></pre> | 19,826,856 | 1 | 0 | null | 2013-11-07 02:22:43.543 UTC | 9 | 2013-11-07 02:25:54.47 UTC | null | null | null | null | 67,405 | null | 1 | 34 | r|reshape|reshape2 | 19,110 | <p>I don't know the <em>why</em> part, but I do know that you can get the row names by <code>melt</code>ing a <code>matrix</code> instead of a <code>data.frame</code>:</p>
<pre><code>melt(as.matrix(dat))
# Var1 Var2 value
# 1 Cubn FOO 3.7145516
# 2 Gm9779 FOO 2.5605166
# 3 Apod FOO 3.5179670
# 4 Cubn BAR 0.2374546
# 5 Gm9779 BAR 0.2085075
# 6 Apod BAR 0.1959992
</code></pre>
<p>You'll have to look at the code to the <code>melt</code> function to know why it behaves this way. In particular, the code for <code>reshape2:::melt.matrix</code> has the following lines which will create the first two columns in the example above:</p>
<pre><code>labels <- expand.grid(lapply(dn, var.convert), KEEP.OUT.ATTRS = FALSE,
stringsAsFactors = FALSE)
</code></pre> |
47,441,036 | Switch themes in angular material 5 | <p>I been reading a few articles on this but they seem to be conflicting in several different ways. I am hoping to re-create the same theme switching as the <a href="https://material.angular.io/guide/theming" rel="noreferrer">angular material documentation site</a> for the latest version of angular material [5.0.0-rc0]</p>
<p>I have two custom themes, this is custom-theme.scss and there is light-custom-theme.scss which is nearly identical, sans the mat-dark-theme</p>
<pre><code>@import '~@angular/material/theming';
$custom-theme-primary: mat-palette($mat-blue);
$custom-theme-accent: mat-palette($mat-orange, A200, A100, A400);
$custom-theme-warn: mat-palette($mat-red);
$custom-theme: mat-dark-theme($custom-theme-primary, $custom-theme-accent, $custom-theme-warn);
@include angular-material-theme($custom-theme);
</code></pre>
<p>My styles.scss looks like so</p>
<pre><code>@import '~@angular/material/theming';
@include mat-core();
@import 'custom-theme.scss';
@import 'light-custom-theme.scss';
.custom-theme {
@include angular-material-theme($custom-theme);
}
.light-custom-theme {
@include angular-material-theme($light-custom-theme);
}
</code></pre>
<p>And then it's called in the index.html <code><body class="mat-app-background"></code></p>
<p>Everything works fine when I do one theme. But I am trying to switch between the two. Adding both themes into angular-cli.json, the light-custom-theme takes over</p>
<pre><code>"styles": [
"styles.scss",
"custom-theme.scss",
"light-custom-theme.scss"
],
</code></pre>
<p>I have the following code in place in one of my components to handle toggling themes</p>
<pre><code>toggleTheme(): void {
if (this.overlay.classList.contains("custom-theme")) {
this.overlay.classList.remove("custom-theme");
this.overlay.classList.add("light-custom-theme");
} else if (this.overlay.classList.contains("light-custom-theme")) {
this.overlay.classList.remove("light-custom-theme");
this.overlay.classList.add("custom-theme");
} else {
this.overlay.classList.add("light-custom-theme");
}
}
</code></pre>
<p>But whenever it runs the theme remains the same. For what it is worth, there is already a "cdk-overlay-container" object at position 0 in overlay.classList</p>
<pre><code>0:"cdk-overlay-container"
1:"custom-theme"
length:2
value:"cdk-overlay-container custom-theme"
</code></pre>
<p>I am unsure how to debug this as the angular material documentation doesn't give me too much to work with, any help would be appreciative!</p>
<p>Thanks!</p> | 47,759,439 | 4 | 0 | null | 2017-11-22 17:50:53.003 UTC | 10 | 2019-04-08 14:17:26.213 UTC | 2018-08-16 13:21:42.723 UTC | null | 5,364,781 | null | 5,364,781 | null | 1 | 20 | angular|sass|angular-material|angular5 | 36,829 | <p>Here's an alternative solution for Angular 5.1+/Angular Material 5.0+.</p>
<p>*Edit: As noted, this still works in Angular 7+.</p>
<p>Working editable example - <a href="https://stackblitz.com/edit/dynamic-material-theming" rel="noreferrer">https://stackblitz.com/edit/dynamic-material-theming</a></p>
<p>In theme.scss, include a default theme(notice it isn't kept under a class name - this is so Angular will use it as the default), and then a light and dark theme.</p>
<p><strong>theme.scss</strong></p>
<pre><code>@import '~@angular/material/theming';
@include mat-core();
// Typography
$custom-typography: mat-typography-config(
$font-family: Raleway,
$headline: mat-typography-level(24px, 48px, 400),
$body-1: mat-typography-level(16px, 24px, 400)
);
@include angular-material-typography($custom-typography);
// Default colors
$my-app-primary: mat-palette($mat-teal, 700, 100, 800);
$my-app-accent: mat-palette($mat-teal, 700, 100, 800);
$my-app-theme: mat-light-theme($my-app-primary, $my-app-accent);
@include angular-material-theme($my-app-theme);
// Dark theme
$dark-primary: mat-palette($mat-blue-grey);
$dark-accent: mat-palette($mat-amber, A200, A100, A400);
$dark-warn: mat-palette($mat-deep-orange);
$dark-theme: mat-dark-theme($dark-primary, $dark-accent, $dark-warn);
.dark-theme {
@include angular-material-theme($dark-theme);
}
// Light theme
$light-primary: mat-palette($mat-grey, 200, 500, 300);
$light-accent: mat-palette($mat-brown, 200);
$light-warn: mat-palette($mat-deep-orange, 200);
$light-theme: mat-light-theme($light-primary, $light-accent, $light-warn);
.light-theme {
@include angular-material-theme($light-theme)
}
</code></pre>
<p>In the app.component file, include OverlayContainer from @angular/cdk/overlay. You can find Angular's documentation for this here <a href="https://material.angular.io/guide/theming" rel="noreferrer">https://material.angular.io/guide/theming</a>; though their implementation is a little different. Please note, I also had to include OverlayModule as an import in app.module as well.</p>
<p>In my app.component file, I also declared <code>@HostBinding('class') componentCssClass;</code> as a variable, which will be used to set the theme as a class.</p>
<p><strong>app.component.ts</strong></p>
<pre><code>import {Component, HostBinding } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { OverlayContainer} from '@angular/cdk/overlay';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(public overlayContainer: OverlayContainer) {}
@HostBinding('class') componentCssClass;
onSetTheme(theme) {
this.overlayContainer.getContainerElement().classList.add(theme);
this.componentCssClass = theme;
}
}
</code></pre>
<p><strong>app.module.ts</strong></p>
<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { AppComponent } from './app.component';
import { OverlayModule} from '@angular/cdk/overlay';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
MatCardModule,
MatButtonModule,
OverlayModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
</code></pre>
<p>Finally, call the onSetTheme function from your view.</p>
<p><strong>app.component.html</strong></p>
<pre><code><button mat-raised-button color="primary" (click)="onSetTheme('default-theme')">Default</button>
<button mat-raised-button color="primary" (click)="onSetTheme('dark-theme')">Dark</button>
<button mat-raised-button color="primary" (click)="onSetTheme('light-theme')">Light</button>
</code></pre>
<p>You might consider using an observable so that the functionality would be more dynamic.</p> |
21,377,360 | Proper way to create unique_ptr that holds an allocated array | <p>What is the proper way to create an unique_ptr that holds an array that is allocated on the free store? Visual studio 2013 supports this by default, but when I use gcc version 4.8.1 on Ubuntu I get memory leaks and undefined behaviour.</p>
<p>The problem can be reproduced with this code: </p>
<pre><code>#include <memory>
#include <string.h>
using namespace std;
int main()
{
unique_ptr<unsigned char> testData(new unsigned char[16000]());
memset(testData.get(),0x12,0);
return 0;
}
</code></pre>
<p>Valgrind will give this output:</p>
<pre><code>==3894== 1 errors in context 1 of 1:
==3894== Mismatched free() / delete / delete []
==3894== at 0x4C2BADC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3894== by 0x400AEF: std::default_delete<unsigned char>::operator()(unsigned char*) const (unique_ptr.h:67)
==3894== by 0x4009D0: std::unique_ptr<unsigned char, std::default_delete<unsigned char> >::~unique_ptr() (unique_ptr.h:184)
==3894== by 0x4007A9: main (test.cpp:19)
==3894== Address 0x5a1a040 is 0 bytes inside a block of size 16,000 alloc'd
==3894== at 0x4C2AFE7: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3894== by 0x40075F: main (test.cpp:15)
</code></pre> | 21,377,382 | 6 | 1 | null | 2014-01-27 09:37:58.89 UTC | 29 | 2020-08-11 09:05:59.5 UTC | null | null | null | null | 2,849,736 | null | 1 | 97 | c++|linux|gcc|c++11|unique-ptr | 110,856 | <p>Using the <code>T[]</code> specialisation:</p>
<pre><code>std::unique_ptr<unsigned char[]> testData(new unsigned char[16000]());
</code></pre>
<p>Note that, in an ideal world, you would not have to explicitly use <code>new</code> to instantiate a <code>unique_ptr</code>, avoiding a potential exception safety pitfall. To this end, C++14 provides you with the <code>std::make_unique</code> function template. See <a href="http://herbsutter.com/gotw/_102/" rel="noreferrer">this excellent GOTW</a> for more details. The syntax is:</p>
<pre><code>auto testData = std::make_unique<unsigned char[]>(16000);
</code></pre> |
18,976,302 | Returning Rendered Html via Ajax | <p>I am trying to return html via and Ajax call and I have the following snippet of code in my view</p>
<pre><code>if request.is_ajax():
t = loader.get_template('frontend/scroll.html')
html = t.render(RequestContext({'dishes': dishes})
return HttpResponse(json.dumps({'html': html}))
</code></pre>
<p>and my Ajax</p>
<pre><code> $.ajax({
type: "POST",
url: "/filter_home",
data: {'name': 'me', 'csrfmiddlewaretoken': '{{csrf_token}}'},
success : function(data) {
$('.row.replace').html(data);
}
});
</code></pre>
<p>and it throws the following error</p>
<pre><code>Exception Value: 'dict' object has no attribute 'META'
Exception Location: /opt/bitnami/apps/django/lib/python2.7/sitepackages/django/core/context_processors.py in debug, line 39
</code></pre>
<p>what am I doing wrong?</p> | 18,976,471 | 3 | 0 | null | 2013-09-24 08:17:00.987 UTC | 13 | 2021-09-25 09:04:35.147 UTC | null | null | null | null | 2,758,219 | null | 1 | 20 | django | 25,290 | <p>There are a few issues with your code:</p>
<p>You need to use <a href="https://docs.djangoproject.com/en/3.2/topics/templates/#django.template.loader.render_to_string" rel="nofollow noreferrer"><code>render_to_string</code></a>.</p>
<p>You also don't need to convert your HTML into json because you are replacing the contents directly.</p>
<p>Putting all this together you have:</p>
<pre><code>from django.template.loader import render_to_string
from django.http import HttpResponse
if request.is_ajax():
html = render_to_string('frontend/scroll.html', {'dishes': dishes})
return HttpResponse(html)
</code></pre>
<p>In your front end, you need:</p>
<pre><code>$.ajax({
type: "POST",
url: "/filter_home",
data: {'name': 'me', 'csrfmiddlewaretoken': '{{ csrf_token }}'},
success : function(data) {
$('.row.replace').html(data);
}
});
</code></pre> |
46,943,314 | XGBoost plot_importance doesn't show feature names | <p>I'm using XGBoost with Python and have successfully trained a model using the XGBoost <code>train()</code> function called on <code>DMatrix</code> data. The matrix was created from a Pandas dataframe, which has feature names for the columns.</p>
<pre><code>Xtrain, Xval, ytrain, yval = train_test_split(df[feature_names], y, \
test_size=0.2, random_state=42)
dtrain = xgb.DMatrix(Xtrain, label=ytrain)
model = xgb.train(xgb_params, dtrain, num_boost_round=60, \
early_stopping_rounds=50, maximize=False, verbose_eval=10)
fig, ax = plt.subplots(1,1,figsize=(10,10))
xgb.plot_importance(model, max_num_features=5, ax=ax)
</code></pre>
<p>I want to now see the feature importance using the <code>xgboost.plot_importance()</code> function, but the resulting plot doesn't show the feature names. Instead, the features are listed as <code>f1</code>, <code>f2</code>, <code>f3</code>, etc. as shown below.</p>
<p><a href="https://i.stack.imgur.com/zhehV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zhehV.png" alt="enter image description here"></a></p>
<p>I think the problem is that I converted my original Pandas data frame into a DMatrix. How can I associate feature names properly so that the feature importance plot shows them?</p> | 46,943,417 | 8 | 0 | null | 2017-10-25 23:01:14.973 UTC | 10 | 2021-12-28 10:41:02.483 UTC | null | null | null | null | 4,561,314 | null | 1 | 32 | python|pandas|machine-learning|xgboost | 37,629 | <p>You want to use the <code>feature_names</code> parameter when creating your <code>xgb.DMatrix</code></p>
<pre><code>dtrain = xgb.DMatrix(Xtrain, label=ytrain, feature_names=feature_names)
</code></pre> |
43,383,835 | Remove the first six characters from a String (Swift) | <p>What's the best way to go about removing the first six characters of a string? Through Stack Overflow, I've found a couple of ways that were supposed to be solutions but I noticed an error with them. For instance,</p>
<pre><code>extension String {
func removing(charactersOf string: String) -> String {
let characterSet = CharacterSet(charactersIn: string)
let components = self.components(separatedBy: characterSet)
return components.joined(separator: "")
}
</code></pre>
<p>If I type in a website like <code>https://www.example.com</code>, and store it as a variable named website, then type in the following</p>
<pre><code>website.removing(charactersOf: "https://")
</code></pre>
<p>it removes the <code>https://</code> portion but it also removes all h's, all t's, :'s, etc. from the text.</p>
<p>How can I just delete the first characters?</p> | 43,383,945 | 4 | 1 | null | 2017-04-13 04:59:36.107 UTC | 6 | 2020-11-08 08:48:46.983 UTC | 2020-11-08 08:48:46.983 UTC | null | 12,984,567 | null | 6,494,850 | null | 1 | 34 | swift|string|character | 32,062 | <p><code>length</code> is the number of characters you want to remove (6 in your case)</p>
<pre><code>extension String {
func toLengthOf(length:Int) -> String {
if length <= 0 {
return self
} else if let to = self.index(self.startIndex, offsetBy: length, limitedBy: self.endIndex) {
return self.substring(from: to)
} else {
return ""
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/LzQUH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LzQUH.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/dS35w.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dS35w.png" alt="enter image description here"></a></p> |
8,426,242 | How to create new fields for customer | <p>I am developing a website with magento ver-1.6. I am try to create new fields for customer registration, but it not created. I followed the same way what we followed in ver-1.5.</p>
<p>Any variation in create customer fields in 1.6?</p> | 8,426,639 | 2 | 0 | null | 2011-12-08 04:40:04.017 UTC | 11 | 2014-11-05 16:30:43.72 UTC | null | null | null | null | 799,258 | null | 1 | 7 | magento|magento-1.5 | 18,016 | <p>I don't know what you tried so I'm just going to list all the steps needed to add a new schooL customer attribute to the Magento 1.6.1 registration form.</p>
<ol>
<li><p>Create a module preferably, or place similiar code to this in some .phtml file and run it once. If you're doing this proper and creating a module, put code like this into the mysql_install file:</p>
<pre><code><?php
$installer = $this;
$installer->startSetup();
$setup = Mage::getModel('customer/entity_setup', 'core_setup');
$setup->addAttribute('customer', 'school', array(
'type' => 'int',
'input' => 'select',
'label' => 'School',
'global' => 1,
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'default' => '0',
'visible_on_front' => 1,
'source'=> 'profile/entity_school',
));
if (version_compare(Mage::getVersion(), '1.6.0', '<='))
{
$customer = Mage::getModel('customer/customer');
$attrSetId = $customer->getResource()->getEntityType()->getDefaultAttributeSetId();
$setup->addAttributeToSet('customer', $attrSetId, 'General', 'school');
}
if (version_compare(Mage::getVersion(), '1.4.2', '>='))
{
Mage::getSingleton('eav/config')
->getAttribute('customer', 'school')
->setData('used_in_forms', array('adminhtml_customer','customer_account_create','customer_account_edit','checkout_register'))
->save();
}
$installer->endSetup();
?>
</code></pre></li>
<li><p>In your module config.xml file. Note that the name of my module is Excellence_Profile.</p>
<pre><code><profile_setup> <!-- Replace with your module name -->
<setup>
<module>Excellence_Profile</module> <!-- Replace with your module name -->
<class>Mage_Customer_Model_Entity_Setup</class>
</setup>
</profile_setup>
</code></pre></li>
<li><p>Here we will add our attribute, to the customer registration form. In version 1.6.0(+) the phtml file used is <code>persistance/customer/register.phtml</code> and in version 1.6.0(-) the phtml file used is <code>customer/form/register.phtml</code>
So we need to open the phtml file, based on magento version and add this code in the tag.</p>
<pre><code><li>
<?php
$attribute = Mage::getModel('eav/config')->getAttribute('customer','school');
?>
<label for="school" class="<?php if($attribute->getIsRequired() == true){?>required<?php } ?>"><?php if($attribute->getIsRequired() == true){?><em>*</em><?php } ?><?php echo $this->__('School') ?></label>
<div class="input-box">
<select name="school" id="school" class="<?php if($attribute->getIsRequired() == true){?>required-entry<?php } ?>">
<?php
$options = $attribute->getSource()->getAllOptions();
foreach($options as $option){
?>
<option value='<?php echo $option['value']?>' <?php if($this->getFormData()->getSchool() == $option['value']){ echo 'selected="selected"';}?>><?php echo $this->__($option['label'])?></option>
<?php } ?>
</select>
</div>
</li>
</code></pre></li>
<li><p>For magento 1.4.2(+) that is all that is required for the registration step. If you create a user from here, you should see the school text field in admin.
For magento 1.4.1(-), we need to do another thing open the your modules config.xml file and add:</p>
<pre><code><global>
<fieldsets>
<customer_account>
<school><create>1</create><update>1</update><name>1</name></school>
</customer_account>
</fieldsets>
</global>
</code></pre></li>
<li><p>Once, user has created his account in the MyAccount->Account Information section he should be able to edit the school field as well. For this open the phtml file <code>customer/form/edit.phtml</code> and put in the code in the :</p>
<pre><code><?php
<li>
<?php
$attribute = Mage::getModel('eav/config')->getAttribute('customer','school');
?>
<label for="is_active" class="<?php if($attribute->getIsRequired() == true){?>required<?php } ?>"><?php if($attribute->getIsRequired() == true){?><em>*</em><?php } ?><?php echo $this->__('School') ?></label>
<div class="input-box">
<select name="school" id="school" class="<?php if($attribute->getIsRequired() == true){?>required-entry<?php } ?>">
<?php
$options = $attribute->getSource()->getAllOptions();
foreach($options as $option){
?>
<option value='<?php echo $option['value']?>' <?php if($this->getCustomer()->getSchool() == $option['value']){ echo 'selected="selected"';}?>><?php echo $this->__($option['label'])?></option>
<?php } ?>
</select>
</div>
</li>
</code></pre></li>
<li><p>A registration form also shows up at the checkout page in magento. To add you field here, you need to edit <code>checkout/onepage/billing.phtml</code> for magento version 1.6(-) and <code>persistant/checkout/onepage/billing.phtml</code> for magento version 1.6(+) file and then find the code:</p>
<pre><code><?php if(!$this->isCustomerLoggedIn()): ?>
</code></pre>
<p>inside this if condition add your field</p>
<pre><code><li>
<li>
<?php
$attribute = Mage::getModel('eav/config')->getAttribute('customer','school');
?>
<label for="school" class="<?php if($attribute->getIsRequired() == true){?>required<?php } ?>"><?php if($attribute->getIsRequired() == true){?><em>*</em><?php } ?><?php echo $this->__('School') ?></label>
<div class="input-box">
<select name="billing[school]" id="school" class="<?php if($attribute->getIsRequired() == true){?>required-entry<?php } ?>">
<?php
$options = $attribute->getSource()->getAllOptions();
foreach($options as $option){
?>
<option value='<?php echo $option['value']?>'><?php echo $this->__($option['label'])?></option>
<?php } ?>
</select>
</div>
</li>
</code></pre>
<p>Next open your module config.xml or any other config.xml file, add the following lines:</p>
<pre><code> <global>
<fieldsets>
<checkout_onepage_quote>
<customer_school>
<to_customer>school</to_customer>
</customer_school>
</checkout_onepage_quote>
<customer_account>
<school>
<to_quote>customer_school</to_quote>
</school>
</customer_account>
</fieldsets>
</global>
</code></pre></li>
<li><p>Next we need to make some changes in the quote table i.e sales_flat_quote table in magento. If you have a module then create an upgrade version of your sql file and put in this code:</p>
<pre><code>$tablequote = $this->getTable('sales/quote');
$installer->run("
ALTER TABLE $tablequote ADD `customer_school` INT NOT NULL
");
</code></pre></li>
</ol>
<p>After doing this make sure to clear you magento cache, specifically “Flush Magento Cache” and “Flush Cache Storage”.
Now when you place order, the customer is created with the correct school attribute.</p> |
48,149,323 | What does the gcc warning "project parameter passing for X changed in GCC 7.1" mean? | <p>I have a C++ project that builds fine and without warnings with gcc 7.2 on x86 Linux and Windows, I needed to port it to an ARM device so I tried to crosscompile it with an "arm-linux-gnueabihf" gcc 7.2 that runs on my x86 machine, it builds but I get a lot of warnings of this kind</p>
<pre><code>note: parameter passing for argument of type '__gnu_cxx::__normal_iterator<P2d*, std::vector<P2d> >' changed in GCC 7.1
_M_realloc_insert(end(), __x);
</code></pre>
<p>and</p>
<pre><code>/opt/armv7-gcc-2017/arm-linux-gnueabihf/include/c++/7.2.0/bits/vector.tcc:105:21: note: parameter passing for argument of type '__gnu_cxx::__normal_iterator<cpzparser::Anchor*, std::vector<cpzparser::Anchor> >' changed in GCC 7.1
_M_realloc_insert(end(), std::forward<_Args>(__args)...);
</code></pre>
<p>or</p>
<pre><code>/opt/armv7-gcc-2017/arm-linux-gnueabihf/include/c++/7.2.0/bits/vector.tcc:394:7: note: parameter passing for argument of type 'std::vector<cpzparser::PointEntity>::iterator {aka __gnu_cxx::__normal_iterator<cpzparser::PointEntity*, std::vector<cpzparser::PointEntity> >}' changed in GCC 7.1
vector<_Tp, _Alloc>::
</code></pre>
<p>the generated executable seems to work fine but I am worried by the presence of all those warnings since I have no idea of what they mean.. any clue?</p> | 48,149,400 | 1 | 0 | null | 2018-01-08 11:24:37.503 UTC | 4 | 2020-02-23 09:46:28.303 UTC | 2020-02-23 09:46:28.303 UTC | null | 1,033,581 | null | 2,318,607 | null | 1 | 65 | c++|gcc | 27,359 | <p>That warning is telling you that there was a subtle ABI change (actually a conformance fix) between 6 and 7.1, such that libraries built with 6.x or earlier may not work properly when called from code built with 7.x (and vice-versa). As long as all your C++ code is built with GCC 7.1 or later, you can safely ignore this warning. To disable it, pass <code>-Wno-psabi</code> to the compiler.</p>
<p>For more details on the context of the change, see <a href="https://gcc.gnu.org/gcc-7/changes.html" rel="noreferrer">the GCC 7 changelog</a>, and <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77728" rel="noreferrer">the associated bug</a>.</p> |
59,956,670 | Parsing city of origin / destination city from a string | <p>I have a pandas dataframe where one column is a bunch of strings with certain travel details. My goal is to parse each string to extract the city of origin and destination city (I would like to ultimately have two new columns titled 'origin' and 'destination').</p>
<p>The data:</p>
<pre><code>df_col = [
'new york to venice, italy for usd271',
'return flights from brussels to bangkok with etihad from €407',
'from los angeles to guadalajara, mexico for usd191',
'fly to australia new zealand from paris from €422 return including 2 checked bags'
]
</code></pre>
<p>This should result in:</p>
<pre><code>Origin: New York, USA; Destination: Venice, Italy
Origin: Brussels, BEL; Destination: Bangkok, Thailand
Origin: Los Angeles, USA; Destination: Guadalajara, Mexico
Origin: Paris, France; Destination: Australia / New Zealand (this is a complicated case given two countries)
</code></pre>
<p>Thus far I have tried:
A variety of NLTK methods, but what has gotten me closest is using the <code>nltk.pos_tag</code> method to tag each word in the string. The result is a list of tuples with each word and associated tag. Here's an example...</p>
<pre><code>[('Fly', 'NNP'), ('to', 'TO'), ('Australia', 'NNP'), ('&', 'CC'), ('New', 'NNP'), ('Zealand', 'NNP'), ('from', 'IN'), ('Paris', 'NNP'), ('from', 'IN'), ('€422', 'NNP'), ('return', 'NN'), ('including', 'VBG'), ('2', 'CD'), ('checked', 'VBD'), ('bags', 'NNS'), ('!', '.')]
</code></pre>
<p>I am stuck at this stage and am unsure how to best implement this. Can anyone point me in the right direction, please? Thanks.</p> | 59,959,188 | 1 | 1 | null | 2020-01-28 20:39:24.623 UTC | 20 | 2020-03-02 21:48:24.877 UTC | 2020-01-28 20:46:16.323 UTC | null | 2,179,795 | null | 2,179,795 | null | 1 | 26 | python|regex|pandas|nlp|nltk | 8,453 | <h1>TL;DR</h1>
<p>Pretty much impossible at first glance, unless you have access to some API that contains pretty sophisticated components. </p>
<h1>In Long</h1>
<p>From first look, it seems like you're asking to solve a natural language problem magically. But lets break it down and scope it to a point where something is buildable. </p>
<p>First, to identify countries and cities, you need data that enumerates them, so lets try: <a href="https://www.google.com/search?q=list+of+countries+and+cities+in+the+world+json" rel="noreferrer">https://www.google.com/search?q=list+of+countries+and+cities+in+the+world+json</a> </p>
<p>And top of the search results, we find <a href="https://datahub.io/core/world-cities" rel="noreferrer">https://datahub.io/core/world-cities</a> that leads to the world-cities.json file. Now we load them into sets of countries and cities. </p>
<pre><code>import requests
import json
cities_url = "https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json"
cities_json = json.loads(requests.get(cities_url).content.decode('utf8'))
countries = set([city['country'] for city in cities_json])
cities = set([city['name'] for city in cities_json])
</code></pre>
<h2>Now given data, lets try to build <strong>component ONE</strong>:</h2>
<ul>
<li><strong>Task:</strong> Detect if any substring in the texts matches a city/country.</li>
<li><strong>Tool:</strong> <a href="https://github.com/vi3k6i5/flashtext" rel="noreferrer">https://github.com/vi3k6i5/flashtext</a> (a fast string search/match)</li>
<li><strong>Metric:</strong> No. of correctly identified cities/countries in string</li>
</ul>
<p>Lets put them together.</p>
<pre><code>import requests
import json
from flashtext import KeywordProcessor
cities_url = "https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json"
cities_json = json.loads(requests.get(cities_url).content.decode('utf8'))
countries = set([city['country'] for city in cities_json])
cities = set([city['name'] for city in cities_json])
keyword_processor = KeywordProcessor(case_sensitive=False)
keyword_processor.add_keywords_from_list(sorted(countries))
keyword_processor.add_keywords_from_list(sorted(cities))
texts = ['new york to venice, italy for usd271',
'return flights from brussels to bangkok with etihad from €407',
'from los angeles to guadalajara, mexico for usd191',
'fly to australia new zealand from paris from €422 return including 2 checked bags']
keyword_processor.extract_keywords(texts[0])
</code></pre>
<p>[out]:</p>
<pre><code>['York', 'Venice', 'Italy']
</code></pre>
<h2>Hey, what went wrong?!</h2>
<p>Doing due diligence, first hunch is that "new york" is not in the data, </p>
<pre><code>>>> "New York" in cities
False
</code></pre>
<p>What the?! #$%^&* For sanity sake, we check these:</p>
<pre><code>>>> len(countries)
244
>>> len(cities)
21940
</code></pre>
<p>Yes, you cannot just trust a single data source, so lets try to fetch all data sources.</p>
<p>From <a href="https://www.google.com/search?q=list+of+countries+and+cities+in+the+world+json" rel="noreferrer">https://www.google.com/search?q=list+of+countries+and+cities+in+the+world+json</a>, you find another link <a href="https://github.com/dr5hn/countries-states-cities-database" rel="noreferrer">https://github.com/dr5hn/countries-states-cities-database</a> Lets munge this...</p>
<pre><code>import requests
import json
cities_url = "https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json"
cities1_json = json.loads(requests.get(cities_url).content.decode('utf8'))
countries1 = set([city['country'] for city in cities1_json])
cities1 = set([city['name'] for city in cities1_json])
dr5hn_cities_url = "https://raw.githubusercontent.com/dr5hn/countries-states-cities-database/master/cities.json"
dr5hn_countries_url = "https://raw.githubusercontent.com/dr5hn/countries-states-cities-database/master/countries.json"
cities2_json = json.loads(requests.get(dr5hn_cities_url).content.decode('utf8'))
countries2_json = json.loads(requests.get(dr5hn_countries_url).content.decode('utf8'))
countries2 = set([c['name'] for c in countries2_json])
cities2 = set([c['name'] for c in cities2_json])
countries = countries2.union(countries1)
cities = cities2.union(cities1)
</code></pre>
<h2>And now that we are neurotic, we do sanity checks.</h2>
<pre><code>>>> len(countries)
282
>>> len(cities)
127793
</code></pre>
<p>Wow, that's a lot more cities than previously. </p>
<p>Lets try the <code>flashtext</code> code again.</p>
<pre><code>from flashtext import KeywordProcessor
keyword_processor = KeywordProcessor(case_sensitive=False)
keyword_processor.add_keywords_from_list(sorted(countries))
keyword_processor.add_keywords_from_list(sorted(cities))
texts = ['new york to venice, italy for usd271',
'return flights from brussels to bangkok with etihad from €407',
'from los angeles to guadalajara, mexico for usd191',
'fly to australia new zealand from paris from €422 return including 2 checked bags']
keyword_processor.extract_keywords(texts[0])
</code></pre>
<p>[out]:</p>
<pre><code>['York', 'Venice', 'Italy']
</code></pre>
<h2>Seriously?! There is no New York?! $%^&*</h2>
<p>Okay, for more sanity checks, lets just look for "york" in the list of cities.</p>
<pre><code>>>> [c for c in cities if 'york' in c.lower()]
['Yorklyn',
'West York',
'West New York',
'Yorktown Heights',
'East Riding of Yorkshire',
'Yorke Peninsula',
'Yorke Hill',
'Yorktown',
'Jefferson Valley-Yorktown',
'New York Mills',
'City of York',
'Yorkville',
'Yorkton',
'New York County',
'East York',
'East New York',
'York Castle',
'York County',
'Yorketown',
'New York City',
'York Beach',
'Yorkshire',
'North Yorkshire',
'Yorkeys Knob',
'York',
'York Town',
'York Harbor',
'North York']
</code></pre>
<h2>Eureka! It's because it's call "New York City" and not "New York"!</h2>
<p><strong>You:</strong> What kind of prank is this?! </p>
<p><strong>Linguist:</strong> Welcome to the world of <strong>natural language</strong> processing, where natural language is a social construct subjective to communal and idiolectal variant. </p>
<p><strong>You</strong>: Cut the crap, tell me how to solve this. </p>
<p><strong>NLP Practitioner</strong> (A real one that works on noisy user-generate texts): You just have to add to the list. But before that, check your <em>metric</em> given the list you already have.</p>
<h3>For every texts in your sample "test set", you should provide some truth labels to make sure you can "measure your metric".</h3>
<pre><code>from itertools import zip_longest
from flashtext import KeywordProcessor
keyword_processor = KeywordProcessor(case_sensitive=False)
keyword_processor.add_keywords_from_list(sorted(countries))
keyword_processor.add_keywords_from_list(sorted(cities))
texts_labels = [('new york to venice, italy for usd271', ('New York', 'Venice', 'Italy')),
('return flights from brussels to bangkok with etihad from €407', ('Brussels', 'Bangkok')),
('from los angeles to guadalajara, mexico for usd191', ('Los Angeles', 'Guadalajara')),
('fly to australia new zealand from paris from €422 return including 2 checked bags', ('Australia', 'New Zealand', 'Paris'))]
# No. of correctly extracted terms.
true_positives = 0
false_positives = 0
total_truth = 0
for text, label in texts_labels:
extracted = keyword_processor.extract_keywords(text)
# We're making some assumptions here that the order of
# extracted and the truth must be the same.
true_positives += sum(1 for e, l in zip_longest(extracted, label) if e == l)
false_positives += sum(1 for e, l in zip_longest(extracted, label) if e != l)
total_truth += len(label)
# Just visualization candies.
print(text)
print(extracted)
print(label)
print()
</code></pre>
<p>Actually, it doesn't look that bad. We get an accuracy of 90%:</p>
<pre><code>>>> true_positives / total_truth
0.9
</code></pre>
<h3>But I %^&*(-ing want 100% extraction!!</h3>
<p>Alright, alright, so look at the "only" error that the above approach is making, it's simply that "New York" isn't in the list of cities. </p>
<p><strong>You</strong>: Why don't we just add "New York" to the list of cities, i.e. </p>
<pre><code>keyword_processor.add_keyword('New York')
print(texts[0])
print(keyword_processor.extract_keywords(texts[0]))
</code></pre>
<p>[out]:</p>
<pre><code>['New York', 'Venice', 'Italy']
</code></pre>
<p><strong>You</strong>: See, I did it!!! Now I deserve a beer.
<strong>Linguist</strong>: How about <code>'I live in Marawi'</code>?</p>
<pre><code>>>> keyword_processor.extract_keywords('I live in Marawi')
[]
</code></pre>
<p><strong>NLP Practitioner</strong> (chiming in): How about <code>'I live in Jeju'</code>? </p>
<pre><code>>>> keyword_processor.extract_keywords('I live in Jeju')
[]
</code></pre>
<p><strong>A Raymond Hettinger fan</strong> (from farway): "There must be a better way!"</p>
<p>Yes, there is what if we just try something silly like adding keywords of cities that ends with "City" into our <code>keyword_processor</code>?</p>
<pre><code>for c in cities:
if 'city' in c.lower() and c.endswith('City') and c[:-5] not in cities:
if c[:-5].strip():
keyword_processor.add_keyword(c[:-5])
print(c[:-5])
</code></pre>
<h1>It works!</h1>
<p>Now lets retry our regression test examples:</p>
<pre><code>from itertools import zip_longest
from flashtext import KeywordProcessor
keyword_processor = KeywordProcessor(case_sensitive=False)
keyword_processor.add_keywords_from_list(sorted(countries))
keyword_processor.add_keywords_from_list(sorted(cities))
for c in cities:
if 'city' in c.lower() and c.endswith('City') and c[:-5] not in cities:
if c[:-5].strip():
keyword_processor.add_keyword(c[:-5])
texts_labels = [('new york to venice, italy for usd271', ('New York', 'Venice', 'Italy')),
('return flights from brussels to bangkok with etihad from €407', ('Brussels', 'Bangkok')),
('from los angeles to guadalajara, mexico for usd191', ('Los Angeles', 'Guadalajara')),
('fly to australia new zealand from paris from €422 return including 2 checked bags', ('Australia', 'New Zealand', 'Paris')),
('I live in Florida', ('Florida')),
('I live in Marawi', ('Marawi')),
('I live in jeju', ('Jeju'))]
# No. of correctly extracted terms.
true_positives = 0
false_positives = 0
total_truth = 0
for text, label in texts_labels:
extracted = keyword_processor.extract_keywords(text)
# We're making some assumptions here that the order of
# extracted and the truth must be the same.
true_positives += sum(1 for e, l in zip_longest(extracted, label) if e == l)
false_positives += sum(1 for e, l in zip_longest(extracted, label) if e != l)
total_truth += len(label)
# Just visualization candies.
print(text)
print(extracted)
print(label)
print()
</code></pre>
<p>[out]:</p>
<pre><code>new york to venice, italy for usd271
['New York', 'Venice', 'Italy']
('New York', 'Venice', 'Italy')
return flights from brussels to bangkok with etihad from €407
['Brussels', 'Bangkok']
('Brussels', 'Bangkok')
from los angeles to guadalajara, mexico for usd191
['Los Angeles', 'Guadalajara', 'Mexico']
('Los Angeles', 'Guadalajara')
fly to australia new zealand from paris from €422 return including 2 checked bags
['Australia', 'New Zealand', 'Paris']
('Australia', 'New Zealand', 'Paris')
I live in Florida
['Florida']
Florida
I live in Marawi
['Marawi']
Marawi
I live in jeju
['Jeju']
Jeju
</code></pre>
<h3>100% Yeah, NLP-bunga !!!</h3>
<p>But seriously, this is only the tip of the problem. What happens if you have a sentence like this:</p>
<pre><code>>>> keyword_processor.extract_keywords('Adam flew to Bangkok from Singapore and then to China')
['Adam', 'Bangkok', 'Singapore', 'China']
</code></pre>
<p><strong>WHY is <code>Adam</code> extracted as a city?!</strong></p>
<p>Then you do some more neurotic checks:</p>
<pre><code>>>> 'Adam' in cities
Adam
</code></pre>
<p>Congratulations, you've jumped into another NLP rabbit hole of polysemy where the same word has different meaning, in this case, <code>Adam</code> most probably refer to a person in the sentence but it is also coincidentally the name of a city (according to the data you've pulled from).</p>
<h3>I see what you did there... Even if we ignore this polysemy nonsense, you are still not giving me the desired output:</h3>
<p>[in]:</p>
<pre><code>['new york to venice, italy for usd271',
'return flights from brussels to bangkok with etihad from €407',
'from los angeles to guadalajara, mexico for usd191',
'fly to australia new zealand from paris from €422 return including 2 checked bags'
]
</code></pre>
<p>[out]:</p>
<pre><code>Origin: New York, USA; Destination: Venice, Italy
Origin: Brussels, BEL; Destination: Bangkok, Thailand
Origin: Los Angeles, USA; Destination: Guadalajara, Mexico
Origin: Paris, France; Destination: Australia / New Zealand (this is a complicated case given two countries)
</code></pre>
<p><strong>Linguist</strong>: Even with the assumption that the preposition (e.g. <code>from</code>, <code>to</code>) preceding the city gives you the "origin" / "destination" tag, how are you going to handle the case of "multi-leg" flights, e.g. </p>
<pre><code>>>> keyword_processor.extract_keywords('Adam flew to Bangkok from Singapore and then to China')
</code></pre>
<p>What's the desired output of this sentence:</p>
<pre><code>> Adam flew to Bangkok from Singapore and then to China
</code></pre>
<p>Perhaps like this? What is the specification? How (un-)structured is your input text?</p>
<pre><code>> Origin: Singapore
> Departure: Bangkok
> Departure: China
</code></pre>
<h2>Lets try to build component TWO to detect prepositions.</h2>
<p>Lets take that assumption you have and try some hacks to the same <code>flashtext</code> methods. </p>
<p><strong>What if we add <code>to</code> and <code>from</code> to the list?</strong></p>
<pre><code>from itertools import zip_longest
from flashtext import KeywordProcessor
keyword_processor = KeywordProcessor(case_sensitive=False)
keyword_processor.add_keywords_from_list(sorted(countries))
keyword_processor.add_keywords_from_list(sorted(cities))
for c in cities:
if 'city' in c.lower() and c.endswith('City') and c[:-5] not in cities:
if c[:-5].strip():
keyword_processor.add_keyword(c[:-5])
keyword_processor.add_keyword('to')
keyword_processor.add_keyword('from')
texts = ['new york to venice, italy for usd271',
'return flights from brussels to bangkok with etihad from €407',
'from los angeles to guadalajara, mexico for usd191',
'fly to australia new zealand from paris from €422 return including 2 checked bags']
for text in texts:
extracted = keyword_processor.extract_keywords(text)
print(text)
print(extracted)
print()
</code></pre>
<p>[out]:</p>
<pre><code>new york to venice, italy for usd271
['New York', 'to', 'Venice', 'Italy']
return flights from brussels to bangkok with etihad from €407
['from', 'Brussels', 'to', 'Bangkok', 'from']
from los angeles to guadalajara, mexico for usd191
['from', 'Los Angeles', 'to', 'Guadalajara', 'Mexico']
fly to australia new zealand from paris from €422 return including 2 checked bags
['to', 'Australia', 'New Zealand', 'from', 'Paris', 'from']
</code></pre>
<h3>Heh, that's pretty crappy rule to use to/from,</h3>
<ol>
<li>What if the "from" is referring the price of the ticket?</li>
<li>What if there's no "to/from" preceding the country/city? </li>
</ol>
<p>Okay, lets work with the above output and see what we do about the problem 1. <strong>Maybe check if the term after the from is city, if not, remove the to/from?</strong></p>
<pre><code>from itertools import zip_longest
from flashtext import KeywordProcessor
keyword_processor = KeywordProcessor(case_sensitive=False)
keyword_processor.add_keywords_from_list(sorted(countries))
keyword_processor.add_keywords_from_list(sorted(cities))
for c in cities:
if 'city' in c.lower() and c.endswith('City') and c[:-5] not in cities:
if c[:-5].strip():
keyword_processor.add_keyword(c[:-5])
keyword_processor.add_keyword('to')
keyword_processor.add_keyword('from')
texts = ['new york to venice, italy for usd271',
'return flights from brussels to bangkok with etihad from €407',
'from los angeles to guadalajara, mexico for usd191',
'fly to australia new zealand from paris from €422 return including 2 checked bags']
for text in texts:
extracted = keyword_processor.extract_keywords(text)
print(text)
new_extracted = []
extracted_next = extracted[1:]
for e_i, e_iplus1 in zip_longest(extracted, extracted_next):
if e_i == 'from' and e_iplus1 not in cities and e_iplus1 not in countries:
print(e_i, e_iplus1)
continue
elif e_i == 'from' and e_iplus1 == None: # last word in the list.
continue
else:
new_extracted.append(e_i)
print(new_extracted)
print()
</code></pre>
<p>That seems to do the trick and remove the <code>from</code> that doesn't precede a city/country. </p>
<p>[out]:</p>
<pre><code>new york to venice, italy for usd271
['New York', 'to', 'Venice', 'Italy']
return flights from brussels to bangkok with etihad from €407
from None
['from', 'Brussels', 'to', 'Bangkok']
from los angeles to guadalajara, mexico for usd191
['from', 'Los Angeles', 'to', 'Guadalajara', 'Mexico']
fly to australia new zealand from paris from €422 return including 2 checked bags
from None
['to', 'Australia', 'New Zealand', 'from', 'Paris']
</code></pre>
<h3>But the "from New York" still isn't solve!!</h3>
<p><strong>Linguist</strong>: Think carefully, should ambiguity be resolved by making an informed decision to make ambiguous phrase obvious? If so, what is the "information" in the informed decision? Should it follow a certain template first to detect the information before filling in the ambiguity?</p>
<p><strong>You</strong>: I'm losing my patience with you... You're bringing me in circles and circles, where's that AI that can understand human language that I keep hearing from the news and Google and Facebook and all?!</p>
<p><strong>You</strong>: What you gave me are rule based and where's the AI in all these?</p>
<p><strong>NLP Practitioner</strong>: Didn't you wanted 100%? Writing "business logics" or rule-based systems would be the only way to really achieve that "100%" given a specific data set without any preset data set that one can use for "training an AI".</p>
<p><strong>You</strong>: What do you mean by training an AI? Why can't I just use Google or Facebook or Amazon or Microsoft or even IBM's AI? </p>
<p><strong>NLP Practitioner</strong>: Let me introduce you to </p>
<ul>
<li><a href="https://learning.oreilly.com/library/view/data-science-from/9781492041122/" rel="noreferrer">https://learning.oreilly.com/library/view/data-science-from/9781492041122/</a></li>
<li><a href="https://allennlp.org/tutorials" rel="noreferrer">https://allennlp.org/tutorials</a></li>
<li><a href="https://www.aclweb.org/anthology/" rel="noreferrer">https://www.aclweb.org/anthology/</a></li>
</ul>
<p>Welcome to the world of Computational Linguistics and NLP!</p>
<h1>In Short</h1>
<p>Yes, there's no real ready-made magical solution and if you want to use an "AI" or machine learning algorithm, most probably you would need a lot more training data like the <code>texts_labels</code> pairs shown in the above example.</p> |
26,542,936 | 504 Gateway Timeout - Two EC2 instances with load balancer | <p>This might be the impossible issue. I've tried everything. I feel like there's a guy at a switchboard somewhere, twirling his mustache.</p>
<p><strong>The problem:</strong></p>
<p>I have Amazon EC2 running an application. It functions without issue when there is only one instance and no load balancer.</p>
<p>But in my production environment I have two identical instances running behind one load-balancer and when performing certain tasks, like a feature that generates a PDF and attaches it to an email, nothing happens at all, and when using Google Developer tools with the Network tab I get the error "504 Gateway Timeout" once the timeout hits (I have it set at 30 seconds).</p>
<p>My Database is external, on Amazon RDS.</p>
<p>I think.... If I could force a client to stay connected to their initial server they logged in at, this problem would be solved, because it's my understanding that the 504 Gateway Timeout is happening when instance-1 tries to reach out to instance-2 to perform the task.</p>
<p>This happens ONLY WHEN using Load Balancing, but never when connecting straight to one of my two servers.</p>
<p><strong>Load Balancer Settings:</strong></p>
<ul>
<li>The load balancer has a CRECORD on my Registrar so that app.myapplication.com points to myloadbalancerDNSname.elb.amazonaws.com</li>
<li>The load balancer has 2 healthy instances, each in the same region but they are in different availability zones.</li>
<li>The load balancer is using the same Security Groups as the Instances (allow ALL IPs on ports 22, 80, and 443)</li>
<li>The load balancer has cross-zone load balancing turned on.</li>
<li>CORS (in Amazon S3) is enabled to GET, POST, PUT, DELETE from * to * (I have no idea how this is associated with my instances but anyway I did it as the instructions said)</li>
<li>The load balancer has listeners configured as such: </li>
<li><ul>
<li>Load Balancer Protocol:HTTP Load Balancer Port:80 Instance Protocol:HTTP Instance Port:80</li>
</ul></li>
<li><ul>
<li>Load Balancer Protocol:HTTPS Load Balancer Port:443 Instance Protocol:HTTP Instance Port:80 (cipher chosen correctly per my Cert provider, and SSL fields 100% surely correct)</li>
</ul></li>
</ul>
<p><strong>Some more ideas:</strong></p>
<p>That being said, I'm not testing with HTTPS, but normal HTTP instead. I'm not convinced SSL is setup properly even though my certificate provider said it is. The reason I'm suspicious is that when I try to key in <a href="https://app.myapplication.com" rel="noreferrer">https://app.myapplication.com</a> I get the error "(failed) net::ERR_CONNECTION_CLOSED" in Google Developer Tools, in the Network tab. But this should be non-applicable because I'm having the problem even using regular HTTP. I can troubleshoot SSL later.</p>
<p>So to reiterate, my problem is having the "504 Gateway Timeout" problem when using some functions, but also occasionally at random instead of loading the page (but rarely). This 504 problem happens ONLY WHEN using Load Balancing, but never when connecting straight to one of my two instances.</p>
<p>I don't know which question to ask, because I've Followed every document to the T, double and triple checked all suggestions all over the web and NOTHING.</p> | 27,776,682 | 8 | 0 | null | 2014-10-24 06:56:21.863 UTC | 9 | 2022-07-26 06:18:45.05 UTC | 2014-10-24 07:04:28.81 UTC | null | 3,035,649 | null | 3,035,649 | null | 1 | 21 | amazon-ec2|load-balancing|http-status-code-504 | 53,719 | <p>In my case, it turns out that there was no problem with the load balancer. The final solution ending up being Ubuntu's hosts file in which there was an inexplicable entry to route traffic from some mystery IP to my application's host name. So, during the process of creating the PDF, paths were getting re-written by the PDF generator to point at the mystery server, and hence the Gateway timeout issues. I have no idea why it was occasionally working and not failing.</p>
<pre><code>127.0.0.1 localhost
127.0.1.1 ubuntu-server
42.139.126.191 app.myapp.com
</code></pre>
<p>This is what it looked like, so I removed that third line and all the gears started turning again. :P</p> |
61,396,989 | What is the docker-desktop-data distro used for when running docker desktop with the WSL 2 engine | <p>When running docker desktop on Windows with Hyper-V I have a single VM called DockerDesktopVM where my Linux VM is running with it's containers inside.</p>
<p><a href="https://i.stack.imgur.com/y0LGA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/y0LGA.png" alt="DockerDesktopVM"></a></p>
<p>However when I run docker desktop with the WSL engine I see that it creates 2 WSL distros.</p>
<ol>
<li>docker-desktop</li>
<li>docker-desktop-data</li>
</ol>
<p><a href="https://i.stack.imgur.com/N2EOf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/N2EOf.png" alt="enter image description here"></a> </p>
<p>I can shell into the docker-desktop distro like I would any other distro.</p>
<p><a href="https://i.stack.imgur.com/res9H.png" rel="noreferrer"><img src="https://i.stack.imgur.com/res9H.png" alt="enter image description here"></a></p>
<p>But trying to do the same to docker-desktop-data just bounces me out.</p>
<p><a href="https://i.stack.imgur.com/Y5XsI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Y5XsI.png" alt="enter image description here"></a></p>
<p>So my question is what is the docker-desktop-data distro for and why does it exist separately from the docker-desktop distro? Clearly the name implies data but what specific data and why can't I jump into the distro as I would any other? </p> | 61,431,088 | 2 | 0 | null | 2020-04-23 21:06:13.557 UTC | 8 | 2022-06-07 08:58:21.353 UTC | null | null | null | null | 2,529,475 | null | 1 | 39 | docker|windows-subsystem-for-linux|docker-for-windows|docker-desktop | 19,674 | <p>The docker-desktop-data distro is used by the docker-desktop distro as the backing store for container images etc. When docker is run under Hyper-V the same result is achieved by mounting a VHD in the Hyper-V image but this isn't possible with WSL2.</p>
<p>To quote from <a href="https://www.docker.com/blog/new-docker-desktop-wsl2-backend/" rel="nofollow noreferrer">the docker blog introducing the new wsl2 backend</a>:</p>
<blockquote>
<p>This will create 2 WSL distros for you:</p>
<pre><code>Docker-desktop, which I’ll call the bootstrapping distro
Docker-desktop-data, which I’ll call the data store distro
</code></pre>
<p>From a high level perspective, the bootstrapping distro essentially
replaces Hyper-V, while the data store distro replaces the VHD that we
previously attached to the VM.</p>
<p>The bootstrapping distro creates a Linux namespace with its own root
filesystem based on the same 2 iso files we mentioned earlier (not
entirely true, but close enough), and use the data-store distro as the
backing store for container images etc. instead of a VHD (WSL 2 does
not allow us to attach additional VHD at the moment, so we leverage
cross-distro mounts for that).</p>
</blockquote>
<p>To prevent you from being able to <code>wsl -d ubuntu-desktop-data</code> the distro has a 0-byte <code>/init</code>.</p>
<p><a href="https://www.docker.com/blog/new-docker-desktop-wsl2-backend/" rel="nofollow noreferrer">The blog post</a> is a great introduction to how docker on wsl works.</p> |
30,335,749 | Sending data / payload to the Google Chrome Push Notification with Javascript | <p>I'm working on the Google Chrome Push Notification and I'm trying to send the payload to the google chrome worker but, I have no idea how I receive this payload.</p>
<p>I have an API to create and save the notifications in my database and I need send the values through the <code>https://android.googleapis.com/gcm/send</code> and receive on the worker.js</p>
<p>This is my worker.js</p>
<pre><code> self.addEventListener('push', function(event) {
var title = 'Yay a message.';
var body = 'We have received a push message.';
var icon = '/images/icon-192x192.png';
var tag = 'simple-push-demo-notification-tag';
event.waitUntil(
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
);
});
</code></pre>
<p>And this is how I'm calling the GCM </p>
<pre><code>curl --header "Authorization: key=AIzaSyDQjYDxeS9MM0LcJm3oR6B7MU7Ad2x2Vqc" --header "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{ \"data\":{\"foo\":\"bar\"}, \"registration_ids\":[\"APA91bGqJpCmyCnSHLjY6STaBQEumz3eFY9r-2CHTtbsUMzBttq0crU3nEXzzU9TxNpsYeFmjA27urSaszKtA0WWC3yez1hhneLjbwJqlRdc_Yj1EiqLHluVwHB6V4FNdXdKb_gc_-7rbkYkypI3MtHpEaJbWsj6M5Pgs4nKqQ2R-WNho82mnRU\"]}"
</code></pre>
<p>I tried to get <code>event.data</code> but, this is undefined.</p>
<p>Does anyone have any idea or sugestion?</p> | 48,918,081 | 6 | 0 | null | 2015-05-19 20:42:42.353 UTC | 14 | 2018-08-20 19:30:15.42 UTC | null | null | null | null | 3,156,955 | null | 1 | 24 | javascript|google-chrome|push-notification | 23,483 | <p>To retrieve that data, you need to parse "event.data.text()" to a JSON object. I'm guessing something was updated since you tried to get this to work, but it works now. Unlucky! </p>
<p>However, since I made it to this post when searching for a solution myself, others would probably like a working answer. Here it is:</p>
<pre><code>// Push message event handler
self.addEventListener('push', function(event) {
// If true, the event holds data
if(event.data){
// Need to parse to JSON format
// - Consider event.data.text() the "stringify()"
// version of the data
var payload = JSON.parse(event.data.text());
// For those of you who love logging
console.log(payload);
var title = payload.data.title;
var body = payload.data.body;
var icon = './assets/icons/icon.ico'
var tag = 'notification-tag';
// Wait until payload is fetched
event.waitUntil(
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag,
data: {} // Keeping this here in case I need it later
})
);
} else {
console.log("Event does not have data...");
}
}); // End push listener
// Notification Click event
self.addEventListener('notificationclick', function(event) {
console.log("Notification Clicked");
}); // End click listener
</code></pre>
<p>Personally, I will be creating a "generic" notification in case my data is funky, and will also be using try/catch. I suggest doing the same.</p> |
30,450,763 | spark-streaming and connection pool implementation | <p>The spark-streaming website at <a href="https://spark.apache.org/docs/latest/streaming-programming-guide.html#output-operations-on-dstreams">https://spark.apache.org/docs/latest/streaming-programming-guide.html#output-operations-on-dstreams</a> mentions the following code:</p>
<pre><code>dstream.foreachRDD { rdd =>
rdd.foreachPartition { partitionOfRecords =>
// ConnectionPool is a static, lazily initialized pool of connections
val connection = ConnectionPool.getConnection()
partitionOfRecords.foreach(record => connection.send(record))
ConnectionPool.returnConnection(connection) // return to the pool for future reuse
}
}
</code></pre>
<p>I have tried to implement this using org.apache.commons.pool2 but running the application fails with the expected java.io.NotSerializableException: </p>
<pre><code>15/05/26 08:06:21 ERROR OneForOneStrategy: org.apache.commons.pool2.impl.GenericObjectPool
java.io.NotSerializableException: org.apache.commons.pool2.impl.GenericObjectPool
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
...
</code></pre>
<p>I am wondering how realistic it is to implement a connection pool that is serializable. Has anyone succeeded in doing this ?</p>
<p>Thank you. </p> | 30,593,303 | 2 | 0 | null | 2015-05-26 06:14:20.113 UTC | 17 | 2018-01-29 07:25:42.28 UTC | 2015-06-03 09:30:16.893 UTC | null | 764,040 | null | 478,746 | null | 1 | 9 | apache-spark|spark-streaming | 10,437 | <p>To address this "local resource" problem what's needed is a singleton object - i.e. an object that's warranted to be instantiated once and only once in the JVM. Luckily, Scala <code>object</code> provides this functionality out of the box.</p>
<p>The second thing to consider is that this singleton will provide a service to all tasks running on the same JVM where it's hosted, so, it <em>MUST</em> take care of concurrency and resource management.</p>
<p>Let's try to sketch(*) such service:</p>
<pre class="lang-scala prettyprint-override"><code>class ManagedSocket(private val pool: ObjectPool, val socket:Socket) {
def release() = pool.returnObject(socket)
}
// singleton object
object SocketPool {
var hostPortPool:Map[(String, Int),ObjectPool] = Map()
sys.addShutdownHook{
hostPortPool.values.foreach{ // terminate each pool }
}
// factory method
def apply(host:String, port:String): ManagedSocket = {
val pool = hostPortPool.getOrElse{(host,port), {
val p = ??? // create new pool for (host, port)
hostPortPool += (host,port) -> p
p
}
new ManagedSocket(pool, pool.borrowObject)
}
}
</code></pre>
<p>Then usage becomes:</p>
<pre><code>val host = ???
val port = ???
stream.foreachRDD { rdd =>
rdd.foreachPartition { partition =>
val mSocket = SocketPool(host, port)
partition.foreach{elem =>
val os = mSocket.socket.getOutputStream()
// do stuff with os + elem
}
mSocket.release()
}
}
</code></pre>
<p>I'm assuming that the <code>GenericObjectPool</code> used in the question is taking care of concurrency. Otherwise, access to each <code>pool</code> instance need to be guarded with some form of synchronization.</p>
<p>(*) code provided to illustrate the idea on how to design such object - needs additional effort to be converted into a working version.</p> |
455,911 | What's the best way to make sure only one instance of a Perl program is running? | <p>There are several ways to do this, but I'm not sure which one of them is the best.</p>
<p>Here's what I can think of:</p>
<ul>
<li>Look for the process using pgrep.</li>
<li>Have the script lock itself using flock, and then check if it is locked each time it runs.</li>
<li>Create a pid file in /var/run/program_name.pid and check for existence, and compare pids if needed.</li>
</ul>
<p>There are probably more ways to do this. What do you think is the best approach?</p> | 455,963 | 3 | 1 | null | 2009-01-18 21:19:59.113 UTC | 9 | 2019-02-22 04:30:33.123 UTC | 2019-02-22 04:30:33.123 UTC | brian d foy | 6,862,601 | Bonzo | 13,523 | null | 1 | 25 | perl|process|mutual-exclusion | 5,500 | <p>There are many ways to do it. PID files are the traditional way to do it. You could also hold a lock on a file, for example the program itself. This small piece of code will do the trick:</p>
<pre><code>use Fcntl ':flock';
open my $self, '<', $0 or die "Couldn't open self: $!";
flock $self, LOCK_EX | LOCK_NB or die "This script is already running";
</code></pre>
<p>One advantage over PID files is that files automatically get unlocked when the program exits. It's much easier to implement in a reliable way.</p> |
507,059 | Convert.ChangeType and converting to enums? | <p>I got an <code>Int16</code> value, from the database, and need to convert this to an enum type. This is unfortunately done in a layer of the code that knows very little about the objects except for what it can gather through reflection.</p>
<p>As such, it ends up calling <code>Convert.ChangeType</code> which fails with an invalid cast exception.</p>
<p>I found what I consider a smelly workaround, like this:</p>
<pre><code>String name = Enum.GetName(destinationType, value);
Object enumValue = Enum.Parse(destinationType, name, false);
</code></pre>
<p>Is there a better way, so that I don't have to move through this String operation?</p>
<p>Here's a short, but complete, program that can be used if anyone need to experiment:</p>
<pre><code>using System;
public class MyClass
{
public enum DummyEnum
{
Value0,
Value1
}
public static void Main()
{
Int16 value = 1;
Type destinationType = typeof(DummyEnum);
String name = Enum.GetName(destinationType, value);
Object enumValue = Enum.Parse(destinationType, name, false);
Console.WriteLine("" + value + " = " + enumValue);
}
}
</code></pre> | 507,091 | 3 | 2 | null | 2009-02-03 13:28:47.653 UTC | 2 | 2017-07-28 14:12:41.66 UTC | null | null | null | lassevk | 267 | null | 1 | 70 | c#|enums|changetype | 21,624 | <p><code>Enum.ToObject(....</code> is what you're looking for!</p>
<p><strong>C#</strong></p>
<pre><code>StringComparison enumValue = (StringComparison)Enum.ToObject(typeof(StringComparison), 5);
</code></pre>
<p><strong>VB.NET</strong></p>
<pre><code>Dim enumValue As StringComparison = CType([Enum].ToObject(GetType(StringComparison), 5), StringComparison)
</code></pre>
<p>If you do a lot of Enum converting try using the following class it will save you alot of code.</p>
<pre><code>public class Enum<EnumType> where EnumType : struct, IConvertible
{
/// <summary>
/// Retrieves an array of the values of the constants in a specified enumeration.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public static EnumType[] GetValues()
{
return (EnumType[])Enum.GetValues(typeof(EnumType));
}
/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
/// <remarks></remarks>
public static EnumType Parse(string name)
{
return (EnumType)Enum.Parse(typeof(EnumType), name);
}
/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
/// </summary>
/// <param name="name"></param>
/// <param name="ignoreCase"></param>
/// <returns></returns>
/// <remarks></remarks>
public static EnumType Parse(string name, bool ignoreCase)
{
return (EnumType)Enum.Parse(typeof(EnumType), name, ignoreCase);
}
/// <summary>
/// Converts the specified object with an integer value to an enumeration member.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks></remarks>
public static EnumType ToObject(object value)
{
return (EnumType)Enum.ToObject(typeof(EnumType), value);
}
}
</code></pre>
<p>Now instead of writing <code>(StringComparison)Enum.ToObject(typeof(StringComparison), 5);</code> you can simply write <code>Enum<StringComparison>.ToObject(5);</code>.</p> |
518,352 | Does Dispose still get called when exception is thrown inside of a using statement? | <p>In the example below, is the connection going to close and disposed when an exception is thrown if it is within a <code>using</code> statement?</p>
<pre><code>using (var conn = new SqlConnection("..."))
{
conn.Open();
// stuff happens here and exception is thrown...
}
</code></pre>
<p>I know this code below will make sure that it does, but I'm curious how using statement does it.</p>
<pre><code>var conn;
try
{
conn = new SqlConnection("...");
conn.Open();
// stuff happens here and exception is thrown...
}
// catch it or let it bubble up
finally
{
conn.Dispose();
}
</code></pre>
<p><h3>Related:</h3> <a href="https://stackoverflow.com/questions/141204/what-is-the-proper-way-to-ensure-a-sql-connection-is-closed-when-an-exception-is">What is the proper way to ensure a SQL connection is closed when an exception is thrown?</a></p> | 518,365 | 3 | 0 | null | 2009-02-05 22:51:42.243 UTC | 12 | 2019-05-09 18:37:30.377 UTC | 2017-05-23 12:02:11.563 UTC | Brian Kim | -1 | Brian Kim | 5,704 | null | 1 | 116 | c#|asp.net|using-statement | 33,207 | <p>Yes, <code>using</code> wraps your code in a try/finally block where the <code>finally</code> portion will call <code>Dispose()</code> if it exists. It won't, however, call <code>Close()</code> directly as it only checks for the <code>IDisposable</code> interface being implemented and hence the <code>Dispose()</code> method.</p>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/220234/intercepting-an-exception-inside-idisposable-dispose">Intercepting an exception inside IDisposable.Dispose</a></li>
<li><a href="https://stackoverflow.com/questions/141204/what-is-the-proper-way-to-ensure-a-sql-connection-is-closed-when-an-exception-is">What is the proper way to ensure a SQL connection is closed when an exception is thrown?</a></li>
<li><a href="https://stackoverflow.com/questions/149609/c-using-syntax">C# "Using" Syntax</a></li>
<li><a href="https://stackoverflow.com/questions/317184/c-using-keyword-when-and-when-not-to-use-it">C# USING keyword - when and when not to use it?</a></li>
<li><a href="https://stackoverflow.com/questions/278902/using-statement-vs-try-finally">'using' statement vs 'try finally'</a></li>
<li><a href="https://stackoverflow.com/questions/212198/what-is-the-c-using-block-and-why-should-i-use-it">What is the C# Using block and why should I use it?</a></li>
<li><a href="https://stackoverflow.com/questions/513672/disposable-using-pattern">Disposable Using Pattern</a></li>
<li><a href="https://stackoverflow.com/questions/376068/does-end-using-close-an-open-sql-connection">Does End Using close an open SQL Connection</a></li>
</ul> |
39,708,213 | Enable logging in docker mysql container | <p>I'm trying to get familiar with the docker ecosystem and tried to setup a mysql database container. With <code>docker-compose</code> this looks like:</p>
<pre><code>version: '2'
services:
db:
image: mysql:5.6.33@sha256:31ad2efd094a1336ef1f8efaf40b88a5019778e7d9b8a8579a4f95a6be88eaba
volumes:
- "./db/data:/var/lib/mysql"
- "./db/log:/var/log/mysql"
- "./db/conf:/etc/mysql/conf.d"
restart: "yes"
environment:
MYSQL_ROOT_PASSWORD: rootpw
MYSQL_DATABASE: db
MYSQL_USER: db
MYSQL_PASSWORD: dbpw
</code></pre>
<p>My conf directory contains one file:</p>
<pre><code>[mysqld]
log_error =/var/log/mysql/mysql_error.log
general_log_file=/var/log/mysql/mysql.log
general_log =1
slow_query_log =1
slow_query_log_file=/var/log/mysql/mysql_slow.log
long_query_time =2
log_queries_not_using_indexes = 1
</code></pre>
<p>Unfortunately I don't get any log files that way. The setup itself is correct and the cnf file is used. After connecting to the container and creating the 3 files, <code>chown</code> them to <code>mysql</code> and restarting the container, the logging is working as expected.</p>
<p>I'm pretty sure that this is a common scenario, and my current way to get it running seems really stupid. <strong>What is the correct way to do it?</strong> </p>
<p>I could improve my approach by moving all this stuff in a Dockerfile, but this still seem strange to me.</p> | 39,710,013 | 4 | 0 | null | 2016-09-26 16:48:39.223 UTC | 7 | 2022-07-07 07:31:26.223 UTC | null | null | null | null | 638,893 | null | 1 | 26 | mysql|logging|docker | 53,951 | <blockquote>
<p>After connecting to the container and creating the 3 files, chown them to mysql and restarting the container, the logging is working as expected.</p>
</blockquote>
<p>That points to a host volume permission issue. When you map from a container to the host, no mappings are made on user id's, and the name attached to the uid inside the container may be very different from outside. You need to initialize the directory permissions with something the container user can write to. One simple method is to create a group that has access to write to the files on both the host and container, and then add the various users to this group on both your image and host OS. Another option is to use a named filesystem that you don't access directly from your host and initialize it with the image's directory permissions.</p>
<hr>
<p>Edit: An example of a named volume with your docker-compose.yml is as simple as:</p>
<pre><code>version: '2'
volumes:
mysql-data:
driver: local
mysql-log:
driver: local
mysql-conf:
driver: local
services:
db:
image: mysql:5.6.33
volumes:
- "mysql-data:/var/lib/mysql"
- "mysql-log:/var/log/mysql"
- "mysql-conf:/etc/mysql/conf.d"
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: rootpw
MYSQL_DATABASE: db
MYSQL_USER: db
MYSQL_PASSWORD: dbpw
</code></pre>
<p>Note that I also removed the sha256 from your image name, this reference would block you from being able to pull patched versions of the image. I also prefer the "unless-stopped" restart policy so that Docker does expected things on a reboot.</p> |
39,668,916 | Angular2 get url query parameters | <p>I'm setting up a Facebook registration for my Angular2 web app.
Once the application accepted via Facebook (after being redirected to the Facebook authorization page), it redirect to my webapp with the token and code as url params:</p>
<pre><code>http://localhost:55976/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE
</code></pre>
<p>But once the page is loaded, the params are removed. The url become:</p>
<pre><code>http://localhost:55976/
</code></pre>
<p>How can I extract the parameters (access_token and code) before they are removed?
My routing configuration contains:</p>
<pre><code>{ path: 'login', component: LoginComponent },
{ path: 'login/:access_token/:code', component: LoginComponent },
</code></pre>
<p><strong>EDIT:</strong></p>
<p>Here is how I redirect to facebook in my login.component:
html:</p>
<pre><code><a class="btn btn-social btn-facebook socialaccount_provider facebook" title="Facebook" href="#" (click)="login_facebook()">
<span class="fa fa-facebook"></span> <span style="padding-left:25px">Sign in with Facebook</span>
</a>
</code></pre>
<p>Typescript:</p>
<pre><code>login_facebook() {
let url = 'https://www.facebook.com/dialog/oauth?'+
'client_id=my_client_id' +
'&redirect_uri=' + encodeURIComponent('http://localhost:55976/#/login/') +
'&response_type=code%20token';
console.log(url);
window.location.href = url;
}
</code></pre>
<p>The facebook api redirect to <a href="http://localhost:55976/#/login/" rel="noreferrer">http://localhost:55976/#/login/</a>, this is where I try to get the access_token and code parameters.</p>
<p><strong>EDIT 2:</strong></p>
<p>If I remove the sharp in the redirect url, facebook redirect me to the good URL, but without the sharp, angular cannot resolve the url.</p>
<p>Before removing '#':</p>
<pre><code>redirect_uri: http://localhost:55976/#/login/
facebook return: http://localhost:55976/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE
</code></pre>
<p>After removing '#':</p>
<pre><code>redirect_uri: http://localhost:55976/login/
facebook return: http://localhost:55976/login/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE
</code></pre>
<p>That mean that the problem comes from the sharp. But without the sharp, angular returns HTTP Error 404.0 - Not Found.</p> | 40,058,721 | 7 | 0 | null | 2016-09-23 20:19:23.173 UTC | 9 | 2019-03-01 13:33:30.11 UTC | 2016-09-24 10:18:59.033 UTC | null | 1,378,016 | null | 1,378,016 | null | 1 | 26 | url|angular|parameters|routing | 46,325 | <p>Here is my final working code:</p>
<p>Imports:</p>
<pre><code>import { Router, NavigationCancel } from '@angular/router';
import { URLSearchParams, } from '@angular/http';
</code></pre>
<p>Constructor:</p>
<pre><code> constructor(public router: Router) {
router.events.subscribe(s => {
if (s instanceof NavigationCancel) {
let params = new URLSearchParams(s.url.split('#')[1]);
let access_token = params.get('access_token');
let code = params.get('code');
}
});
}
</code></pre> |
6,609,582 | C# DLL Injection | <p>Is it possible to inject a DLL file into a process such as explorer or svchost using C#? I know this is possible in C++ but is it in C#? If so would it matter how the DLL was written, e.g. would it differ betweeen a C++ DLL or a Visual Studio C# .NET DLL? If this is at all possible could someone post the code that I could use to do this. Thank you very much.</p> | 6,609,628 | 1 | 0 | null | 2011-07-07 11:03:05.93 UTC | 10 | 2012-11-13 19:51:41.747 UTC | 2011-07-07 11:04:37.663 UTC | null | 374,104 | null | 799,586 | null | 1 | 14 | c#|dll-injection | 33,584 | <p>Yes it is possible: <a href="http://www.codingthewheel.com/archives/how-to-inject-a-managed-assembly-dll" rel="noreferrer">http://www.codingthewheel.com/archives/how-to-inject-a-managed-assembly-dll</a></p>
<p>Since that link appears to be down, here's a cached version: <a href="http://web.archive.org/web/20101224064236/http://codingthewheel.com/archives/how-to-inject-a-managed-assembly-dll" rel="noreferrer">http://web.archive.org/web/20101224064236/http://codingthewheel.com/archives/how-to-inject-a-managed-assembly-dll</a></p> |
6,338,752 | Mongoid Scope order by syntax please | <p>I'm using the latest mongoid...</p>
<p>How do I do the mongoid equivalent of this active record named_scope:</p>
<pre><code>class Comment
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :post
field :body, :type => String
named_scope :recent, :limit => 100, :order => 'created_at DESC'
...
end
</code></pre> | 6,339,085 | 1 | 0 | null | 2011-06-14 03:26:26.017 UTC | 10 | 2012-11-18 16:44:14.29 UTC | null | null | null | null | 322,557 | null | 1 | 18 | ruby-on-rails|mongodb|scope|mongoid|named-scope | 12,777 | <p>It has to be defined like this</p>
<pre><code>scope :recent, order_by(:created_at => :desc).limit(100)
</code></pre>
<p>You can check out the mongoid documentation for scopes <a href="http://mongoid.org/en/mongoid/docs/querying.html#scoping">here</a></p>
<p>From the page</p>
<p>Named scopes are defined at the class level using a scope macro and can be chained to create result sets in a nice DSL.</p>
<pre><code>class Person
include Mongoid::Document
field :occupation, type: String
field :age, type: Integer
scope :rock_n_rolla, where(occupation: "Rockstar")
scope :washed_up, where(:age.gt => 30)
scope :over, ->(limit) { where(:age.gt => limit) }
end
# Find all the rockstars.
Person.rock_n_rolla
# Find all rockstars that should probably quit.
Person.washed_up.rock_n_rolla
# Find a criteria with Keith Richards in it.
Person.rock_n_rolla.over(60)
</code></pre> |
42,026,239 | What does font-size really correspond to? | <p>I am trying to find what the value set in the <code>font-size</code> CSS property is corresponding to.</p>
<p>To give the context, I want to get in CSS the size in <code>em</code> of parts of the font (above the capital height and under the baseline) that I know from its OS/2 metrics. The <code>em</code> unit is relative to the given <code>font-size</code> and the OS/2 metrics are relative to the em-square.</p>
<h1>What I expect</h1>
<p>My expectations are based on the following references. I did not found anything more clear or precise.</p>
<ol>
<li><p>According to the <a href="https://www.w3.org/TR/CSS21/fonts.html#propdef-font-size" rel="noreferrer">W3C reference for <code>font-size</code> in CSS2.1</a>, and as quoted in all the Stack Overflow questions I found on the topic (<a href="https://stackoverflow.com/questions/3495872/how-is-font-size-calculated/3495925#3495925">here</a>, <a href="https://stackoverflow.com/questions/11073602/css-font-size-specifics/11074476#11074476">here</a> and <a href="https://stackoverflow.com/questions/2269997/clarification-what-exactly-css-font-size-measures/2270025#2270025">here</a>):</p>
<blockquote>
<p>The font size corresponds to the em square, a concept used in typography. Note that certain glyphs may bleed outside their em squares.</p>
</blockquote></li>
<li><p>Following the few knowledges I have in typography, the <code>em square</code> is the entire square of font metrics in which ascending, descending, gaps, (etc...) lines are defined. In OS/2 metrics, the <code>em square</code> is the size of the font itself (often 1000 or 2048 UPM).</p>
<p><a href="https://i.stack.imgur.com/7FltD.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/7FltD.gif" alt="Letter metrics"></a><br>
<sub>(source: <a href="https://www.microsoft.com/typography/otspec/images/IMG00294.GIF" rel="noreferrer">microsoft.com</a>)</sub> </p>
<p>The only explanation I found from W3C is in an <a href="https://www.w3.org/TR/WD-font-970721#emsq" rel="noreferrer">old reference from 1997 for CSS1</a>, and it is coherent with the modern digital definition of <code>em square</code> I use:</p>
<blockquote>
<p>Certain values, such as width metrics, are expressed in units that are relative to an abstract square whose height is the intended distance between lines of type in the same type size. This square is called the EM square. (...) Common values are 250 (Intellifont), 1000 (Type 1) and 2048 (TrueType).</p>
</blockquote></li>
</ol>
<p>So if I understand these references correctly, the <em>value specified in <code>font-size</code></em> should be used to generate the <em>entire <code>em square</code></em> of the font, and we should be able to calculate the size of a part of the font from the font's size and metrics.</p>
<p>For example, with...</p>
<pre class="lang-css prettyprint-override"><code>.my-letter {
font-family: 'Helvetica Neue';
font-size: 100px;
text-transform: uppercase;
}
</code></pre>
<p>... we should have an <code>em square</code> of <code>100px</code>, and because <code>Helvetica Neue</code> has a Capital Height of <code>714 / 1000</code> (<code>sCapHeight</code> in the OS/2 table), a capital height of <code>71.4px</code>.</p>
<p><a href="https://i.stack.imgur.com/9v7Zt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9v7Zt.png" alt="Expected Letter"></a></p>
<h1>What actually happens.</h1>
<p>The generated <code>em square</code> is <strong>bigger</strong> than <code>font-size</code> (tested on the latest versions of Chrome, Firefox and Safari for Mac). At first, I thought that the browser had an other definition of <code>em square</code> and was making a <em>part</em> of the letter equal to <code>font-size</code>, but I did not found any OS/2 metrics (with or without ascender, descender, gaps...) that matches with it.</p>
<p><a href="https://i.stack.imgur.com/1jMnS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1jMnS.png" alt="Rendered Letter"></a></p>
<p>You can also see <a href="https://codepen.io/ncoden/pen/mRJvEg" rel="noreferrer">this CodePen</a>. Please note that I use <code>line-height: 1;</code> to highlight the expected size, but my problem is with <code>font-size</code> (the "rendered ink") and not <code>line-height</code> (the "collision box"). This is something I have to precise because I have already been misunderstood several times. <em><code>line-height</code> is not the problem</em>.</p>
<hr>
<p>So I have three questions:</p>
<ul>
<li>Did I understood correctly the W3C references, or I am assuming things that these references did not said?</li>
<li>If not, why does the generated font have an em-square greater than <code>font-size</code>?</li>
<li>The most important: <strong>How could I know the size of the rendered em-square</strong> (relatively to the <code>font-size</code>) ?</li>
</ul>
<p>Thank you for your help.</p> | 42,036,689 | 2 | 2 | null | 2017-02-03 14:13:16.327 UTC | 5 | 2021-03-25 12:09:54.773 UTC | 2019-10-09 17:16:09.22 UTC | null | 4,751,173 | null | 4,317,384 | null | 1 | 29 | css|fonts|font-size|w3c|fontmetrics | 3,993 | <p>Your understanding of the W3C references is correct, but your understanding of the red box is not.</p>
<p>The red box does not depict the em-square. Its height is the sum of the ascent and descent from the metrics.</p> |
36,312,494 | How to use Gitlab CI/CD to deploy a meteor project? | <p>As claimed at their website Gitlab can be used to auto deploy projects after some code is pushed into the repository but I am not able to figure out how. There are plenty of ruby tutorials out there but none for meteor or node.</p>
<p>Basically I just need to rebuild an Docker container on my server, after code is pushed into my master branch. Does anyone know how to achieve it? I am totally new to the .gitlab-ci.yml stuff and appreciate help pretty much. </p> | 37,188,570 | 1 | 1 | null | 2016-03-30 14:53:59.943 UTC | 10 | 2016-05-12 13:34:58.663 UTC | null | null | null | null | 1,255,102 | null | 1 | 17 | meteor|gitlab|gitlab-ci|continuous-delivery | 5,717 | <p><em>Brief: I am running a Meteor 1.3.2 app, hosted on Digital Ocean (Ubuntu 14.04) since 4 months. I am using Gitlab v. 8.3.4 running on the same Digital Ocean droplet as the Meteor app. It is a 2 GB / 2 CPUs droplet ($ 20 a month). Using the built in Gitlab CI for CI/CD. This setup has been running successfully till now. (We are currently not using Docker, however this should not matter.)</em></p>
<p><strong>Our CI/CD strategy:</strong></p>
<ol>
<li>We check out Master branch on our local laptop. The branch contains the whole Meteor project as shown below:</li>
</ol>
<p><a href="https://i.stack.imgur.com/12rMz.png"><img src="https://i.stack.imgur.com/12rMz.png" alt="enter image description here"></a></p>
<p>We use git CLI tool on Windows to connect to our Gitlab server. (for pull, push, etc. similar regular git activities)</p>
<ol start="2">
<li><p>Open the checked out project in Atom editor. We have also integrated Atom with Gitlab. This helps in quick git status/pull/push etc. within Atom editor itself. Do regular Meteor work viz. fix bugs etc.</p></li>
<li><p>Post testing on local laptop, we then do git push & commit on master. This triggers auto build using Gitlab CI and the results (including build logs) can be seen in Gitlab itself as shown below:</p></li>
</ol>
<p><a href="https://i.stack.imgur.com/lUJ9y.png"><img src="https://i.stack.imgur.com/lUJ9y.png" alt="enter image description here"></a></p>
<p>Below image shows all previous build logs:</p>
<p><a href="https://i.stack.imgur.com/XStWE.png"><img src="https://i.stack.imgur.com/XStWE.png" alt="enter image description here"></a></p>
<p><strong>Please follow below steps:</strong></p>
<ol>
<li><p>Install meteor on the DO droplet.</p></li>
<li><p>Install Gitlab on DO (using 1-click deploy if possible) or manual installation. Ensure you are installing Gitlab v. 8.3.4 or newer version. I had done a DO one-click deploy on my droplet.
Start the gitlab server & log into gitlab from browser. Open your project and go to project settings -> Runners from left menu</p></li>
</ol>
<p><a href="https://i.stack.imgur.com/F2YwJ.png"><img src="https://i.stack.imgur.com/F2YwJ.png" alt="enter image description here"></a></p>
<ol start="3">
<li><p>SSH to your DO server & configure a new upstart service on the droplet as root:</p>
<pre><code>vi /etc/init/meteor-service.conf
</code></pre></li>
</ol>
<p>Sample file:</p>
<pre><code>#upstart service file at /etc/init/meteor-service.conf
description "Meteor.js (NodeJS) application for eaxmple.com:3000"
author "[email protected]"
# When to start the service
start on runlevel [2345]
# When to stop the service
stop on shutdown
# Automatically restart process if crashed
respawn
respawn limit 10 5
script
export PORT=3000
# this allows Meteor to figure out correct IP address of visitors
export HTTP_FORWARDED_COUNT=1
export MONGO_URL=mongodb://xxxxxx:[email protected]:59672/meteor-db
export ROOT_URL=http://<droplet_ip>:3000
exec /home/gitlab-runner/.meteor/packages/meteor-tool/1.1.10/mt-os.linux.x86_64/dev_bundle/bin/node /home/gitlab-runner/erecaho-build/server-alpha-running/bundle/main.js >> /home/gitlab-runner/erecaho-build/server-alpha-running/meteor.log
end script
</code></pre>
<ol start="4">
<li><p>Install gitlab-ci-multi-runner from here: <a href="https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/linux-repository.md">https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/linux-repository.md</a> as per the instructions
<em>Cheatsheet:</em></p>
<pre><code>curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-ci-multi-runner/script.deb.sh | sudo bash
sudo apt-get install gitlab-ci-multi-runner
sudo gitlab-ci-multi-runner register
</code></pre>
<p>Enter details from step 2</p></li>
<li><p>Now the new runner should be green or activate the runner if required</p></li>
<li><p>Create .gitlab-ci.yml within the meteor project directory</p>
<p>Sample file:</p>
<pre><code>before_script:
- echo "======================================"
- echo "==== START auto full script v0.1 ====="
- echo "======================================"
types:
- cleanup
- build
- test
- deploy
job_cleanup:
type: cleanup
script:
- cd /home/gitlab-runner/erecaho-build
- echo "cleaning up existing bundle folder"
- echo "cleaning up current server-running folder"
- rm -fr ./server-alpha-running
- mkdir ./server-alpha-running
only:
- master
tags:
- master
job_build:
type: build
script:
- pwd
- meteor build /home/gitlab-runner/erecaho-build/server-alpha-running --directory --server=http://example.org:3000 --verbose
only:
- master
tags:
- master
job_test:
type: test
script:
- echo "testing ----"
- cd /home/gitlab-runner/erecaho-build/server-alpha-running/bundle
- ls -la main.js
only:
- master
tags:
- master
job_deploy:
type: deploy
script:
- echo "deploying ----"
- cd /home/gitlab-runner/erecaho-build/server-alpha-running/bundle/programs/server/ && /home/gitlab-runner/.meteor/packages/meteor-tool/1.1.10/mt-os.linux.x86_64/dev_bundle/bin/npm install
- cd ../..
- sudo restart meteor-service
- sudo status meteor-service
only:
- master
tags:
- master
</code></pre></li>
<li><p>Check in above file in gitlab. This should trigger Gitlab CI and after the build process is complete, the new app will be available @ example.net:3000</p></li>
</ol>
<p><strong>Note</strong>: The app will not be available after checking in .gitlab-ci.yml for the first time, since restart meteor-service will result in service not found. Manually run sudo start meteor-service once on DO SSH console. Post this any new check-in to gitlab master will trigger auto CI/CD and the new version of the app will be available on example.com:3000 after the build is completed successfully.</p>
<p><em>P.S.: gitlab ci yaml docs can be found at <a href="http://doc.gitlab.com/ee/ci/yaml/README.html">http://doc.gitlab.com/ee/ci/yaml/README.html</a> for your customization and to understand the sample yaml file above.
For docker specific runner, please refer <a href="https://gitlab.com/gitlab-org/gitlab-ci-multi-runner">https://gitlab.com/gitlab-org/gitlab-ci-multi-runner</a></em></p> |
36,187,522 | React select with value null | <p>I have the following code as part of my React component:</p>
<pre><code><select
className="input form-control"
onChange={this.onUserChanged}
value={task.user_id}>
<option value=''></option>
{this.renderUserOptions()}
</select>
</code></pre>
<p>When the task.user_id is null on the first rendering of the component, the select is properly displayed with the empty option with value <code>''</code>.</p>
<p>However, if I change the value from something that has a value back to the default option, the server side updates correctly, the task object returns the <code>null</code> for <code>task.user_id</code> but the select doesn't change to the default value.</p>
<p>What should I do to handle this scenario?</p>
<hr> | 36,188,373 | 3 | 1 | null | 2016-03-23 19:55:36.997 UTC | 6 | 2022-02-02 09:17:10.17 UTC | 2018-09-12 07:52:42.687 UTC | null | 1,727,948 | null | 14,540 | null | 1 | 30 | javascript|reactjs | 67,172 | <p>When setting the value for your select component, you will have to convert <code>null</code> to <code>''</code>; and when receiving the value from your component, you will have to convert <code>''</code> to <code>null</code>. A simple example:</p>
<pre><code>class Example extends React.Component {
constructor(props) {
super(props);
this.state = { selected: null };
}
render() {
return <div>
<select
className="input form-control"
onChange={e => this.setState({ selected: e.target.value || null })}
value={this.state.selected || ''}>
<option value=''></option>
<option value='1'>cook dinner</option>
<option value='2'>do dishes</option>
<option value='3'>walk dog</option>
</select>
<input type='button' onClick={() => this.setState({ selected: null })} value='Reset' />
</div>
}
}
</code></pre>
<p>This works assuming that your ids are always truthy: <code>e.target.value || null</code> will convert the selected empty string to <code>null</code>; and <code>this.state.selected || ''</code> will convert your <code>null</code> state to an empty string. If your ids can be falsey (for example the number <code>0</code>), you will need a more robust conversion.</p>
<p><a href="https://jsfiddle.net/iaretiga/v2each25/1/" rel="noreferrer">See Fiddle here</a>.</p> |
6,314,841 | Django TypeError: 'RelatedManager' object is not iterable | <p>I have these Django models:</p>
<pre><code>class Group(models.Model):
name = models.CharField(max_length=100)
parent_group = models.ManyToManyField("self", blank=True)
def __unicode__(self):
return self.name
class Block(models.Model):
name = models.CharField(max_length=100)
app = models.CharField(max_length=100)
group = models.ForeignKey(Group)
def __unicode__(self):
return self.name
</code></pre>
<p>Lets say that block <strong>b1</strong> has the <strong>g1</strong> group. By it's name I want to get <strong>all blocks</strong> from group <strong>g1</strong>. I wrote this recursive function:</p>
<pre><code>def get_blocks(group):
def get_needed_blocks(group):
for block in group.block_set:
blocks.append(block)
if group.parent_group is not None:
get_needed_blocks(group.parent_group)
blocks = []
get_needed_blocks(group)
return blocks
</code></pre>
<p>But <strong>b1.group.block_set</strong> returns a <strong>RelatedManager</strong> object, which is not iterable.</p>
<p>What am I doing wrong and how can I fix it?</p> | 6,314,856 | 3 | 0 | null | 2011-06-11 08:02:42.16 UTC | 12 | 2022-08-29 16:09:42.117 UTC | 2022-08-29 16:09:42.117 UTC | null | 209,920 | null | 378,767 | null | 1 | 107 | python|django|django-models|django-queryset | 65,584 | <p>Try this:</p>
<pre><code>block in group.block_set.all()
</code></pre> |
5,610,527 | boost Shared_pointer NULL | <p>I'm using <code>reset()</code> as a default value for my shared_pointer (equivalent to a <code>NULL</code>).</p>
<p>But how do I check if the shared_pointer is <code>NULL</code>?</p>
<p>Will this return the right value ?</p>
<pre><code>boost::shared_ptr<Blah> blah;
blah.reset()
if (blah == NULL)
{
//Does this check if the object was reset() ?
}
</code></pre> | 5,610,531 | 4 | 0 | null | 2011-04-10 08:10:51.577 UTC | 5 | 2018-06-20 23:24:10.17 UTC | 2016-03-31 20:29:15.467 UTC | null | 3,964,927 | null | 536,086 | null | 1 | 29 | c++|boost|shared-ptr|smart-pointers | 35,691 | <p>Use:</p>
<pre><code>if (!blah)
{
//This checks if the object was reset() or never initialized
}
</code></pre> |
1,383,528 | Capturing all multitouch trackpad input in Cocoa | <p>Using touchesBeganWithEvent, touchesEndedWithEvent, etc you can get the touch data from the multitouch trackpad, but is there a way to block that touch data from moving the mouse/activating the system-wide gestures (similar to what is done in the chinese text input)?</p> | 13,755,292 | 2 | 1 | null | 2009-09-05 14:59:29.783 UTC | 11 | 2013-07-22 05:57:45.06 UTC | null | null | null | null | 169,021 | null | 1 | 13 | objective-c|cocoa|macos|multi-touch | 4,807 | <p>As noted by valexa, using NSEventMask for CGEventTap is a hack. Tarmes also notes that Rob Keniger's answer no longer works (OS X >= 10.8). Luckily, Apple has provided a way to do this quite easily by using <code>kCGEventMaskForAllEvents</code> and converting the CGEventRef to an NSEvent within the callback:</p>
<pre><code>NSEventMask eventMask = NSEventMaskGesture|NSEventMaskMagnify|NSEventMaskSwipe|NSEventMaskRotate|NSEventMaskBeginGesture|NSEventMaskEndGesture;
CGEventRef eventTapCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef eventRef, void *refcon) {
// convert the CGEventRef to an NSEvent
NSEvent *event = [NSEvent eventWithCGEvent:eventRef];
// filter out events which do not match the mask
if (!(eventMask & NSEventMaskFromType([event type]))) { return [event CGEvent]; }
// do stuff
NSLog(@"eventTapCallback: [event type] = %d", [event type]);
// return the CGEventRef
return [event CGEvent];
}
void initCGEventTap() {
CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionListenOnly, kCGEventMaskForAllEvents, eventTapCallback, nil);
CFRunLoopAddSource(CFRunLoopGetCurrent(), CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0), kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRunLoopRun();
}
</code></pre>
<p>Note that the call to <code>CFRunLoopRun()</code> is included since this snippet was taken from a project which could not use NSApplication but instead had a bare-bones CFRunLoop. Omit it if you use NSApplication.</p> |
1,934,624 | Item assignment to bytes object? | <p>GAHH, code not working is bad code indeed!</p>
<pre class="lang-none prettyprint-override"><code> in RemoveRETNs
toOutput[currentLoc - 0x00400000] = b'\xCC' TypeError: 'bytes' object does not support item assignment
</code></pre>
<p>How can I fix this?</p>
<pre><code>inputFile = 'original.exe'
outputFile = 'output.txt'
patchedFile = 'original_patched.exe'
def GetFileContents(filename):
f = open(filename, 'rb')
fileContents = f.read()
f.close()
return fileContents
def FindAll(fileContents, strToFind):
found = []
lastOffset = -1
while True:
lastOffset += 1
lastOffset = fileContents.find(b'\xC3\xCC\xCC\xCC\xCC', lastOffset)
if lastOffset != -1:
found.append(lastOffset)
else:
break
return found
def FixOffsets(offsetList):
for current in range(0, len(offsetList)):
offsetList[current] += 0x00400000
return offsetList
def AbsentFromList(toFind, theList):
for i in theList:
if i == toFind:
return True
return False
# Outputs the original file with all RETNs replaced with INT3s.
def RemoveRETNs(locationsOfRETNs, oldFilesContents, newFilesName):
target = open(newFilesName, 'wb')
toOutput = oldFilesContents
for currentLoc in locationsOfRETNs:
toOutput[currentLoc - 0x00400000] = b'\xCC'
target.write(toOutput)
target.close()
fileContents = GetFileContents(inputFile)
offsets = FixOffsets(FindAll(fileContents, '\xC3\xCC\xCC\xCC\xCC'))
RemoveRETNs(offsets, fileContents, patchedFile)
</code></pre>
<p>What am I doing wrong, and what can I do to fix it? Code sample?</p> | 1,934,649 | 2 | 0 | null | 2009-12-20 01:16:16.26 UTC | 1 | 2020-09-10 10:20:11.933 UTC | 2020-09-10 10:20:11.933 UTC | null | 355,230 | null | 105,760 | null | 1 | 16 | python|python-3.x | 47,402 | <p>Change the <code>return</code> statement of <code>GetFileContents</code> into</p>
<pre><code>return bytearray(fileContents)
</code></pre>
<p>and the rest should work. You need to use <code>bytearray</code> rather than <code>bytes</code> simply because the former is mutable (read/write), the latter (which is what you're using now) is immutable (read-only).</p> |
1,347,776 | How to correctly setup a NSPredicate for a to-many relationship when using Core Data? | <p>I have a Core Data model in which a Task entity includes an optional to-many relationship ExcludedDays to the ExcludedDay entity. One of the properties of ExcludedDay is day, which is an NSDate object. The ExcludedDay entity has an inverse mandatory to-one relationship to the Task entity.</p>
<p>In order to fetch the tasks for a specified day, I need to make sure that the specified day does not appear as the day property of any ExludedDay entity.</p>
<p>I started trying</p>
<pre><code>NSPredicate *dayIsNotExcludedPredicate = [NSPredicate predicateWithFormat: @"ALL excludedDays.day != %@", today];
</code></pre>
<p>However, despite what the documentation says, ALL does not work and the application throws an exception: Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘Unsupported predicate.</p>
<p>After posting the same question in this forum, I was able to devise the following predicate with the help of various people:</p>
<pre><code>NSPredicate * dayIsNotExcludedPredicate = [NSPredicate predicateWithFormat: @"excludedDays.@count == 0 || (excludedDays.@count > 0 && NONE excludedDays.day == %@))", today];
</code></pre>
<p>While this worked at first, I have just discovered that this only works when the ExcludedDay entity contains ONLY one day. As soon as the ExcludedDay entity contains more than one day for the same task, this predicate stops working. As a result, a task is selected for a day even though the day appears as a day in the ExcludedDay entity, which is of course wrong. The problem is not tied to the property day being a NSDate object: replacing day with the corresponding NSString or equivalently with an integer, I still face the same issue and incorrect behaviour.</p>
<p>What is the correct way to implement the predicate in this case? May this be a bug related to the ANY aggregate operator when using core data?
Thank you in advance, this is now driving me crazy.</p> | 1,425,834 | 2 | 0 | null | 2009-08-28 15:34:26.973 UTC | 20 | 2009-09-15 08:12:41.333 UTC | null | null | null | null | 68,814 | null | 1 | 22 | iphone|core-data | 25,009 | <p>It turns out this is yet another problem with missing and/or inconsistent documentation.</p>
<p>The correct predicate in this case is the following one:</p>
<pre><code>[NSPredicate predicateWithFormat:@"(excludedOccurrences.@count == 0) OR (0 == SUBQUERY(excludedOccurrences, $sub, $sub.day == %@).@count)", today]
</code></pre>
<p>In the predicate, a subquery is used to test if the number of related excludedOccurrences with a date matching your test date is equal to zero. However, the documentation is misleading. Here is what the Predicate Programming Guide says regarding the use of predicates in conjunction with to-many relationships.</p>
<p>Using Predicates with Relationships</p>
<p>If you use a to-many relationship, the construction of a predicate is slightly different. If you want to fetch Departments in which at least one of the employees has the first name "Matthew," for instance, you use an ANY operator as shown in the following example:</p>
<pre><code>NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"ANY employees.firstName like 'Matthew'"];
</code></pre>
<p>If you want to find Departments in which all the employees are paid more than a certain amount, you use an ALL operator as shown in the following example:</p>
<pre><code>float salary = ... ;
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"ALL employees.salary > %f", salary];
</code></pre> |
1,901,828 | Best python XMPP / Jabber client library? | <p>What are your experiences with Python Jabber / XMPP client libraries?
What do you recommend?</p> | 1,930,276 | 2 | 0 | null | 2009-12-14 16:11:59.227 UTC | 23 | 2020-07-18 22:48:26.233 UTC | null | null | null | null | 63,051 | null | 1 | 55 | python|chat|xmpp|google-talk | 44,823 | <p>It depends what license you can use. Some popular libraries are GPL which can cause serious issues if you need to use it for work, especially if you need to keep proprietary extensions. The LGPL libraries are a little less popular, I think, but you have more flexibility with what you can use them for.</p>
<p>I'd once looked at using twisted directly for some simple XMPP scripting but the documentation was literally non-existant. Like, I opened a published twisted reference manual and it didn't include xmpp or jabbber <em>at all</em>. Maybe they've fixed that now.</p>
<p>MIT libraries.</p>
<ul>
<li><a href="https://dev.louiz.org/projects/slixmpp" rel="noreferrer" title="slixmpp">slixmpp</a> is a friendly fork of sleekxmpp. It has removed all threads and is for python 3.7+.</li>
<li><a href="https://github.com/fritzy/SleekXMPP/wiki" rel="noreferrer">sleekxmpp</a> was pretty popular and was used for
examples in Peter Saint-Andre's XMPP
book from O'Reilly. It has been depricated in favor of slixmpp.</li>
</ul>
<p>GPL libraries.</p>
<ul>
<li><a href="http://xmpppy.sourceforge.net/" rel="noreferrer">xmpppy</a> was used by gajim from 2005-2014, and began as a forked jabberpy. Also lives at <a href="https://github.com/normanr/xmpppy" rel="noreferrer">xmpppy</a>.</li>
<li><a href="https://python-nbxmpp.gajim.org/" rel="noreferrer">nbxmpp</a> forked xmpppy, and is used by gajim. It requires python 3.7+ and is actively maintained.</li>
</ul>
<p>LPGL libraries.</p>
<ul>
<li><a href="https://github.com/horazont/aioxmpp" rel="noreferrer" title="aioxmpp">aioxmpp</a> is an asyncio-based python 3.4+ library.</li>
<li><a href="https://github.com/Jajcus/pyxmpp" rel="noreferrer">pyxmpp</a> is abandoned in favor of pyxmpp2. It uses libxml2 internally for xml parsing.</li>
<li><a href="https://github.com/Jajcus/pyxmpp2" rel="noreferrer">pyxmpp2</a> is the next version of pyxmpp, runs on python 2.7 and 3.3, and removes the libxml2 requirement. Like many, it requires <a href="http://www.dnspython.org/" rel="noreferrer">dnspython</a>.</li>
<li><a href="http://jabberpy.sourceforge.net/" rel="noreferrer">jabberpy</a> is the original and is thoroughly unmaintained.</li>
</ul>
<p>Other libraries.</p>
<ul>
<li><a href="http://wokkel.ik.nu/" rel="noreferrer">Wokkel</a>, mentioned in another post. That's a new one for me, based on twisted.</li>
</ul> |
29,223,071 | How do I require() from the console using webpack? | <p>How do I require() / import modules from the console? For example, say I've installed the ImmutableJS npm, I'd like to be able to use functions from the module while I'm working in the console.</p> | 39,410,265 | 10 | 1 | null | 2015-03-24 00:47:29.313 UTC | 7 | 2022-01-05 21:57:28.473 UTC | null | null | null | null | 294,247 | null | 1 | 49 | javascript|ecmascript-6|webpack | 18,636 | <p>Here's another more generic way of doing this.</p>
<h1>Requiring a module by ID</h1>
<p>The current version of WebPack exposes <code>webpackJsonp(...)</code>, which can be used to require a module by ID:</p>
<pre class="lang-js prettyprint-override"><code>function _requireById(id) {
return webpackJsonp([], null, [id]);
}
</code></pre>
<p>or in TypeScript
</p>
<pre><code>window['_requireById'] =
(id: number): any => window['webpackJsonp'];([], null, [id]);
</code></pre>
<p>The ID is visible at the top of the module in the bundled file or in the footer of the original source file served via source maps.</p>
<h1>Requiring a module by name</h1>
<p>Requiring a module by name is much trickier, as WebPack doesn't appear to keep any reference to the module path once it has processed all the sources. But the following code seems to do the trick in lot of the cases:</p>
<pre><code>/**
* Returns a promise that resolves to the result of a case-sensitive search
* for a module or one of its exports. `makeGlobal` can be set to true
* or to the name of the window property it should be saved as.
* Example usage:
* _requireByName('jQuery', '$');
* _requireByName('Observable', true)´;
*/
window['_requireByName'] =
(name: string, makeGlobal?: (string|boolean)): Promise<any> =>
getAllModules()
.then((modules) => {
let returnMember;
let module = _.find<any, any>(modules, (module) => {
if (_.isObject(module.exports) && name in module.exports) {
returnMember = true;
return true;
} else if (_.isFunction(module.exports) &&
module.exports.name === name) {
return true;
}
});
if (module) {
module = returnMember ? module.exports[name] : module.exports;
if (makeGlobal) {
const moduleName = makeGlobal === true ? name : makeGlobal as string;
window[moduleName] = module;
console.log(`Module or module export saved as 'window.${moduleName}':`,
module);
} else {
console.log(`Module or module export 'name' found:`, module);
}
return module;
}
console.warn(`Module or module export '${name}'' could not be found`);
return null;
});
// Returns promise that resolves to all installed modules
function getAllModules() {
return new Promise((resolve) => {
const id = _.uniqueId('fakeModule_');
window['webpackJsonp'](
[],
{[id]: function(module, exports, __webpack_require__) {
resolve(__webpack_require__.c);
}},
[id]
);
});
}
</code></pre>
<p>This is quick first shot at this, so it's all up for improvement!</p> |
6,311,855 | C# is rounding down divisions by itself | <p>When I make a division in C#, it automaticaly rounds down. See this example: </p>
<pre><code>double i;
i = 200 / 3;
Messagebox.Show(i.ToString());
</code></pre>
<p>This shows me a messagebox containing "66". 200 / 3 is actually 66.66666~ however.</p>
<p>Is there a way I can avoid this rounding down and keep a number like 66.6666667?</p> | 6,311,881 | 10 | 3 | null | 2011-06-10 20:43:30.84 UTC | 3 | 2014-10-28 04:26:34.327 UTC | null | null | null | null | 769,490 | null | 1 | 36 | c#|division | 39,813 | <p><code>i = 200 / 3</code> is performing integer division.</p>
<p>Try either:</p>
<p><code>i = (double)200 / 3</code></p>
<p>or</p>
<p><code>i = 200.0 / 3</code></p>
<p>or</p>
<p><code>i = 200d / 3</code></p>
<p>Declaring one of the constants as a double will cause the double division operator to be used.</p> |
6,182,644 | "Missing compiler required member" error being thrown multiple times with almost no changes to code | <p>Today after deploying some changes to a C# MVC site that I run, I went back to make some more modifications and came across this error:</p>
<blockquote>
<p>Missing compiler required member System.Runtime.CompilerServices.ExtensionAttribute..ctor</p>
</blockquote>
<p>The error is a bit vague (other than it's description, obviously) as it doesn't give me a file, line, or column to reference, only the project. Also, it throws the error a total of 20 times. I only made three changes to the code between the time I deployed (it was completely functional at that time) and now. I reverted my changes and it is still throwing the same error which makes no sense to me.</p>
<p>I haven't found a lot of information on this error on SO or Google, other than <a href="http://blog.flexforcefive.com/?p=105" rel="noreferrer">this guys</a> solution and a couple references to some Mono project errors (I'm not using Mono). The solution the guy above gives requires adding a class definition that will allow the compiler to resolve the reference. I don't particularly want to do this because I haven't needed to do it up until this point and it will just muddy my code. </p>
<p>Just curious if anyone has run across this before. Thanks in advance!</p> | 6,182,717 | 12 | 1 | null | 2011-05-31 03:09:18.153 UTC | 8 | 2022-08-24 14:09:40.7 UTC | 2011-05-31 03:13:41.963 UTC | null | 76,217 | null | 3,552 | null | 1 | 100 | c#|asp.net-mvc | 76,010 | <p>This error usually means either your project is compiling against .NET 2.0 or you aren't referencing the correct version of System.Core.dll</p>
<p>For a near duplicate question, see <a href="https://stackoverflow.com/questions/205644/error-when-using-extension-methods-in-c">Error when using extension methods in C#</a></p> |
5,800,426 | Expandable list view move group icon indicator to right | <p>As regards to expandable list view, the group icon indicator is positioned to the left side, can I move the indicator and positioned it to the right? Thanks.</p>
<p><strong>EDITED:</strong> Since I don't want to extend the view, I got this workaround of getting the width dynamically. Just sharing my solution.</p>
<p><pre>
Display newDisplay = getWindowManager().getDefaultDisplay();
int width = newDisplay.getWidth();
newListView.setIndicatorBounds(width-50, width);
</pre> | 5,800,630 | 16 | 1 | null | 2011-04-27 06:46:05.907 UTC | 25 | 2020-08-13 12:27:31.227 UTC | 2011-04-27 08:58:30.817 UTC | null | 504,470 | null | 504,470 | null | 1 | 67 | android|expandablelistview|indicator | 78,370 | <p>According to <code>ExpandableListView</code>'s source code, the only way to move an indicator to the right side is to change its bounds using <code>ExpandableListView.setIndicatorBounds()</code> method. You can calculate bound in <code>onSizeChanged()</code> method, for example.</p> |
38,982,637 | regex to match any character or none? | <p>I have the two following peices of strings;</p>
<pre><code>line1 = [16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore
line2 = [16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore
</code></pre>
<p>I'm trying to grab these two parts;</p>
<pre><code>"GET /file/ HTTP/1.1" 302
"" 400
</code></pre>
<p>Basically any character in between the two "" or nothing in between "". So far I've tried this;</p>
<pre><code>regex_example = re.search("\".+?\" [0-9]{3}", line1)
print regex_example.group()
</code></pre>
<p>This will work with line1, but give an error for line2. This is due to the '.' matching any character, but giving an error if no character exists. </p>
<p>Is there any way for it to match any character or nothing in between the two ""?</p> | 38,982,803 | 5 | 1 | null | 2016-08-16 19:05:24.023 UTC | 2 | 2020-04-26 18:02:29.233 UTC | null | null | null | null | 1,165,419 | null | 1 | 9 | python|regex | 81,635 | <p>Use <code>.*?</code> instead of <code>.+?</code>.</p>
<p><code>+</code> means "1 or more"</p>
<p><code>*</code> means "0 or more"</p>
<p><a href="https://regex101.com/r/gU7oT6/2" rel="noreferrer">Regex101 Demo</a></p>
<p>If you want a more efficient regex, use a negated character class <code>[^"]</code> instead of a lazy quantifier <code>?</code>. You should also use the raw string flag <code>r</code> and <code>\d</code> for digits. </p>
<pre><code>r'"[^"]*" \d{3}'
</code></pre> |
44,213,446 | Cannot find setter for field - using Kotlin with Room database | <p>I'm integrating with the Room persistence library. I have a data class in Kotlin like:</p>
<pre><code>@Entity(tableName = "story")
data class Story (
@PrimaryKey val id: Long,
val by: String,
val descendants: Int,
val score: Int,
val time: Long,
val title: String,
val type: String,
val url: String
)
</code></pre>
<p>The <code>@Entity</code> and <code>@PrimaryKey</code> annotations are for the Room library. When I try to build, it is failing with error:</p>
<pre><code>Error:Cannot find setter for field.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
</code></pre>
<p>I also tried providing a default constructor:</p>
<pre><code>@Entity(tableName = "story")
data class Story (
@PrimaryKey val id: Long,
val by: String,
val descendants: Int,
val score: Int,
val time: Long,
val title: String,
val type: String,
val url: String
) {
constructor() : this(0, "", 0, 0, 0, "", "", "")
}
</code></pre>
<p>But this doesn't work as well. A thing to note is that it works if I convert this Kotlin class into a Java class with getters and setters. Any help is appreciated!</p> | 44,213,583 | 20 | 1 | null | 2017-05-27 05:54:18.69 UTC | 16 | 2022-08-16 14:44:47.693 UTC | null | null | null | null | 819,911 | null | 1 | 102 | android|kotlin|android-room | 41,266 | <p>Since your fields are marked with <code>val</code>, they are effectively final and don't have setter fields.</p>
<p>Try switching out the <code>val</code> with <code>var</code>.
You might also need to initialize the fields.</p>
<pre><code>@Entity(tableName = "story")
data class Story (
@PrimaryKey var id: Long? = null,
var by: String = "",
var descendants: Int = 0,
var score: Int = 0,
var time: Long = 0L,
var title: String = "",
var type: String = "",
var url: String = ""
)
</code></pre>
<p><strong>EDIT</strong></p>
<p>The above solution is a general fix for this error in Kotlin when using Kotlin with other Java libraries like Hibernate where i've seen this as well. If you want to keep immutability with Room, see some of the other answers which may be more specific to your case. </p>
<p>In some cases immutability with Java libraries is simply not working at all and while making sad developer noises, you have to switch that <code>val</code> for a <code>var</code> unfortunately.</p> |
25,162,407 | What does <f:facet> do and when should I use it? | <p>I have been having trouble with the tag <code><f:facet></code>. I am working form other examples of code which use it, but I'm not sure exactly what purpose it serves.</p>
<p>I have written some code which in method is exactly the same as other code I have seen which works, except there's is wrapped in a <code><f:facet name=actions></code> tag. When I add this around my code the drop down box I am wrapping it around disappears when I deploy. Anyone able to suggest a reason for this or give me an insight into how and when to use facet?</p>
<p>Here is my code, I won't bother adding the bean code as they're just basic getters and setters and I don't think they're causing the trouble.</p>
<pre><code><f:facet name="actions">
<p:selectOneMenu id="SwitchWeekDrpDwnMenu"
value="#{depotWorkloadBean.selectView}"
partialSubmit="true">
<p:ajax update="mainForm"
listener="#{depotWorkloadBean.updateView}" />
<f:selectItem itemLabel="Day view" itemValue="Day"/>
<f:selectItem itemLabel="01/01/2014" itemValue="Week"/>
</p:selectOneMenu>
</f:facet>
</code></pre>
<p>If I remove the facet tag the dropdown box displays, but doesn't function as it should with the beans.</p> | 34,710,052 | 1 | 1 | null | 2014-08-06 14:00:35.2 UTC | 11 | 2020-11-09 08:02:25.23 UTC | 2016-01-08 08:04:56.577 UTC | null | 3,885,376 | null | 3,560,123 | null | 1 | 56 | jsf|primefaces|xhtml|facet | 71,164 | <blockquote>
<p>A facet represents a named section within a container component. For example, you can create a header and a footer facet for a dataTable component.
<a href="https://web.archive.org/web/20170828020413/http://www.jsftoolbox.com/documentation/help/12-TagReference/core/f_facet.html" rel="nofollow noreferrer">https://web.archive.org/web/20170828020413/http://www.jsftoolbox.com/documentation/help/12-TagReference/core/f_facet.html</a></p>
</blockquote>
<p>It's useful when you want to create component that uses some code from user (let's say wrapper).</p>
<p>ie. when you want to create component that hides long text and shows short version of it. You can use just the element body, but then you will get only one value, if you want to get from user the short AND the long version then you can not do it in one value (without using some discriminant), just use facet and say which one is the long and which is the short version.</p>
<pre><code><textShortener>
<f:facet name="short">
This text is short.
</f:facet>
<f:facet name="long">
This text is too <b>long</b> to be showed when page loads. User have to click the button after the short text to show this.
</f:facet>
</textShortener>
</code></pre>
<p>Yes, this can (and should) be done with jsf templating, but I hope you got it.</p>
<p>To question: you defined facet just in the wild xml, nobody requested it so nobody processed it - that's why it did not throw error nor showed anything.</p> |
24,581,873 | What exactly is Hot Module Replacement in Webpack? | <p>I've read a <a href="https://webpack.js.org/guides/hot-module-replacement/" rel="nofollow noreferrer">few</a> <a href="https://webpack.js.org/concepts/hot-module-replacement/" rel="nofollow noreferrer">pages</a> about Hot Module Replacement in Webpack.<br />
There's even a <a href="http://webpack.github.io/example-app/" rel="nofollow noreferrer">sample app</a> that <a href="https://github.com/webpack/example-app/commit/a1b50cc3d2aa5c1e77d7ead12589698f958319ec" rel="nofollow noreferrer">uses it</a>.</p>
<p>I've read all of this and still don't get the idea.</p>
<p>What can I do with it?</p>
<ol>
<li>Is it supposed to only be used in development and not in production?</li>
<li>Is it like LiveReload, but you have to manage it yourself?</li>
<li>Is WebpackDevServer integrated with LiveReload in some way?</li>
</ol>
<p>Suppose I want to update my CSS (one stylesheet) and JS modules when I save them to disk, without reloading the page and without using plugins such as LiveReload. Is this something Hot Module Replacement can help me with? What kind of work do I need to do, and what does HMR already provide?</p> | 24,587,740 | 2 | 1 | null | 2014-07-05 00:13:56.067 UTC | 206 | 2022-07-28 13:12:55.783 UTC | 2022-07-28 13:12:55.783 UTC | null | 3,955,557 | null | 458,193 | null | 1 | 299 | javascript|module|livereload|webpack | 62,141 | <p><em>First I want to note that Hot Module Replacement (HMR) is still an experimental feature.</em></p>
<p>HMR is a way of exchanging modules in a running application (and adding/removing modules). You basically can update changed modules without a full page reload.</p>
<h2>Documentation</h2>
<p>Prerequirements:</p>
<ul>
<li>Using Plugins: <a href="https://webpack.js.org/concepts/plugins/" rel="nofollow noreferrer">https://webpack.js.org/concepts/plugins/</a></li>
<li>Code Splitting: <a href="https://webpack.js.org/guides/code-splitting/" rel="nofollow noreferrer">https://webpack.js.org/guides/code-splitting/</a></li>
<li>webpack-dev-server: <a href="https://webpack.js.org/configuration/dev-server/" rel="nofollow noreferrer">https://webpack.js.org/configuration/dev-server/</a></li>
</ul>
<p>It's not so much for HMR, but here are the links:</p>
<ul>
<li>Example: <a href="https://webpack.js.org/guides/hot-module-replacement/" rel="nofollow noreferrer">https://webpack.js.org/guides/hot-module-replacement/</a></li>
<li>API: <a href="https://webpack.js.org/concepts/hot-module-replacement/" rel="nofollow noreferrer">https://webpack.js.org/concepts/hot-module-replacement/</a></li>
</ul>
<p>I'll add these answers to the documentation.</p>
<h2>How does it work?</h2>
<h3>From the app view</h3>
<p>The app code asks the HMR runtime to check for updates. The HMR runtime downloads the updates (async) and tells the app code that an update is available. The app code asks the HMR runtime to apply updates. The HMR runtime applies the updates (sync). The app code may or may not require user interaction in this process (you decide).</p>
<h3>From the compiler (webpack) view</h3>
<p>In addition to the normal assets, the compiler needs to emit the "Update" to allow updating from a previous version to this version. The "Update" contains two parts:</p>
<ol>
<li>the update manifest (json)</li>
<li>one or multiple update chunks (js)</li>
</ol>
<p>The manifest contains the new compilation hash and a list of all update chunks (2).</p>
<p>The update chunks contain code for all updated modules in this chunk (or a flag if a module was removed).</p>
<p>The compiler additionally makes sure that module and chunk ids are consistent between these builds. It uses a "records" json file to store them between builds (or it stores them in memory).</p>
<h3>From the module view</h3>
<p>HMR is an opt-in feature, so it only affects modules that contains HMR code. The documentation describes the API that is available in modules. In general, the module developer writes handlers that are called when a dependency of this module is updated. They can also write a handler that is called when this module is updated.</p>
<p>In most cases, it's not mandatory to write HMR code in every module. If a module has no HMR handlers, the update bubbles up. This means a single handler can handle updates for a complete module tree. If a single module in this tree is updated, the complete module tree is reloaded (only reloaded, not transferred).</p>
<h3>From the HMR runtime view (technical)</h3>
<p>Additional code is emitted for the module system runtime to track module <code>parents</code> and <code>children</code>.</p>
<p>On the management side, the runtime supports two methods: <code>check</code> and <code>apply</code>.</p>
<p>A <code>check</code> does a HTTP request to the update manifest. When this request fails, there is no update available. Elsewise the list of updated chunks is compared to the list of currently-loaded chunks. For each loaded chunk, the corresponding update chunk is downloaded. All module updates are stored in the runtime as updates. The runtime switches into the <code>ready</code> state, meaning an update has been downloaded and is ready to be applied.</p>
<p>For each new chunk request in the ready state, the update chunk is also downloaded.</p>
<p>The <code>apply</code> method flags all updated modules as invalid. For each invalid module, there needs to be an update handler in the module or update handlers in every parent. Else the invalid bubbles up and marks all parents as invalid too. This process continues until no more "bubble up" occurs. If it bubbles up to an entry point, the process fails.</p>
<p>Now all invalid modules are disposed (dispose handler) and unloaded. Then the current hash is updated and all "accept" handlers are called. The runtime switches back to the <code>idle</code> state and everything continues as normal.</p>
<p><a href="https://i.stack.imgur.com/sPpGk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sPpGk.png" alt="generated update chunks" /></a></p>
<h2>What can I do with it?</h2>
<p>You can use it in development as a LiveReload replacement. Actually the webpack-dev-server supports a hot mode which tries to update with HMR before trying to reload the whole page. You only need to add the <code>webpack/hot/dev-server</code> entry point and call the dev-server with <code>--hot</code>.</p>
<p>You can also use it in production as update mechanisms. Here you need to write your own management code that integrates HMR with your app.</p>
<p>Some loaders already generate modules that are hot-updateable. e.g. The <code>style-loader</code> can exchange the stylesheet. You don't need to do anything special.</p>
<blockquote>
<p>Suppose I want to update my CSS (one stylesheet) and JS modules when I save them to disk, without reloading the page and without using plugins such as LiveReload. Is this something Hot Module Replacement can help me with?</p>
</blockquote>
<p>Yes</p>
<blockquote>
<p>What kind of work do I need to do, and what does HMR already provide?</p>
</blockquote>
<p>Here is a little example: <a href="https://webpack.js.org/guides/hot-module-replacement/" rel="nofollow noreferrer">https://webpack.js.org/guides/hot-module-replacement/</a></p>
<p>A module can only be updated if you "accept" it. So you need to <code>module.hot.accept</code> the module in the parents or the parents of the parents... e.g. A Router is a good place, or a subview.</p>
<p>If you only want to use it with the webpack-dev-server, just add <code>webpack/hot/dev-server</code> as entry point. Else you need some HMR management code that calls <code>check</code> and <code>apply</code>.</p>
<h2>Opinion: What makes it so cool?</h2>
<ul>
<li>It's LiveReload but for every module kind.</li>
<li>You can use it in production.</li>
<li>The updates respect your Code Splitting and only download updates for the used parts of your app.</li>
<li>You can use it for a part of your application and it doesn't affect other modules</li>
<li>If HMR is disabled, all HMR code is removed by the compiler (wrap it in <code>if(module.hot)</code>).</li>
</ul>
<h2>Caveats</h2>
<ul>
<li>It's experimental and not tested so well.</li>
<li>Expect some bugs.</li>
<li>Theoretically usable in production, but it may be too early to use it for something serious.</li>
<li>The module IDs need to be tracked between compilations so you need to store them (<code>records</code>).</li>
<li>The optimizer cannot optimize module IDs any more after the first compilation. A bit of an impact on bundle size.</li>
<li>HMR runtime code increases the bundle size.</li>
<li>For production usage, additional testing is required to test the HMR handlers. This could be pretty difficult.</li>
</ul> |
71,191,685 | visit_Psych_Nodes_Alias: Unknown alias: default (Psych::BadAlias) | <p>I updated from ruby 2.7.1 to 3.1.1, then removed Gemfile.lock and ran <code>bundle update</code> (it's on a dev branch, so I can throw it away if this is a bad idea, I just wanted to see if it would work).</p>
<p><code>bundle update</code> succeeds, but when I start the server:</p>
<pre><code>rails s
=> Booting Puma
=> Rails 7.0.2.2 application starting in development
=> Run `bin/rails server --help` for more startup options
Exiting
/Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:430:in `visit_Psych_Nodes_Alias': Unknown alias: default (Psych::BadAlias)
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/visitor.rb:30:in `visit'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/visitor.rb:6:in `accept'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:35:in `accept'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:345:in `block in revive_hash'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:343:in `each'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:343:in `each_slice'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:343:in `revive_hash'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:167:in `visit_Psych_Nodes_Mapping'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/visitor.rb:30:in `visit'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/visitor.rb:6:in `accept'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:35:in `accept'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:345:in `block in revive_hash'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:343:in `each'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:343:in `each_slice'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:343:in `revive_hash'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:167:in `visit_Psych_Nodes_Mapping'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/visitor.rb:30:in `visit'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/visitor.rb:6:in `accept'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:35:in `accept'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:318:in `visit_Psych_Nodes_Document'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/visitor.rb:30:in `visit'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/visitor.rb:6:in `accept'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych/visitors/to_ruby.rb:35:in `accept'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych.rb:335:in `safe_load'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/psych.rb:370:in `load'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/webpacker-4.3.0/lib/webpacker/env.rb:30:in `available_environments'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/webpacker-4.3.0/lib/webpacker/env.rb:21:in `current'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/webpacker-4.3.0/lib/webpacker/env.rb:15:in `inquire'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/webpacker-4.3.0/lib/webpacker/env.rb:7:in `inquire'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/webpacker-4.3.0/lib/webpacker/instance.rb:11:in `env'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/webpacker-4.3.0/lib/webpacker/instance.rb:18:in `config'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/webpacker-4.3.0/lib/webpacker.rb:34:in `config'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/webpacker-4.3.0/lib/webpacker/railtie.rb:32:in `block in <class:Engine>'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/initializable.rb:32:in `instance_exec'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/initializable.rb:32:in `run'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/initializable.rb:61:in `block in run_initializers'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/tsort.rb:228:in `block in tsort_each'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/tsort.rb:431:in `each_strongly_connected_component_from'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/tsort.rb:349:in `block in each_strongly_connected_component'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/tsort.rb:347:in `each'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/tsort.rb:347:in `call'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/tsort.rb:347:in `each_strongly_connected_component'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/tsort.rb:226:in `tsort_each'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/3.1.0/tsort.rb:205:in `tsort_each'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/initializable.rb:60:in `run_initializers'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/application.rb:372:in `initialize!'
from /Users/st/rails/hangswith/config/environment.rb:5:in `<main>'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/bootsnap-1.10.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/bootsnap-1.10.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/zeitwerk-2.5.4/lib/zeitwerk/kernel.rb:35:in `require'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/bootsnap-1.10.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:42:in `require_relative'
from config.ru:3:in `block in <main>'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/rack-2.2.3/lib/rack/builder.rb:116:in `eval'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/rack-2.2.3/lib/rack/builder.rb:116:in `new_from_string'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/rack-2.2.3/lib/rack/builder.rb:105:in `load_file'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/rack-2.2.3/lib/rack/builder.rb:66:in `parse_file'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/rack-2.2.3/lib/rack/server.rb:349:in `build_app_and_options_from_config'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/rack-2.2.3/lib/rack/server.rb:249:in `app'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/rack-2.2.3/lib/rack/server.rb:422:in `wrapped_app'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/commands/server/server_command.rb:76:in `log_to_stdout'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/commands/server/server_command.rb:36:in `start'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/commands/server/server_command.rb:143:in `block in perform'
from <internal:kernel>:90:in `tap'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/commands/server/server_command.rb:134:in `perform'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/thor-1.2.1/lib/thor/command.rb:27:in `run'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/thor-1.2.1/lib/thor/invocation.rb:127:in `invoke_command'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/thor-1.2.1/lib/thor.rb:392:in `dispatch'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/command/base.rb:87:in `perform'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/command.rb:48:in `invoke'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/railties-7.0.2.2/lib/rails/commands.rb:18:in `<main>'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/bootsnap-1.10.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
from /Users/st/.rbenv/versions/3.1.1/lib/ruby/gems/3.1.0/gems/bootsnap-1.10.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
from bin/rails:4:in `<main>'
</code></pre>
<h3>What I've tried</h3>
<p>Googling the 'psych' error message reveals <a href="https://stackoverflow.com/q/22664614/5783745">this</a> which may be related. But when I search the entire app for <code>YAML.safe_load</code> (or even just <code>safe_load</code>), there are 0 occurrences of it. (perhaps I should be searching actual gems in my app?).</p>
<p>It was a long shot but based on <a href="https://github.com/ruby/psych/issues/533#issuecomment-1034067033" rel="noreferrer">this</a> comment, I <a href="https://stackoverflow.com/a/3917878/5783745">ran <code>gem rdoc --all</code></a> to update all rdoc documentation. But that didn't help.</p> | 71,192,990 | 4 | 0 | null | 2022-02-20 05:50:19.613 UTC | 5 | 2022-09-12 07:32:45.997 UTC | 2022-06-19 13:16:34.383 UTC | null | 74,089 | null | 5,783,745 | null | 1 | 41 | ruby-on-rails|ruby | 10,725 | <p>The problem is related to the Ruby 3.1 / Psych 4.x incompatibility described in this issue: <a href="https://bugs.ruby-lang.org/issues/17866" rel="noreferrer">https://bugs.ruby-lang.org/issues/17866</a></p>
<p>Ruby 3.0 comes with Psych 3, while Ruby 3.1 comes with Psych 4, which has a major breaking change (<a href="https://my.diffend.io/gems/psych/3.3.2/4.0.0" rel="noreferrer">diff 3.3.2 → 4.0.0</a>).</p>
<ul>
<li>The new YAML loading methods (Psych 4) do not load aliases unless they get the <code>aliases: true</code> argument.</li>
<li>The old YAML loading methods (Psych 3) do not support the <code>aliases</code> keyword.</li>
</ul>
<p>At this point, it seems like anyone, anywhere that wants to load YAML in the same way it worked prior to Ruby 3.1, need to do something like this:</p>
<pre class="lang-rb prettyprint-override"><code>begin
YAML.load(source, aliases: true, **options)
rescue ArgumentError
YAML.load(source, **options)
end
</code></pre>
<p><a href="https://github.com/rails/rails/commit/179d0a1f474ada02e0030ac3bd062fc653765dbe" rel="noreferrer">as patched by the Rails team</a>.</p>
<p>In your case, I suspect you will need to see which Rails version that matches your major version preference includes this patch before you can upgrade to Ruby 3.1.</p>
<p>Personally, wherever I have control of the code that loads YAML, I am adding an extension like this:</p>
<pre class="lang-rb prettyprint-override"><code>module YAML
def self.properly_load_file(path)
YAML.load_file path, aliases: true
rescue ArgumentError
YAML.load_file path
end
end
</code></pre>
<p>or, if I want to completely revert this change done in Psych 4, I add this to my code:</p>
<pre class="lang-rb prettyprint-override"><code>module YAML
class << self
alias_method :load, :unsafe_load if YAML.respond_to? :unsafe_load
end
end
</code></pre>
<p>This has the advantage of restoring <code>YAML::load</code>, and <code>YAML::load_file</code> (which uses it) to their original glory, and solves everything including libraries that you have no control of, in all Ruby versions.</p>
<p>Lastly, as I mentioned in the comments, in case you prefer a minimally invasive stopgap measure, you might be able to get away with pinning Psych to <code>< 4</code> in your Gemfile:</p>
<pre class="lang-rb prettyprint-override"><code>gem 'psych', '< 4'
</code></pre>
<h3>Note for Rails users (>= 7.0.3.1)</h3>
<p>ActiveRecord 7.0.3.1 <a href="https://github.com/rails/rails/commit/611990f1a6c137c2d56b1ba06b27e5d2434dcd6a" rel="noreferrer">changed an internal call</a> and it now calls <code>safe_load</code> directly. If you see a Psych related error during rails tests, you might be affected by this change.</p>
<p>To resolve it, you can add this to a new or existing initializer:</p>
<pre class="lang-rb prettyprint-override"><code># config/initializers/activerecord_yaml.rb
ActiveRecord.use_yaml_unsafe_load = true
</code></pre>
<p>You may also use <code>ActiveRecord.yaml_column_permitted_classes</code> to configure the allowed classes instead.</p>
<p>More info in <a href="https://discuss.rubyonrails.org/t/cve-2022-32224-possible-rce-escalation-bug-with-serialized-columns-in-active-record/81017" rel="noreferrer">this post</a>.</p> |
33,517,624 | Java 8 - chaining constructor call and setter in stream.map() | <p>I have a class</p>
<pre><code>class Foo{
String name;
// setter, getter
}
</code></pre>
<p>which just has a default constructor.</p>
<p>Then, I am trying to create a List of <code>Foo</code> from some string:</p>
<pre><code>Arrays.stream(fooString.split(","))
.map(name -> {
Foo x = new Foo();
x.setName(name);
return x;
}).collect(Collectors.toList()));
</code></pre>
<p>Since there is no constructor which takes a name, I can't simply use a method reference. Of course, I could extract those three lines, with the constructor call and the setter, into a method but is there any better or concise way to do that? (without changing <code>Foo</code>, which is a generated file)</p> | 33,518,219 | 5 | 1 | null | 2015-11-04 09:03:55.627 UTC | 3 | 2016-05-10 11:18:23.813 UTC | 2016-05-10 11:18:23.813 UTC | null | 2,711,488 | null | 4,945,535 | null | 1 | 35 | java|lambda|java-8|java-stream | 29,417 | <p>If this happens repeatedly, you may create a generic utility method handling the problem of constructing an object given one property value:</p>
<pre><code>public static <T,V> Function<V,T> create(
Supplier<? extends T> constructor, BiConsumer<? super T, ? super V> setter) {
return v -> {
T t=constructor.get();
setter.accept(t, v);
return t;
};
}
</code></pre>
<p>Then you may use it like:</p>
<pre><code>List<Foo> l = Arrays.stream(fooString.split(","))
.map(create(Foo::new, Foo::setName)).collect(Collectors.toList());
</code></pre>
<p>Note how this isn’t specific to <code>Foo</code> nor its <code>setName</code> method:</p>
<pre><code>List<List<String>> l = Arrays.stream(fooString.split(","))
.map(create(ArrayList<String>::new, List::add)).collect(Collectors.toList());
</code></pre>
<hr>
<p>By the way, if <code>fooString</code> gets very large and/or may contain lots of elements (after splitting), it might be more efficient to use <code>Pattern.compile(",").splitAsStream(fooString)</code> instead of <code>Arrays.stream(fooString.split(","))</code>.</p> |
9,110,803 | Make custom page-based loop in Jekyll | <p>I would like to create another page-based loop, in the same way the <code>_posts</code> folder works for the blog section, but for a small catalogue of magazines. (Hopefully that makes sense)</p>
<p>Maybe i'm misunderstanding something simple, but I just can't work it out.
I have this loop, which feels like it should work, but nothing gets returned.</p>
<pre><code>{% for page in site.pressitems %}
<li>
<a href="{{ post.url }}">{{ page.title }}</a>
</li>
{% endfor %}
</code></pre>
<p>Code, links, explanation, anything is greatly appreciated. :)</p> | 9,117,390 | 4 | 0 | null | 2012-02-02 10:33:26.99 UTC | 10 | 2020-01-17 12:40:22.36 UTC | 2012-02-02 16:20:12.16 UTC | null | 334,479 | null | 334,479 | null | 1 | 16 | jekyll|liquid | 11,687 | <p>You can't add your own collection to <code>site</code> just like that.</p>
<p><code>site</code> only knows about three collections: <code>pages</code>, <code>posts</code>, and <code>categories</code>. You can get all the posts of a category by doing <code>site.<category>.posts</code> . AFAIK, categories only work for posts, not pages.</p>
<p>This makes sense, since Jekyll is supposed to be mainly a blogging engine, and not a generic static website generator.</p>
<p>So your best solution right now consists on "lying" to jekyll. Make it believe you have posts, when in reality you are making pages.</p>
<pre><code>_posts/
pressitems/
blog/
</code></pre>
<p>You will be able to loop over the elements inside _posts/pressitems like this:</p>
<pre><code>for item in site.categories.pressitems.posts do
... {{ item.title }} ... {{ item.url }}
endfor
</code></pre>
<p>Similarly, your "real blog entries" would go this way:</p>
<pre><code>for p in site.categories.blog.posts do
... {{ p.title }} ... {{ p.url }}
endfor
</code></pre>
<p>The catch is that you will have to respect Jekyll's naming convention regarding filenames; your pressitems have to look like real posts. This means they have to be named starting with a yyyy-mm-dd- string, like posts. Just give them a random date.</p>
<pre><code>_posts/
pressitems/
1901-01-01-the-first-press-item.textile
1902-01-01-the-second-one.textile
</code></pre>
<p>EDIT: This was true when this post was originally written, in 2012, but not any more. Modern Jekyll does allow you to create your own collections <a href="https://jekyllrb.com/docs/collections/" rel="noreferrer">https://jekyllrb.com/docs/collections/</a></p> |
9,391,845 | Why doesn't Python evaluate constant number arithmetic before compiling to bytecode? | <p>In the following code, why doesn't Python compile <code>f2</code> to the same bytecode as <code>f1</code>?</p>
<p>Is there a reason not to?</p>
<pre><code>>>> def f1(x):
x*100
>>> dis.dis(f1)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (100)
6 BINARY_MULTIPLY
7 POP_TOP
8 LOAD_CONST 0 (None)
11 RETURN_VALUE
>>> def f2(x):
x*10*10
>>> dis.dis(f2)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (10)
6 BINARY_MULTIPLY
7 LOAD_CONST 1 (10)
10 BINARY_MULTIPLY
11 POP_TOP
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
</code></pre> | 9,392,000 | 2 | 0 | null | 2012-02-22 09:07:41.407 UTC | 7 | 2012-02-22 19:43:40.81 UTC | 2012-02-22 19:43:40.81 UTC | null | 63,550 | null | 348,545 | null | 1 | 44 | python|bytecode | 1,408 | <p>This is because <code>x</code> could have a <code>__mul__</code> method with side-effects. <code>x * 10 * 10</code> calls <code>__mul__</code> twice, while <code>x * 100</code> only calls it once:</p>
<pre><code>>>> class Foo(object):
... def __init__ (self):
... self.val = 5
... def __mul__ (self, other):
... print "Called __mul__: %s" % (other)
... self.val = self.val * other
... return self
...
>>> a = Foo()
>>> a * 10 * 10
Called __mul__: 10
Called __mul__: 10
<__main__.Foo object at 0x1017c4990>
</code></pre>
<p>Automatically folding the constants and only calling <code>__mul__</code> once could change behavior.</p>
<p>You can get the optimization you want by reordering the operation such that the constants are multiplied first (or, as mentioned in the comments, using parentheses to group them such that they are merely operated on together, regardless of position), thus making explicit your desire for the folding to happen:</p>
<pre><code>>>> def f1(x):
... return 10 * 10 * x
...
>>> dis.dis(f1)
2 0 LOAD_CONST 2 (100)
3 LOAD_FAST 0 (x)
6 BINARY_MULTIPLY
7 RETURN_VALUE
</code></pre> |
9,394,338 | How do RVM and rbenv actually work? | <p>I am interested in how RVM and rbenv actually work.</p>
<p>Obviously they swap between different versions of Ruby and gemsets, but how is this achieved? I had assumed they were simply updating symlinks, but having delved into the code (and I must admit my knowledge of Bash is superficial) they appear to be doing more than this.</p> | 9,422,296 | 5 | 0 | null | 2012-02-22 12:00:02.263 UTC | 73 | 2016-03-03 17:35:12.303 UTC | 2016-03-03 17:35:12.303 UTC | null | 128,421 | null | 687,677 | null | 1 | 145 | ruby-on-rails|ruby|rubygems|rvm|rbenv | 25,611 | <p>Short explanation: rbenv works by hooking into your environment's <code>PATH</code>. The concept is simple, but the devil is in the details; full scoop below.</p>
<p>First, rbenv creates <em>shims</em> for all the commands (<code>ruby</code>, <code>irb</code>, <code>rake</code>, <code>gem</code> and so on) across all your installed versions of Ruby. This process is called <em>rehashing</em>. Every time you install a new version of Ruby or install a gem that provides a command, run <code>rbenv rehash</code> to make sure any new commands are shimmed.</p>
<p>These shims live in a single directory (<code>~/.rbenv/shims</code> by default). To use rbenv, you need only add the shims directory to the front of your <code>PATH</code>:</p>
<pre><code>export PATH="$HOME/.rbenv/shims:$PATH"
</code></pre>
<p>Then any time you run <code>ruby</code> from the command line, or run a script whose shebang reads <code>#!/usr/bin/env ruby</code>, your operating system will find <code>~/.rbenv/shims/ruby</code> first and run it instead of any other <code>ruby</code> executable you may have installed.</p>
<p>Each shim is a tiny Bash script that in turn runs <code>rbenv exec</code>. So with rbenv in your path, <code>irb</code> is equivalent to <code>rbenv exec irb</code>, and <code>ruby -e "puts 42"</code> is equivalent to <code>rbenv exec ruby -e "puts 42"</code>.</p>
<p>The <code>rbenv exec</code> command figures out what version of Ruby you want to use, then runs the corresponding command for that version. Here's how:</p>
<ol>
<li>If the <code>RBENV_VERSION</code> environment variable is set, its value determines the version of Ruby to use.</li>
<li>If the current working directory has an <code>.rbenv-version</code> file, its contents are used to set the <code>RBENV_VERSION</code> environment variable.</li>
<li>If there is no <code>.rbenv-version</code> file in the current directory, rbenv searches each parent directory for an <code>.rbenv-version</code> file until it hits the root of your filesystem. If one is found, its contents are used to set the <code>RBENV_VERSION</code> environment variable.</li>
<li>If <code>RBENV_VERSION</code> is still not set, rbenv tries to set it using the contents of the <code>~/.rbenv/version</code> file.</li>
<li>If no version is specified anywhere, rbenv assumes you want to use the "system" Ruby—i.e. whatever version would be run if rbenv weren't in your path.</li>
</ol>
<p>(You can set a project-specific Ruby version with the <code>rbenv local</code> command, which creates a <code>.rbenv-version</code> file in the current directory. Similarly, the <code>rbenv global</code> command modifies the <code>~/.rbenv/version</code> file.)</p>
<p>Armed with an <code>RBENV_VERSION</code> environment variable, rbenv adds <code>~/.rbenv/versions/$RBENV_VERSION/bin</code> to the front of your <code>PATH</code>, then execs the command and arguments passed to <code>rbenv exec</code>. Voila!</p>
<p>For a thorough look at exactly what happens under the hood, try setting <code>RBENV_DEBUG=1</code> and running a Ruby command. Every Bash command that rbenv runs will be written to your terminal.</p>
<hr>
<p>Now, rbenv is just concerned with switching versions, but a thriving ecosystem of plugins will help you do everything from <a href="https://github.com/sstephenson/ruby-build" rel="noreferrer">installing Ruby</a> to <a href="https://github.com/sstephenson/rbenv-vars" rel="noreferrer">setting up your environment</a>, <a href="https://github.com/jamis/rbenv-gemset" rel="noreferrer">managing "gemsets"</a> and even <a href="https://github.com/carsomyr/rbenv-bundler" rel="noreferrer">automating <code>bundle exec</code></a>.</p>
<p>I am not quite sure what IRC support has to do with switching Ruby versions, and rbenv is designed to be simple and understandable enough not to require support. But should you ever need help, the issue tracker and Twitter are just a couple of clicks away.</p>
<p><em>Disclosure: I am the author of rbenv, ruby-build, and rbenv-vars.</em></p> |
10,301,589 | How do you add multiple tuples(lists, whatever) to a single dictionary key without merging them? | <p>I've been trying to figure out how to add multiple tuples that contain multiple values to to a single key in a dictionary. But with no success so far. I can add the values to a tuple or list, but I can't figure out how to add a tuple so that the key will now have 2 tuples containing values, as opposed to one tuple with all of them.</p>
<p>For instance say the dictionary = <code>{'Key1':(1.000,2.003,3.0029)}</code></p>
<p>and I want to add <code>(2.3232,13.5232,1325.123)</code> so that I end up with:</p>
<p>dictionary = <code>{'Key1':((1.000,2.003,3.0029),(2.3232,13.5232,1325.123))}</code> (forgot a set of brackets!)</p>
<p>If someone knows how this can be done I'd appreciate the help as it's really starting to annoy me now.</p>
<p>Thanks!</p>
<p>Edit: Thanks everyone! Ironic that I tried that except at the time I was trying to make the value multiple lists instead of multiple tuples; when the solution was to just enclose the tuples in a list. Ah the irony.</p> | 10,301,630 | 6 | 1 | null | 2012-04-24 15:58:51.53 UTC | 2 | 2016-02-22 05:17:16.373 UTC | 2012-04-24 16:54:56.683 UTC | null | 1,340,527 | null | 1,340,527 | null | 1 | 4 | python|list|dictionary|tuples | 51,016 | <p>Just map your key to a list, and append tuples to the list.</p>
<pre><code>d = {'Key1': [(1.000,2.003,3.0029)]}
</code></pre>
<p>Then later..</p>
<pre><code>d['Key1'].append((2.3232,13.5232,1325.123))
</code></pre>
<p>Now you have:</p>
<pre><code>{'Key1': [(1.0, 2.003, 3.0029), (2.3232, 13.5232, 1325.123)]}
</code></pre> |
7,156,228 | Reading a XLSX sheet to feed a MySQL table using PHPExcel | <p>I found the PHPExcel library brilliant to manipulate Excel files with PHP (read, write, and so on).</p>
<p>But nowhere in the documentation is explained <strong>how to read a XLSX worksheet to feed a MySQL table</strong>...</p>
<p>Sorry for this silly question, but i need it for my work and found no answer on the web.</p>
<p>A small example could be very helpful.</p>
<p>Thanks a lot.</p>
<p><strong>UPDATED :</strong></p>
<p>I precise my question :</p>
<p>The only part of code i found in the documentation that could help me is to read an Excel file and display it in a HTML table :</p>
<pre><code>`require_once 'phpexcel/Classes/PHPExcel.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("edf/equipement.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<table border="1">' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";`
</code></pre>
<p>I know i can use the loop to feed my MySQL table, but i don't know how... I'm not aware in OOP...</p>
<p>Can somebody help me, please ?</p> | 7,286,159 | 2 | 1 | null | 2011-08-23 04:21:16.757 UTC | 3 | 2011-11-08 20:20:42.893 UTC | 2011-08-23 18:16:41.973 UTC | null | 707,572 | null | 707,572 | null | 1 | 19 | mysql|phpexcel | 49,529 | <p>The first <code>for</code> loops through rows, and the second one loops through columns.
So, there are plenty of solutions to your "problem".</p>
<p>You could, for example, populate an array and make an insert statement for each row.
As the following :</p>
<pre><code>$rows = array();
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$rows[$col] = mysql_real_espace_string($objWorksheet->getCellByColumnAndRow($col, $row)->getValue());
}
mysql_query("INSERT INTO your_table (col1,col2) VALUES ($rows[1],$rows[2])");
}
</code></pre>
<p>Obviously, this code can be improved.</p> |
23,361,883 | Angular js - detect when all $http() have finished | <p>Ok i have tons of <code>$http()</code> calls all around the app code,</p>
<p>i'm wondering is there any way / best practice to detect when all <code>$http()</code> around the app have finished ( success/error donesn't matter what they return, just need to know if finished )?</p>
<p>So that i can show a loading gif until they are loading ?</p>
<p>thanks</p> | 23,362,321 | 3 | 1 | null | 2014-04-29 10:19:55.753 UTC | 19 | 2016-02-11 14:55:02.037 UTC | null | null | null | null | 895,174 | null | 1 | 26 | javascript|angularjs|http|detect|activity-finish | 22,811 | <p>Do it like this:</p>
<pre><code>angular.module('app').factory('httpInterceptor', ['$q', '$rootScope',
function ($q, $rootScope) {
var loadingCount = 0;
return {
request: function (config) {
if(++loadingCount === 1) $rootScope.$broadcast('loading:progress');
return config || $q.when(config);
},
response: function (response) {
if(--loadingCount === 0) $rootScope.$broadcast('loading:finish');
return response || $q.when(response);
},
responseError: function (response) {
if(--loadingCount === 0) $rootScope.$broadcast('loading:finish');
return $q.reject(response);
}
};
}
]).config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}]);
</code></pre>
<p>Then use event bound to <code>$rootScope</code> anywhere (preferable to use in directive):</p>
<pre><code>$rootScope.$on('loading:progress', function (){
// show loading gif
});
$rootScope.$on('loading:finish', function (){
// hide loading gif
});
</code></pre> |
23,230,569 | How do you create a file from a string in Gulp? | <p>In my gulpfile I have a version number in a string. I'd like to write the version number to a file. Is there a nice way to do this in Gulp, or should I be looking at more general NodeJS APIs?</p> | 23,398,200 | 9 | 1 | null | 2014-04-22 21:29:31.8 UTC | 21 | 2021-06-16 15:15:17.227 UTC | null | null | null | null | 24,158 | null | 1 | 77 | node.js|gulp | 63,526 | <p>If you'd like to do this in a gulp-like way, you can create a stream of "fake" vinyl files and call <code>pipe</code> per usual. Here's a function for creating the stream. "stream" is a core module, so you don't need to install anything:</p>
<pre><code>const Vinyl = require('vinyl')
function string_src(filename, string) {
var src = require('stream').Readable({ objectMode: true })
src._read = function () {
this.push(new Vinyl({
cwd: "",
base: "",
path: filename,
contents: Buffer.from(string, 'utf-8')
}))
this.push(null)
}
return src
}
</code></pre>
<p>You can use it like this:</p>
<pre><code>gulp.task('version', function () {
var pkg = require('package.json')
return string_src("version", pkg.version)
.pipe(gulp.dest('build/'))
})
</code></pre> |
19,089,337 | chosen with bootstrap 3 not working properly | <p>I have this code which triggers a bootstrap modal and load its content via <code>$.load()</code>. the page I'm loading has a select element which I'm calling chosen on.
Here's the code:</p>
<pre><code>$('.someClick').click(function(e){
e.preventDefault();
x.modal('show');
x.find('.modal-body').load('path/page.html',
function(response, status, xhr){
if(status =="success")
$("select[name=elementName]").chosen();
});
});
</code></pre>
<p>the results I'm getting is like the following image:</p>
<p><img src="https://i.stack.imgur.com/sJvKm.png" alt="Modal View"></p>
<p>and this is my Html content:</p>
<pre><code> <select name="elementName" data-placeholder="Please work.." class="chosen-select">
<option value="test">Hi</option>
<option value="test2">bye</option>
</select>
</code></pre> | 19,126,596 | 6 | 2 | null | 2013-09-30 08:10:46.317 UTC | 11 | 2017-10-23 22:33:38.347 UTC | 2014-02-01 13:20:31.053 UTC | null | 569,101 | null | 1,567,581 | null | 1 | 34 | jquery|twitter-bootstrap|jquery-chosen | 26,113 | <p><strong>Applying Chosen after the modal is shown should solve your problem:</strong></p>
<pre><code>$('#myModal').on('shown.bs.modal', function () {
$('.chosen-select', this).chosen();
});
</code></pre>
<p><strong>Or when Chosen was already applied, destroy and reapply:</strong></p>
<pre><code>$('#myModal').on('shown.bs.modal', function () {
$('.chosen-select', this).chosen('destroy').chosen();
});
</code></pre>
<p>Fiddle here: <a href="http://jsfiddle.net/koenpunt/W6dZV/">http://jsfiddle.net/koenpunt/W6dZV/</a></p>
<p><strong>So in your case it would probably something like:</strong></p>
<pre><code>$('.someClick').click(function(e){
e.preventDefault();
x.modal('show');
x.on('shown.bs.modal', function(){
x.find('.modal-body').load('path/page.html', function(response, status, xhr){
if(status == "success"){
$("select[name=elementName]").chosen();
}
});
});
});
</code></pre>
<hr>
<p><strong>EDIT</strong></p>
<p>To complement Chosen you can use the <a href="https://gist.github.com/koenpunt/6424137">Chosen Bootstrap theme</a></p> |
3,805,329 | How does the updatePolicy in maven really work? | <p>When I define an <code>updatePolicy</code> in my maven settings it tells maven how often snapshot artifacts shall be downloaded.</p>
<p>If I set it to always it of course downloads every time all snapshots.</p>
<p>I was wondering what happens if I set it to the default value daily or another longer peroid.</p>
<p>Does maven still check whether a new version of the snapshot is available and if so, does it download it although the policy says daily ?</p>
<p>I'm looking for the correct settings to avoid redundant downloads and not to miss a newer snapshot out there.</p> | 3,805,559 | 1 | 0 | null | 2010-09-27 15:28:50.55 UTC | 11 | 2016-06-01 10:33:14.407 UTC | 2010-09-27 15:57:14.37 UTC | null | 70,604 | null | 459,654 | null | 1 | 45 | maven-2|snapshot | 36,851 | <blockquote>
<p>I was wondering what happens if I set it to the default value daily or another longer period.</p>
</blockquote>
<p>The <a href="https://cwiki.apache.org/confluence/display/MAVENOLD/Repository+-+SNAPSHOT+Handling" rel="noreferrer">Repository - SNAPSHOT Handling</a> explains it maybe better than the <a href="http://maven.apache.org/pom.html#Repositories" rel="noreferrer">POM reference</a>:</p>
<blockquote>
<p>Each repository in the project has its
own update policy:</p>
<ul>
<li>always - always check when Maven is started for newer versions of
snapshots</li>
<li>never - never check for newer remote versions. Once off manual updates can
be performed.</li>
<li>daily (default) - check on the first run of the day (local time)</li>
<li>interval:XXX - check every XXX minutes</li>
</ul>
</blockquote>
<p>I don't think there is anything to add (except maybe that check != download).</p>
<blockquote>
<p>Does maven still check whether a new version of the snapshot is available and if so, does it download it although the policy says daily ?</p>
</blockquote>
<p>Well, no, why would it? </p>
<blockquote>
<p>I'm looking for the correct settings to avoid redundant downloads and not to miss a newer snapshot out there.</p>
</blockquote>
<p>Use <code>always</code> if you always want Maven to download a <em>newer version</em> of snapshots, if available (Maven will always <em>check</em> the remote repository but only <em>download</em> <strong>if</strong> the version is newer).</p> |
21,261,851 | How to set a Textarea to 100% height in Bootstrap 3? | <p>I would like to set a <code>textarea</code> to be 100% height. I'm using <a href="http://getbootstrap.com/" rel="noreferrer">Bootstrap 3</a> but couldn't find an option there. </p>
<pre><code><div class="container">
<textarea class="form-control" rows="8"></textarea>
</div>
</code></pre>
<p>How to do it?</p> | 21,261,965 | 8 | 2 | null | 2014-01-21 15:08:16.16 UTC | 1 | 2020-12-03 21:57:58.583 UTC | null | null | null | null | 2,516,550 | null | 1 | 20 | html|css|twitter-bootstrap-3 | 80,844 | <pre><code>html, body, .container {
height: 100%;
}
textarea.form-control {
height: 100%;
}
</code></pre>
<p>See <a href="http://jsfiddle.net/6WEDU/" rel="noreferrer">demo on Fiddle</a></p> |
28,288,476 | Fade In and Fade out in Animation Swift | <p>I have an UIImageView with an Animation and, in the UIView, I apply a fadeIn effect, but I need to apply fade out when the UIImageView, which is animated, when is touched. </p>
<p>This is what I make to fade in. </p>
<pre><code>UIView.animateWithDuration(0.5, delay: delay,
options: UIViewAnimationOptions.CurveEaseOut, animations: {
uiImageView.alpha = 1.0
}
</code></pre> | 28,289,316 | 4 | 1 | null | 2015-02-02 23:01:48.143 UTC | 6 | 2019-07-10 03:07:20.687 UTC | null | null | null | null | 1,876,100 | null | 1 | 25 | ios|animation|swift|fadein|fadeout | 44,376 | <p>This is what I would do based on my research: (Supposing you're using storyboard)</p>
<ol>
<li><p>Go to your UIImageView, and under the Attributes, check the "User Interaction Enabled" checkbox.</p></li>
<li><p>Drag a TapGestureRecognizer on top of the image view.</p></li>
<li><p>Control click on the Tap Gesture and drag to make a action on your ViewControler.swift.</p></li>
<li><p>Add the following code inside:</p>
<pre><code>UIView.animate(withDuration: 0.5, delay: 0.5, options: .curveEaseOut, animations: {
self.uiImageView.alpha = 0.0
}, completion: nil)
</code></pre></li>
</ol>
<p>Then you're done!</p> |
1,748,470 | How to draw image on a window? | <p>I have created a window with createwindow() api using VS2005 in C++ on Windows Vista</p>
<p>My requirement is to draw an image (of any format) on that window. I am not using any MFC in this application.</p> | 1,760,571 | 3 | 0 | null | 2009-11-17 12:17:28.7 UTC | 8 | 2022-07-26 06:06:18.3 UTC | 2019-01-01 19:21:25.593 UTC | null | 472,495 | null | 122,939 | null | 1 | 17 | windows|winapi|createwindow | 55,717 | <p>not exactly sure what is your problem: draw a bitmap on the form, or you would like know how to work with various image formats, or both. Anyways below is an example of how you could load a bitmap and draw it on the form:</p>
<pre><code>HBITMAP hBitmap = NULL;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
switch (message)
{
<...>
case WM_CREATE:
hBitmap = (HBITMAP)LoadImage(hInst, L"c:\\test.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
break;
case WM_PAINT:
PAINTSTRUCT ps;
HDC hdc;
BITMAP bitmap;
HDC hdcMem;
HGDIOBJ oldBitmap;
hdc = BeginPaint(hWnd, &ps);
hdcMem = CreateCompatibleDC(hdc);
oldBitmap = SelectObject(hdcMem, hBitmap);
GetObject(hBitmap, sizeof(bitmap), &bitmap);
BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, oldBitmap);
DeleteDC(hdcMem);
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
DeleteObject(hBitmap);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
</code></pre>
<p>LoadImage loads an icon, cursor, animated cursor, or bitmap. Details <a href="http://msdn.microsoft.com/en-us/library/ms648045(VS.85).aspx" rel="noreferrer">here</a></p>
<p>For working with various images formats you can use Windows Imaging Component (see <a href="http://msdn.microsoft.com/en-us/library/bb531153(VS.85).aspx" rel="noreferrer">IWICBitmapDecoder</a>) or code from here <a href="http://www.arstdesign.com/articles/picloader.html" rel="noreferrer">Loading JPEG and GIF pictures</a> or 3rd party tools like <a href="http://freeimage.sourceforge.net/" rel="noreferrer">FreeImage</a> or <a href="http://www.leadtools.com/" rel="noreferrer">LeadTools</a></p>
<p>hope this helps, regards</p> |
2,269,363 | Put PNG over a JPG in PHP | <p>I want to do the following in PHP:</p>
<p>I have two images, a jpg and a png. I want to resize the jpg to the same size as the png then put the png on top. The PNG has transparency so I would like to preserve that so the jpg shows underneath.</p>
<p>If anyone could help that would be great!</p>
<p>Thanks</p> | 2,269,459 | 3 | 3 | null | 2010-02-15 22:25:24.587 UTC | 10 | 2010-06-24 21:35:49.107 UTC | null | null | null | null | 94,278 | null | 1 | 20 | php|image|image-processing|gd | 57,804 | <pre><code><?
$png = imagecreatefrompng('./mark.png');
$jpeg = imagecreatefromjpeg('./image.jpg');
list($width, $height) = getimagesize('./image.jpg');
list($newwidth, $newheight) = getimagesize('./mark.png');
$out = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($out, $jpeg, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagecopyresampled($out, $png, 0, 0, 0, 0, $newwidth, $newheight, $newwidth, $newheight);
imagejpeg($out, 'out.jpg', 100);
?>
</code></pre> |
1,679,145 | @interface and @protocol explanation? | <p>I would like to know what the @interface in objective C is? is it just where the programmer want to declare the variables, class name or method names...? I am not sure whether it is like interface in Java.
And about the @protocol in objective C as well. It seems like the interface in Java more.
Could anyone give me detail explanation please. I truly appreciate it.</p> | 1,679,160 | 3 | 0 | null | 2009-11-05 08:38:34.733 UTC | 24 | 2020-04-28 15:43:19.153 UTC | 2009-11-06 00:16:14.28 UTC | null | 1,116 | null | 194,383 | null | 1 | 83 | objective-c | 64,078 | <p>An interface is where you define the attributes and operations of class. You must set out the implementation too.</p>
<p>A protocol is like an interface for java. </p>
<p>e.g.</p>
<pre><code>@protocol Printing
-(void) print;
@end
</code></pre>
<p>can be implemented </p>
<p>by declaring (confusingly in the interface)</p>
<pre><code>@interface Fraction: NSObject <Printing, NSCopying> {
//etc..
</code></pre>
<p>The confusing thing for java developers is that the curly braces <code>{}</code> are not the end of the interface e.g.</p>
<pre><code>@interface Forwarder : Object
{
id recipient;
} //This is not the end of the interface - just the operations
- (id) recipient;
- (id) setRecipient:(id) _recipient;
//these are attributes.
@end
//This is the end of the interface
</code></pre> |
8,715,474 | Servlet and path parameters like /xyz/{value}/test, how to map in web.xml? | <p>Does servlet support urls as follows: </p>
<pre><code>/xyz/{value}/test
</code></pre>
<p>where value could be replaced by text or number. </p>
<p>How to map that in the web.xml?</p> | 8,715,566 | 7 | 1 | null | 2012-01-03 16:40:32.587 UTC | 11 | 2022-03-24 20:41:33.52 UTC | 2015-01-21 13:00:21.797 UTC | null | 157,882 | null | 650,195 | null | 1 | 40 | servlets|get|web.xml|path-parameter | 54,412 | <p>It's not supported by Servlet API to have the URL pattern wildcard <code>*</code> in middle of the mapping. It only allows the wildcard <code>*</code> in the end of the mapping like so <code>/prefix/*</code> or in the start of the mapping like so <code>*.suffix</code>.</p>
<p>With the standard allowed URL pattern syntax your best bet is to map it on <code>/xyz/*</code> and extract the path information using <a href="https://jakarta.ee/specifications/servlet/4.0/apidocs/javax/servlet/http/httpservletrequest#getPathInfo--" rel="nofollow noreferrer"><code>HttpServletRequest#getPathInfo()</code></a>.</p>
<p>So, given an <code><url-pattern>/xyz/*</url-pattern></code>, here's a basic kickoff example how to extract the path information, null checks and array index out of bounds checks omitted:</p>
<pre><code>String pathInfo = request.getPathInfo(); // /{value}/test
String[] pathParts = pathInfo.split("/");
String part1 = pathParts[1]; // {value}
String part2 = pathParts[2]; // test
// ...
</code></pre>
<p>If you want more finer grained control like as possible with Apache HTTPD's <code>mod_rewrite</code>, then you could look at <a href="http://tuckey.org/urlrewrite/" rel="nofollow noreferrer">Tuckey's URL rewrite filter</a> or <a href="https://stackoverflow.com/questions/2725102/how-to-use-a-servlet-filter-in-java-to-change-an-incoming-servlet-request-url">homegrow your own URL rewrite filter</a>.</p> |
27,304,834 | ViewPager Fragments – Shared Element Transitions | <p>An app I'm developing displays a grid of images. When you tap an image, it goes into the details view. The details view contains a ViewPager that allows you swipe between every image in the grid. This is done by passing a lists of paths (containing every image in the grid), along with an offset of the image that was tapped so the ViewPager can be set to show that page initially.</p>
<p>What's the best way to have a shared element transition inside the Fragment of the current offset page in the ViewPager? The grid (RecyclerView) image should expand into the full screen image in the current page. I saw the ability to postpone and resume activity transitions, so the app would wait to display the shared element transition until the image is loaded from the disk. But I want to be able to make it animate to the correct page in the view pager, and also exit to whatever the current page is when the user goes back (since you can swipe between pages). If you swipe to a different page now, the initial page is what animates back into the grid.</p>
<p>Currently, I assign every image in the Fragments of the view pager with a transitionName in the format "image_[index]". When I start the details activity, I use the same transitionName with the index being the offset.</p>
<p>Related to this, I was also wondering how to make ripples work with long presses. When you change a view's activated state, it seems to cancel the ripple. I want an effect similar to Gmail, where the ripple starts over again and quickly finishes after a long press is complete and triggers the activated state.</p> | 27,321,077 | 2 | 3 | null | 2014-12-04 21:53:09.033 UTC | 21 | 2016-07-09 13:06:42.567 UTC | 2014-12-04 23:47:42.66 UTC | null | 309,644 | null | 309,644 | null | 1 | 27 | android|animation|shared-element-transition|activity-transition|sharedelementcallback | 11,111 | <p>From what I can tell (and correct me if I'm wrong), what you are trying to achieve is basically something like this: Assume you have a <code>MainActivity</code>, a <code>DetailsActivity</code>, and an arbitrary set of images. The <code>MainActivity</code> displays the set of images in a grid and the <code>DetailsActivity</code> displays the same set of images in a horizontal <code>ViewPager</code>. When the user selects an image in the <code>MainActivity</code>, that image should transition from its position in the grid to the correct page in the second activity's <code>ViewPager</code>.</p>
<p>The problem we want to solve is "what if the user switches pages inside the <code>DetailsActivity</code>"? If this happens, we want to change the shared image that will be used during the return transition. By default, the activity transition framework will use the shared element that was used during the enter transition... but the view pager's page has changed so obviously we want to somehow override this behavior. To do so, we will need to set a <code>SharedElementCallback</code> in your <code>MainActivity</code> and <code>DetailsActivity</code>'s <code>onCreate()</code> methods and override the <code>onMapSharedElements()</code> method like so:</p>
<pre><code>private final SharedElementCallback mCallback = new SharedElementCallback() {
@Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
if (mCurrentImagePosition != mOriginalImagePosition) {
View sharedView = getImageAtPosition(mCurrentImagePosition);
names.clear();
sharedElements.clear();
names.add(sharedView.getTransitionName());
sharedElements.put(sharedView.getTransitionName(), sharedView);
}
}
/**
* Returns the image of interest to be used as the entering/returning
* shared element during the activity transition.
*/
private View getImageAtPosition(int position) {
// ...
}
};
</code></pre>
<p>For a more complete solution, I have created a <a href="https://github.com/alexjlockwood/activity-transitions"><strong>sample project on GitHub</strong></a> that will achieve this effect (there is too much code to post in a single StackOverflow answer).</p> |
713,138 | Getting the docstring from a function | <p>I have the following function:</p>
<pre><code>def my_func():
"""My docstring is both funny and informative"""
pass
</code></pre>
<p>How do I get access to the docstring?</p> | 713,143 | 4 | 1 | null | 2009-04-03 09:04:09.677 UTC | 32 | 2022-02-07 18:34:23.1 UTC | 2009-04-03 10:17:22.603 UTC | S.Lott | 10,661 | Teifion | 1,384,652 | null | 1 | 235 | python | 139,047 | <p>Interactively, you can display it with</p>
<pre><code>help(my_func)
</code></pre>
<p>Or from code you can retrieve it with</p>
<pre><code>my_func.__doc__
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.