id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,146,497 | Type of "this" in c++? | <pre><code>struct Foo
{
void f()
{
// (*)
}
};
</code></pre>
<p>What is the type of "this" in the line marked with (*) ?</p>
<p>Is it <strong>const Foo*</strong> or <strong>Foo*</strong> ?</p> | 17,146,540 | 4 | 4 | null | 2013-06-17 11:33:20.123 UTC | 9 | 2018-08-24 12:52:21.863 UTC | null | null | null | null | 978,461 | null | 1 | 32 | c++ | 2,822 | <p>n3376 9.3.2/1</p>
<p><Blockquote><P>
In the body of a non-static (9.3) member function, <strong>the keyword this is a prvalue expression</strong> whose value
is the address of the object for which the function is called.</p>
<p><strong>The type of this in a member function of
a class X is X*</strong>. If the member function is declared const, the type of this is const X*, if the member
function is declared volatile, the type of this is volatile X*, and if the member function is declared
const volatile, the type of this is const volatile X*.</P></Blockquote></p> |
17,274,130 | Bootstrap Tooltip - Hide when another tooltip is click | <p>I hope someone can help.</p>
<p>I'm trying to hide the tooltip when another tooltip icon is clicked. It works but when I decide to click the last tooltip again it 'flashes' the tooltip.</p>
<pre><code>var Hastooltip = $('.hastooltip');
HasTooltip.on('click', function(e) {
e.preventDefault();
HasTooltip.tooltip('hide');
}).tooltip({
animation: true
}).parent().delegate('.close', 'click', function() {
HasTooltip.tooltip('hide');
});
</code></pre>
<p>HTML</p>
<pre><code><a href="#" class="hastooltip" data-original-title="Lorem ipsum dolor sit amet, consectetur adipisicing elit.">
<h3>Info 1</h3>
</a>
<a href="#" class="hastooltip" data-original-title="Lorem ipsum dolor sit amet, consectetur adipisicing elit.">
<h3>Info 2</h3>
</a>
</code></pre>
<p>If it helps a following markup is added to the DOM when the user clicks on the button to display the tooltip.</p>
<pre><code><div class="tooltip"</div>
</code></pre> | 17,281,854 | 10 | 4 | null | 2013-06-24 11:14:47.227 UTC | 3 | 2022-09-22 18:21:06.29 UTC | 2013-06-24 17:20:14.673 UTC | null | 422,353 | null | 1,381,806 | null | 1 | 36 | javascript|jquery|twitter-bootstrap|tooltip | 67,090 | <p>You need to check if the tooltip is showing and toggle its visibility manually. This is one way of doing it.</p>
<pre><code>$(function() {
var HasTooltip = $('.hastooltip');
HasTooltip.on('click', function(e) {
e.preventDefault();
var isShowing = $(this).data('isShowing');
HasTooltip.removeData('isShowing');
if (isShowing !== 'true')
{
HasTooltip.not(this).tooltip('hide');
$(this).data('isShowing', "true");
$(this).tooltip('show');
}
else
{
$(this).tooltip('hide');
}
}).tooltip({
animation: true,
trigger: 'manual'
});
});
</code></pre> |
17,301,972 | Projecting into KeyValuePair via EF / Linq | <p>I'm trying to load a list of KeyValuePairs from an EF / Linq query like this: </p>
<pre><code>return (from o in context.myTable
select new KeyValuePair<int, string>(o.columnA, o.columnB)).ToList();
</code></pre>
<p>My problem is that this results in the error </p>
<blockquote>
<p>"Only parameterless constructors and initializers are supported in
LINQ to Entities."</p>
</blockquote>
<p>Is there an easy way around this? I know I could create a custom class for this instead of using KeyValuePair but that does seem like re-inventing the wheel.</p> | 17,302,070 | 3 | 1 | null | 2013-06-25 15:53:33.343 UTC | 4 | 2018-09-11 13:45:48.847 UTC | 2018-09-11 13:45:48.847 UTC | null | 5,947,043 | null | 543,538 | null | 1 | 42 | c#|linq|entity-framework|projection|keyvaluepair | 41,378 | <p>Select only columnA and columnB from your table, and move further processing in memory:</p>
<pre><code>return context.myTable
.Select(o => new { o.columnA, o.columnB }) // only two fields
.AsEnumerable() // to clients memory
.Select(o => new KeyValuePair<int, string>(o.columnA, o.columnB))
.ToList();
</code></pre>
<p>Consider also to create dictionary which contains KeyValuePairs:</p>
<pre><code>return context.myTable.ToDictionary(o => o.columnA, o => o.columnB).ToList();
</code></pre> |
30,692,537 | CoordinatorLayout ignores margins for views with anchor | <p>Given I'm using a layout like this:</p>
<pre><code><android.support.design.widget.CoordinatorLayout
android:id="@+id/main_content"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="@dimen/flexible_space_image_height"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:statusBarScrim="@android:color/transparent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/mainView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginBottom="20dp"
app:fabSize="normal"
app:layout_anchor="@id/appbar"
app:layout_anchorGravity="bottom|center_horizontal"
/>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p>Which is pretty much the standard <a href="https://github.com/chrisbanes/cheesesquare" rel="noreferrer">Cheesesquare</a> sample - except the FloatingActionButton, which I would like to move up by about 20dp.</p>
<p>However, this will not work. No matter if I use margin, padding etc - the button will always be centered at the edge of the anchor, like this:</p>
<p><img src="https://i.stack.imgur.com/NOrYO.png" alt="FAB will ignore the margin"></p>
<p>How can I move the FAB up by 20dp as intended?</p> | 30,694,035 | 7 | 2 | null | 2015-06-07 10:36:56.493 UTC | 5 | 2022-03-13 19:58:08.12 UTC | null | null | null | null | 375,209 | null | 1 | 30 | android|android-support-library|androiddesignsupport | 22,930 | <p>As there might be <a href="https://code.google.com/p/android/issues/list?can=2&q=CoordinatorLayout&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&cells=tiles" rel="nofollow">bugs</a> in the design-support-lib concerning the <code>CoordinatorLayout</code> & margins, I wrote a <code>FrameLayout</code> that implements/copies the same "Behavior" like the FAB and allows to set a <code>padding</code> to simulate the effect:</p>
<p>Be sure to put it in the <code>android.support.design.widget</code> package as it needs to access some package-scoped classes.</p>
<pre><code>/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import com.company.android.R;
import java.util.List;
@CoordinatorLayout.DefaultBehavior(FrameLayoutWithBehavior.Behavior.class)
public class FrameLayoutWithBehavior extends FrameLayout {
public FrameLayoutWithBehavior(final Context context) {
super(context);
}
public FrameLayoutWithBehavior(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public FrameLayoutWithBehavior(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FrameLayoutWithBehavior(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public static class Behavior extends android.support.design.widget.CoordinatorLayout.Behavior<FrameLayoutWithBehavior> {
private static final boolean SNACKBAR_BEHAVIOR_ENABLED;
private Rect mTmpRect;
private boolean mIsAnimatingOut;
private float mTranslationY;
public Behavior() {
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, FrameLayoutWithBehavior child, View dependency) {
return SNACKBAR_BEHAVIOR_ENABLED && dependency instanceof Snackbar.SnackbarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, FrameLayoutWithBehavior child, View dependency) {
if (dependency instanceof Snackbar.SnackbarLayout) {
this.updateFabTranslationForSnackbar(parent, child, dependency);
} else if (dependency instanceof AppBarLayout) {
AppBarLayout appBarLayout = (AppBarLayout) dependency;
if (this.mTmpRect == null) {
this.mTmpRect = new Rect();
}
Rect rect = this.mTmpRect;
ViewGroupUtils.getDescendantRect(parent, dependency, rect);
if (rect.bottom <= appBarLayout.getMinimumHeightForVisibleOverlappingContent()) {
if (!this.mIsAnimatingOut && child.getVisibility() == VISIBLE) {
this.animateOut(child);
}
} else if (child.getVisibility() != VISIBLE) {
this.animateIn(child);
}
}
return false;
}
private void updateFabTranslationForSnackbar(CoordinatorLayout parent, FrameLayoutWithBehavior fab, View snackbar) {
float translationY = this.getFabTranslationYForSnackbar(parent, fab);
if (translationY != this.mTranslationY) {
ViewCompat.animate(fab)
.cancel();
if (Math.abs(translationY - this.mTranslationY) == (float) snackbar.getHeight()) {
ViewCompat.animate(fab)
.translationY(translationY)
.setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR)
.setListener((ViewPropertyAnimatorListener) null);
} else {
ViewCompat.setTranslationY(fab, translationY);
}
this.mTranslationY = translationY;
}
}
private float getFabTranslationYForSnackbar(CoordinatorLayout parent, FrameLayoutWithBehavior fab) {
float minOffset = 0.0F;
List dependencies = parent.getDependencies(fab);
int i = 0;
for (int z = dependencies.size(); i < z; ++i) {
View view = (View) dependencies.get(i);
if (view instanceof Snackbar.SnackbarLayout && parent.doViewsOverlap(fab, view)) {
minOffset = Math.min(minOffset, ViewCompat.getTranslationY(view) - (float) view.getHeight());
}
}
return minOffset;
}
private void animateIn(FrameLayoutWithBehavior button) {
button.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ViewCompat.animate(button)
.scaleX(1.0F)
.scaleY(1.0F)
.alpha(1.0F)
.setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR)
.withLayer()
.setListener((ViewPropertyAnimatorListener) null)
.start();
} else {
Animation anim = android.view.animation.AnimationUtils.loadAnimation(button.getContext(), R.anim.fab_in);
anim.setDuration(200L);
anim.setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR);
button.startAnimation(anim);
}
}
private void animateOut(final FrameLayoutWithBehavior button) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ViewCompat.animate(button)
.scaleX(0.0F)
.scaleY(0.0F)
.alpha(0.0F)
.setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR)
.withLayer()
.setListener(new ViewPropertyAnimatorListener() {
public void onAnimationStart(View view) {
Behavior.this.mIsAnimatingOut = true;
}
public void onAnimationCancel(View view) {
Behavior.this.mIsAnimatingOut = false;
}
public void onAnimationEnd(View view) {
Behavior.this.mIsAnimatingOut = false;
view.setVisibility(View.GONE);
}
})
.start();
} else {
Animation anim = android.view.animation.AnimationUtils.loadAnimation(button.getContext(), R.anim.fab_out);
anim.setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR);
anim.setDuration(200L);
anim.setAnimationListener(new AnimationUtils.AnimationListenerAdapter() {
public void onAnimationStart(Animation animation) {
Behavior.this.mIsAnimatingOut = true;
}
public void onAnimationEnd(Animation animation) {
Behavior.this.mIsAnimatingOut = false;
button.setVisibility(View.GONE);
}
});
button.startAnimation(anim);
}
}
static {
SNACKBAR_BEHAVIOR_ENABLED = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
}
}
</code></pre> |
18,679,020 | Border around tr element doesn't show? | <p>It seems like Chrome/Firefox do not render borders on <code>tr</code>, but it renders the border if the selector is <code>table tr td</code>.</p>
<p>How can I set a border on a tr ?</p>
<p>My attempt, which doesn't work:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>table tr {
border: 1px solid black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tbody>
<tr>
<td>
Text
</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/edi9999/VzPN2/" rel="nofollow noreferrer">http://jsfiddle.net/edi9999/VzPN2/</a></p>
<p>This is a similar question: <a href="https://stackoverflow.com/questions/583539/set-border-to-table-tr-works-in-everything-except-ie-6-7">Set border to table tr, works in everything except IE 6 & 7</a> , but it seems to work everywhere except for IE.</p> | 18,679,047 | 3 | 1 | null | 2013-09-07 23:45:50.39 UTC | 31 | 2022-09-19 13:31:33.26 UTC | 2022-09-19 13:31:33.26 UTC | null | 1,993,501 | null | 1,993,501 | null | 1 | 166 | html|css|html-table | 131,024 | <p>Add this to the stylesheet:</p>
<pre><code>table {
border-collapse: collapse;
}
</code></pre>
<p><a href="http://jsfiddle.net/ZKjAX/" rel="noreferrer">JSFiddle</a>.</p>
<p>The reason why it behaves this way is actually described pretty well in <a href="http://www.w3.org/TR/CSS2/tables.html#borders" rel="noreferrer">the specification</a>:</p>
<blockquote>
<p>There are two distinct models for setting borders on table cells in
CSS. One is most suitable for so-called separated borders around
individual cells, the other is suitable for borders that are
continuous from one end of the table to the other.</p>
</blockquote>
<p>... and later, for <code>collapse</code> setting:</p>
<blockquote>
<p>In the collapsing border model, it is possible to specify borders that
surround all or part of a cell, row, row group, column, and column
group.</p>
</blockquote> |
18,580,397 | How to remove a key from a RethinkDB document? | <p>I'm trying to remove a key from a RethinkDB document.
My approaches (which didn't work):</p>
<pre><code>r.db('db').table('user').replace(function(row){delete row["key"]; return row})
</code></pre>
<p>Other approach:</p>
<pre><code>r.db('db').table('user').update({key: null})
</code></pre>
<p>This one just sets row.key = null (which looks reasonable).</p>
<p>Examples tested on <em>rethinkdb data explorer</em> through web UI. </p> | 18,580,552 | 3 | 0 | null | 2013-09-02 20:31:42.213 UTC | 5 | 2017-12-29 23:59:54.347 UTC | 2017-04-24 14:15:49.147 UTC | null | 265,261 | null | 297,094 | null | 1 | 46 | rethinkdb|rethinkdb-python | 15,826 | <p>Here's the relevant example from the documentation on RethinkDB's website: <a href="http://rethinkdb.com/docs/cookbook/python/#removing-a-field-from-a-document" rel="noreferrer">http://rethinkdb.com/docs/cookbook/python/#removing-a-field-from-a-document</a></p>
<p>To remove a field from all documents in a table, you need to use <code>replace</code> to update the document to not include the desired field (using <code>without</code>):</p>
<pre><code>r.db('db').table('user').replace(r.row.without('key'))
</code></pre>
<p>To remove the field from one specific document in the table:</p>
<pre><code>r.db('db').table('user').get('id').replace(r.row.without('key'))
</code></pre>
<p>You can change the selection of documents to update by using any of the selectors in the API (<a href="http://rethinkdb.com/api/" rel="noreferrer">http://rethinkdb.com/api/</a>), e.g. <code>db</code>, <code>table</code>, <code>get</code>, <code>get_all</code>, <code>between</code>, <code>filter</code>.</p> |
26,074,784 | How to make a view with rounded corners? | <p>I am trying to make a view in android with rounded edges. The solution I found so far is to define a shape with rounded corners and use it as the background of that view.</p>
<p>Here is what I did, define a drawable as given below:</p>
<p>
</p>
<pre><code><padding
android:top="2dp"
android:bottom="2dp"/>
<corners android:bottomRightRadius="20dp"
android:bottomLeftRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"/>
</code></pre>
<p></p>
<p>Now I used this as the background for my layout as below:</p>
<pre><code><LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:clipChildren="true"
android:background="@drawable/rounded_corner">
</code></pre>
<p>This works perfectly fine, I can see that the view has rounded edges. </p>
<p>But my layout has got many other child views in it, say an ImageView or a <code>MapView</code>. When I place an <code>ImageView</code> inside the above layout, the corners of image are not clipped/cropped, instead it appears full.</p>
<p>I have seen other workarounds to make it work like the one explained <a href="http://www.techrepublic.com/article/pro-tip-round-corners-on-an-android-imageview-with-this-hack/" rel="noreferrer">here</a>. </p>
<blockquote>
<p>But is there a method to set rounded corners for a view and all its
child views are contained within that main view that has rounded
corners?</p>
</blockquote> | 26,201,117 | 21 | 4 | null | 2014-09-27 12:41:53.347 UTC | 39 | 2022-06-24 16:32:51.467 UTC | 2020-02-28 07:35:06.31 UTC | null | 6,138,892 | null | 623,401 | null | 1 | 116 | android|android-layout|view|android-view|android-shape | 155,995 | <p>Another approach is to make a custom layout class like the one below. This layout first draws its contents to an offscreen bitmap, masks the offscreen bitmap with a rounded rect and then draws the offscreen bitmap on the actual canvas.</p>
<p>I tried it and it seems to work (at least for my simple testcase). It will of course affect performance compared to a regular layout.</p>
<pre><code>package com.example;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.FrameLayout;
public class RoundedCornerLayout extends FrameLayout {
private final static float CORNER_RADIUS = 40.0f;
private Bitmap maskBitmap;
private Paint paint, maskPaint;
private float cornerRadius;
public RoundedCornerLayout(Context context) {
super(context);
init(context, null, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, metrics);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
setWillNotDraw(false);
}
@Override
public void draw(Canvas canvas) {
Bitmap offscreenBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
Canvas offscreenCanvas = new Canvas(offscreenBitmap);
super.draw(offscreenCanvas);
if (maskBitmap == null) {
maskBitmap = createMask(canvas.getWidth(), canvas.getHeight());
}
offscreenCanvas.drawBitmap(maskBitmap, 0f, 0f, maskPaint);
canvas.drawBitmap(offscreenBitmap, 0f, 0f, paint);
}
private Bitmap createMask(int width, int height) {
Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
Canvas canvas = new Canvas(mask);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
canvas.drawRect(0, 0, width, height, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, paint);
return mask;
}
}
</code></pre>
<p>Use this like a normal layout:</p>
<pre><code><com.example.RoundedCornerLayout
android:layout_width="200dp"
android:layout_height="200dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/test"/>
<View
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#ff0000"
/>
</com.example.RoundedCornerLayout>
</code></pre> |
5,365,566 | Parse string to float number C# | <p>I have float number in string. there is one problem. Number uses "." not "," as decimal point.</p>
<p>This code is not working:</p>
<pre><code>MyNumber = float.Parse("123.5");
</code></pre>
<p>I know that I can use string replace function to "repair" this string before Parsing.</p>
<pre><code>MyNumber = float.Parse("123.5".Replace('.',',');
</code></pre>
<p>But is there any other way to do it?</p> | 5,365,939 | 3 | 0 | null | 2011-03-19 23:14:16.91 UTC | 1 | 2013-07-06 15:03:50.117 UTC | 2012-06-04 15:26:48.853 UTC | null | 44,390 | null | 465,408 | null | 1 | 12 | c#|.net|string|parsing|floating-point | 44,980 | <p>To add to Steven's question, rather than argue differently, the important thing is <em>why</em> the decimal separator is <code>.</code>.</p>
<p>If it's because the source is in a computer-readable format where the period decimal separator is specified as part of the document specification, then I'd go precisely as Steven does in using <code>CultureInfo.InvariantCulture</code>.</p>
<p>If it's human input in a particular locale, then you would want to match that locale by the <code>CultureInfo</code> appropriate for that locale, otherwise if the software is used with a different locale you'd have precisely the opposite problem. Generally you would want to set the thread's <code>CurrentCulture</code> to match this (<code>CurrentCulture</code> for formats, <code>CurrentUICulture</code> for languages). If you've done this, then you don't need to pass a culture at all, as the form <code>float.Parse(string)</code> uses that culture - however, you may wish to use <code>float.Parse(string, CurrentCulture)</code> to be explicit that this is what you are doing (and to shut up some software analysis that complains when you aren't specific in this way).</p>
<p>What gets really tricky, is if you potentially have to accept both period and comma - not least because many cultures that use period as a decimal separator, use comma as a thousands separator, and ultimately it's impossible to guarantee unambiguous parsing. However, assuming the thousands issue doesn't affect you, then the code you gave in your question is the approach, though I'd recommend doing the opposite (replace comma with period) and then parsing with the invariant culture, as that removes any further complications caused by yet more culture changes.</p> |
18,643,457 | How do I add a class to an @Html.ActionLink? | <p>I have two <code>@Html.ActionLink's</code> that I want to make look like buttons. I'm able to make this happen with <code>CSS</code> but only if I use the #ID of the actionlink to apply the <code>CSS</code>. I want to assign a class to the action links but when I do using the code below I get an error saying I have a missing "}". </p>
<pre><code> @Html.ActionLink("Print PO", "PoReport", new { id = 51970},
new { id = "PoPrint"} , new { class = "PoClass"})
</code></pre>
<p>Here is the Style I am applying:</p>
<pre><code><style>
#PoPrint
{
border: 4px outset;
padding: 2px;
text-decoration: none;
background-color:lightskyblue;
}
</style>
</code></pre>
<p>This works and I suppose I could just add the other #ID to tthe style but would like to apply the style to the Class. </p> | 18,643,539 | 5 | 3 | null | 2013-09-05 18:29:46.763 UTC | 8 | 2020-04-16 05:38:48.477 UTC | 2014-10-15 09:05:25.45 UTC | null | 542,251 | null | 1,018,705 | null | 1 | 26 | css|asp.net-mvc|razor | 89,004 | <p>You have to use the <code>@</code> character, since class is a keyword in C#. Here's a link to the MSDN documentation: <a href="http://msdn.microsoft.com/en-us/library/dd492124(v=vs.108).aspx">http://msdn.microsoft.com/en-us/library/dd492124(v=vs.108).aspx</a></p>
<pre><code>@Html.ActionLink("Link Text", "ActionName",
new { controller = "MyController", id = 1 },
new { @class = "my-class" })
</code></pre> |
18,548,156 | How to copy the conditional formatting without copying the rules from a Conditional Formatted cell? | <p>I have a row of data with conditional formatting in it.</p>
<p>I need to copy this row to another row. This new row must be identical (values, formats), but static, i.e. without the rules. If I copy and paste the row and clear the rules, the formatting from the CF rule vanishes.</p>
<p>Is it possible?</p> | 26,157,745 | 8 | 5 | null | 2013-08-31 12:31:36.403 UTC | 5 | 2021-04-05 09:36:59.553 UTC | 2016-12-21 22:21:46.39 UTC | null | 2,359,271 | null | 1,845,356 | null | 1 | 29 | excel | 77,084 | <p>Just discovered an easy way: <strong>Copy the table to MS Word and copy it back to excel :D</strong></p>
<hr>
<p>It worked perfectly for me.</p> |
18,444,194 | Cutting the videos based on start and end time using ffmpeg | <p>I tried to cut the video using the start and end time of the video by using the following command</p>
<pre><code>ffmpeg -ss 00:00:03 -t 00:00:08 -i movie.mp4 -acodec copy -vcodec copy -async 1 cut.mp4
</code></pre>
<p>By using the above command i want to cut the video from <code>00:00:03</code> to <code>00:00:08</code>. But it is not cutting the video between those times instead of that it is cutting the video with first 11 seconds. can anyone help me how resolve this?</p>
<p><strong>Edit 1:</strong></p>
<p>I have tried to cut by using the following command which is suggested by <a href="https://stackoverflow.com/users/112212/mark4o">mark4o</a></p>
<pre><code>ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
</code></pre>
<p>But it was shown the following error.</p>
<p><em><strong>the encoder 'aac' is experimental but experimental codecs are not enabled</strong></em></p>
<p>so i added the <code>-strict -2</code> into the command i.e.,</p>
<pre><code>ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 -strict -2 cut.mp4
</code></pre>
<p>Now it is working fine.</p> | 18,449,609 | 13 | 7 | null | 2013-08-26 12:34:19.137 UTC | 355 | 2022-06-21 21:03:18.29 UTC | 2021-12-07 03:54:07.367 UTC | null | 162,698 | null | 788,891 | null | 1 | 852 | video|ffmpeg|video-editing | 789,198 | <p>You probably do not have a keyframe at the 3 second mark. Because non-keyframes encode differences from other frames, they require all of the data starting with the previous keyframe.</p>
<p>With the mp4 container it is possible to cut at a non-keyframe without re-encoding using an edit list. In other words, if the closest keyframe before 3s is at 0s then it will copy the video starting at 0s and use an edit list to tell the player to start playing 3 seconds in.</p>
<p>If you are using the <a href="http://ffmpeg.org/download.html">latest ffmpeg</a> from git master it will do this using an edit list when invoked using the command that you provided. If this is not working for you then you are probably either using an older version of ffmpeg, or your player does not support edit lists. Some players will ignore the edit list and always play all of the media in the file from beginning to end.</p>
<p>If you want to cut precisely starting at a non-keyframe and want it to play starting at the desired point on a player that does not support edit lists, or want to ensure that the cut portion is not actually in the output file (for example if it contains confidential information), then you can do that by re-encoding so that there will be a keyframe precisely at the desired start time. Re-encoding is the default if you do not specify <code>copy</code>. For example:</p>
<pre><code>ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
</code></pre>
<p>When re-encoding you may also wish to include additional quality-related options or a particular AAC encoder. For details, see ffmpeg's <a href="https://trac.ffmpeg.org/wiki/Encode/H.264">x264 Encoding Guide</a> for video and <a href="https://trac.ffmpeg.org/wiki/Encode/AAC">AAC Encoding Guide</a> for audio.</p>
<p>Also, the <code>-t</code> option specifies a duration, not an end time. The above command will encode 8s of video starting at 3s. To start at 3s and end at 8s use <code>-t 5</code>. If you are using a current version of ffmpeg you can also replace <code>-t</code> with <code>-to</code> in the above command to end at the specified time.</p> |
15,339,143 | Eclipse Run button doesn't work when Android xml file is selected | <p>I have Eclipse Juno SR1 and Android SDK Tools 21.1, SDK Platform-tools 16.0.2 (latest) on Mac.</p>
<p>When I have some XML file selected and hit Run button, nothing happens. I have to select some Java File or project in the Package Explorer. Then it runs. It's quite annoying when I edit XML files. It was working in previous releases of Android SDK Tools. </p>
<p>Anyone knows any solution or workaround?</p> | 15,339,199 | 1 | 0 | null | 2013-03-11 12:55:44.507 UTC | 2 | 2013-03-11 13:03:36.923 UTC | null | null | null | null | 560,358 | null | 1 | 37 | android|eclipse|android-xml|android-sdk-tools | 6,520 | <p>I think its due to some recent changes in <strong>ADT 21.1.0</strong>. Anyhow, to resolve this, you may configure the following in Eclipse:</p>
<blockquote>
<p><kbd>Window</kbd> -> <kbd>Preferences</kbd> -> <kbd>Run/Debug</kbd> ->
<kbd>Launching</kbd> -> (under Launch Operations) <strong>Always launch the
previously launched application</strong></p>
</blockquote>
<p>In case you want to open another project, then you need to revert this process as it will always launch the previously launched application.</p>
<p>Also, keep in mind that this issue may be fixed in the future versions of ADT, so don't rely hard on this solution.</p> |
15,111,408 | How does sklearn.svm.svc's function predict_proba() work internally? | <p>I am using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html" rel="noreferrer">sklearn.svm.svc</a> from <a href="http://scikit-learn.org/stable/" rel="noreferrer">scikit-learn</a> to do binary classification. I am using its predict_proba() function to get probability estimates. Can anyone tell me how predict_proba() internally calculates the probability?</p> | 15,112,563 | 2 | 0 | null | 2013-02-27 11:50:57.28 UTC | 34 | 2014-02-07 01:09:35.147 UTC | 2013-02-27 12:21:08.757 UTC | null | 1,067,887 | null | 2,115,183 | null | 1 | 46 | python|svm|scikit-learn | 37,931 | <p>Scikit-learn uses LibSVM internally, and this in turn uses <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.1639" rel="noreferrer">Platt scaling</a>, as detailed in <a href="http://www.csie.ntu.edu.tw/~cjlin/papers/plattprob.pdf" rel="noreferrer">this note by the LibSVM authors</a>, to calibrate the SVM to produce probabilities in addition to class predictions.</p>
<p>Platt scaling requires first training the SVM as usual, then optimizing parameter vectors <em>A</em> and <em>B</em> such that</p>
<pre><code>P(y|X) = 1 / (1 + exp(A * f(X) + B))
</code></pre>
<p>where <code>f(X)</code> is the signed distance of a sample from the hyperplane (scikit-learn's <code>decision_function</code> method). You may recognize the <a href="https://en.wikipedia.org/wiki/Logistic_function" rel="noreferrer">logistic sigmoid</a> in this definition, the same function that logistic regression and neural nets use for turning decision functions into probability estimates.</p>
<p>Mind you: the <code>B</code> parameter, the "intercept" or "bias" or whatever you like to call it, can cause predictions based on probability estimates from this model to be inconsistent with the ones you get from the SVM decision function <code>f</code>. E.g. suppose that <code>f(X) = 10</code>, then the prediction for <code>X</code> is positive; but if <code>B = -9.9</code> and <code>A = 1</code>, then <code>P(y|X) = .475</code>. I'm pulling these numbers out of thin air, but you've noticed that this can occur in practice.</p>
<p>Effectively, Platt scaling trains a probability model on top of the SVM's outputs under a cross-entropy loss function. To prevent this model from overfitting, it uses an internal five-fold cross validation, meaning that training SVMs with <code>probability=True</code> can be quite a lot more expensive than a vanilla, non-probabilistic SVM.</p> |
28,307,237 | Spring Could not Resolve placeholder | <p>I'm fairly new to spring so excuse me if this is a dumb question. When I try to launch a program I get the following error: <code>java.lang.IllegalArgumentException: Could not resolve placeholder 'appclient' in string value [${appclient}]</code>. The error is thrown when the following code is executed:</p>
<pre><code>package ca.virology.lib2.common.config.spring.properties;
import ca.virology.lib2.config.spring.PropertiesConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
@Configuration
@Import({PropertiesConfig.class})
@PropertySource("${appclient}")
public class AppClientProperties {
private static final Logger log = LoggerFactory.getLogger(AppClientProperties.class);
{
//this initializer block will execute when an instance of this class is created by Spring
log.info("Loading AppClientProperties");
}
@Value("${appclient.port:}")
private int appClientPort;
@Value("${appclient.host:}")
private String appClientHost;
public int getAppClientPort() {
return appClientPort;
}
public String getAppClientHost() {
return appClientHost;
}
}
</code></pre>
<p>A property file called <code>appclient.properties</code> exists in the resources folder with the information for host and port. I'm not sure where the <code>"${appclient}"</code> is defined, if it is at all. Maybe it is not even defined and that is causing the problem. Do I need to change the <code>"${appclient}"</code> to something like <code>"{classpath:/appclient.properties}"</code> or am I missing something else? </p> | 28,307,313 | 9 | 3 | null | 2015-02-03 19:34:01.153 UTC | 11 | 2022-05-24 21:57:04.773 UTC | null | null | null | null | 1,272,809 | null | 1 | 35 | java|spring | 206,300 | <p>You are not reading the properties file correctly. The propertySource should pass the parameter as: <code>file:appclient.properties</code> or <code>classpath:appclient.properties</code>. Change the annotation to:</p>
<pre><code>@PropertySource(value={"classpath:appclient.properties"})
</code></pre>
<p>However I don't know what your <code>PropertiesConfig</code> file contains, as you're importing that also. Ideally the <code>@PropertySource</code> annotation should have been kept there.</p> |
9,575,652 | OpenCV using k-means to posterize an image | <p>I want to posterize an image with k-means and OpenCV in C++ interface (cv namespace) and I get weird results. I need it for reduce some noise. This is my code:</p>
<pre><code>#include "cv.h"
#include "highgui.h"
using namespace cv;
int main() {
Mat imageBGR, imageHSV, planeH, planeS, planeV;
imageBGR = imread("fruits.jpg");
imshow("original", imageBGR);
cv::Mat labels, data;
cv::Mat centers(8, 1, CV_32FC1);
imageBGR.convertTo(data, CV_32F);
cv::kmeans(data, 8, labels,
cv::TermCriteria(CV_TERMCRIT_ITER, 10, 1.0),
3, cv::KMEANS_PP_CENTERS, &centers);
imshow("posterized hue", data);
data.convertTo(data, CV_32FC3);
waitKey();
return 0;
}
</code></pre>
<p>But I get a weird result</p>
<p><img src="https://i.stack.imgur.com/dGy2i.png" alt="Fruit" /></p>
<p>First image: original</p>
<p>Second image: after k-means.</p>
<p>Any advice?</p>
<hr />
<h1>Update: the right solution. maybe someone can help me in optimize the code?</h1>
<pre><code>#include "cv.h"
#include "highgui.h"
#include <iostream>
using namespace cv;
using namespace std;
int main() {
Mat src;
src = imread("fruits.jpg");
imshow("original", src);
blur(src, src, Size(15,15));
imshow("blurred", src);
Mat p = Mat::zeros(src.cols*src.rows, 5, CV_32F);
Mat bestLabels, centers, clustered;
vector<Mat> bgr;
cv::split(src, bgr);
// i think there is a better way to split pixel bgr color
for(int i=0; i<src.cols*src.rows; i++) {
p.at<float>(i,0) = (i/src.cols) / src.rows;
p.at<float>(i,1) = (i%src.cols) / src.cols;
p.at<float>(i,2) = bgr[0].data[i] / 255.0;
p.at<float>(i,3) = bgr[1].data[i] / 255.0;
p.at<float>(i,4) = bgr[2].data[i] / 255.0;
}
int K = 8;
cv::kmeans(p, K, bestLabels,
TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0),
3, KMEANS_PP_CENTERS, centers);
int colors[K];
for(int i=0; i<K; i++) {
colors[i] = 255/(i+1);
}
// i think there is a better way to do this mayebe some Mat::reshape?
clustered = Mat(src.rows, src.cols, CV_32F);
for(int i=0; i<src.cols*src.rows; i++) {
clustered.at<float>(i/src.cols, i%src.cols) = (float)(colors[bestLabels.at<int>(0,i)]);
// cout << bestLabels.at<int>(0,i) << " " <<
// colors[bestLabels.at<int>(0,i)] << " " <<
// clustered.at<float>(i/src.cols, i%src.cols) << " " <<
// endl;
}
clustered.convertTo(clustered, CV_8U);
imshow("clustered", clustered);
waitKey();
return 0;
}
</code></pre>
<p>Result:</p>
<p><img src="https://i.stack.imgur.com/QBVcV.png" alt="Posterized Fruit" /></p> | 9,608,527 | 3 | 9 | null | 2012-03-05 23:22:38.96 UTC | 11 | 2022-05-06 10:21:48.367 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 433,685 | null | 1 | 18 | c++|image-processing|opencv|k-means|noise-reduction | 34,320 | <p>I am no expert in OpenCV so I will give a general advice that relates to your question K-means takes list of vectors which is essentially a matrix:</p>
<pre><code>[x0, y0, r0, g0, b0]
[x1, y1, r1, g1, b1]
[x2, y2, r2, g2, b2]
.
.
.
</code></pre>
<p>You are giving it an image which is not going to work. You first have to convert the image to this k-means matrix format. For each pixel of the source image you have one row in the resulting matrix. Also note that you should scale the values so that they all have similar values. If you don't do that, x and y coordinates will usually have much higher "gravity" than the color which leads to unsatisfactory results. C++ pseudocode:</p>
<pre><code>int pixel_index = 0;
for (int y = 0; y < image height; y++) {
for (int x = 0; x < image width; x++) {
matrix[pixel_index][0] = (float)x / image width;
matrix[pixel_index][1] = (float)y / image height;
matrix[pixel_index][2] = (float)pixel(x, y).r / 255.0f;
matrix[pixel_index][3] = (float)pixel(x, y).g / 255.0f;
matrix[pixel_index][4] = (float)pixel(x, y).b / 255.0f;
}
}
// Pass the matrix to kmeans...
</code></pre>
<p>As a result, you get labels of each individual pixel which corresponds to the cluster it has been assigned to. You then need to determine the color of the clusters - this can vary from taking the center pixel color value to computing an average/median color of the cluster. After you determine the color, just walk the image and set pixels to their cluster colors:</p>
<pre><code>for (int y = 0; y < image height; y++) {
for (int x = 0; x < image width; x++) {
int index = y * image width + x; // This corresponds to pixel_index above
int cluster_index = labels[index]; // 0 to 7 in your case
Color color = colors[cluster_index]; // Colors is an array of 8 colors of the clusters
image.setpixel(x, y, color)
}
}
</code></pre>
<p>If you prefer to use HSV instead of RGB, just use HSV values instead of RGB ones. </p>
<p>It is possible that OpenCV has functions that perform exactly the conversion I described above but I was unable to quick find them using Google.</p> |
8,777,359 | error: subscripted value is neither array nor pointer nor vector in C | <pre><code>the_project.c:73:22: error: subscripted value is neither array nor pointer nor vector
</code></pre>
<p>it gives the error above and the line 73 is the following.</p>
<pre><code>customer_table[my_id][3] = worker_no;
</code></pre>
<p>I declared the array global as follows</p>
<pre><code>int *customer_table; //All the info about the customer
</code></pre>
<p>This line of code is in a function not in main.
And I allocate memory for this global array in the main.
What may this cause this problem?</p> | 8,777,392 | 2 | 3 | null | 2012-01-08 12:07:59.05 UTC | 1 | 2012-01-08 12:27:52.85 UTC | 2012-01-08 12:27:52.85 UTC | null | 1,023,815 | null | 1,002,790 | null | 1 | 2 | c|arrays|pointers | 43,455 | <p>You're declaring a <code>pointer-to-int</code>. So <code>cutomer_table[x]</code> is an int, not a pointer. If you need a two-dimensional, dynamically allocated array, you'll need a:</p>
<pre><code>int **customer_table;
</code></pre>
<p>and you'll need to be very careful with the allocation.</p>
<p>(See e.g. <a href="https://stackoverflow.com/questions/2614249/dynamic-memory-for-2d-char-array">dynamic memory for 2D char array</a> for examples.)</p> |
5,078,752 | Magento ->addCategoryFilter - filtering product collection by root category | <p>Concerning the use of the <strong>->addCategoryFilter</strong> on a product collection. Why is it not possible to filter by the root category? I have 2 stores, both with different root categories. I want to show a list of best-selling products on my homepage. But I can't filter the products by the root category, only sub-categories under that. </p>
<p>So, on my homepage, all products from both stores show up. I can filter ok by any sub-categories. For example, my second root category has an ID of 35. If I try to filter by this, I get every product from both roots. But the first sub-category under that root is ID 36, and filtering by this works correctly, showing only those products. My call is as follows (simplified):</p>
<pre><code>$_category = Mage::getModel('catalog/category')->load(35);
$_testproductCollection = Mage::getResourceModel('catalog/product_collection')
->addCategoryFilter($_category)
->addAttributeToSelect('*');
$_testproductCollection->load();
foreach($_testproductCollection as $_testproduct){
echo $this->htmlEscape($_testproduct->getName())."<br/>";
};
</code></pre>
<p>Anyone know why this isn't working? Or is there some other way to filter by the root category?</p>
<p><strong>UPDATE:</strong>
I still haven't had any luck with this. Seems very buggy - adding a category filter using the root category only works sometimes, you need to add all products to the root, then save, then remove any that shouldn't be in that root cat, then re-save. But if you re-index you get all products showing again. If I output the sql query from my above collection call I get the following:</p>
<pre><code>SELECT `e`.*, `cat_index`.`position` AS `cat_index_position`, `price_index`.`price`, `price_index`.`tax_class_id`, `price_index`.`final_price`, IF(`price_index`.`tier_price`, LEAST(`price_index`.`min_price`, `price_index`.`tier_price`), `price_index`.`min_price`) AS `minimal_price`, `price_index`.`min_price`, `price_index`.`max_price`, `price_index`.`tier_price` FROM `catalog_product_entity` AS `e` INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id='2' AND cat_index.category_id='35' INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0
</code></pre>
<p>As you can see, the category is listed there, so why doesn't the filter work?</p> | 8,480,433 | 5 | 1 | null | 2011-02-22 13:29:03.257 UTC | 2 | 2014-06-24 18:43:39.82 UTC | 2011-03-21 16:25:57.527 UTC | null | 161,056 | null | 161,056 | null | 1 | 6 | magento | 67,464 | <p>OK, I think this works, haven't tested too much but seems to have done the trick. You need to first get your stores root category id, then join some fields so you have access to the products "category_id", then filter using that:</p>
<pre><code>$_rootcatID = Mage::app()->getStore()->getRootCategoryId();
$_testproductCollection = Mage::getResourceModel('catalog/product_collection')
->joinField('category_id','catalog/category_product','category_id','product_id=entity_id',null,'left')
->addAttributeToFilter('category_id', array('in' => $_rootcatID))
->addAttributeToSelect('*');
$_testproductCollection->load();
foreach($_testproductCollection as $_testproduct){
echo $this->htmlEscape($_testproduct->getName())."<br/>";
};
</code></pre> |
4,844,498 | Rails 3 Finding day of week | <p>I'm trying to make my own calendar because i cant seem to get any help with event calendar so what im trying to do is Display the day of the week ie.. January 1 2011 is a Saturday is there an easy command to get that day or do i need something else </p> | 4,844,526 | 6 | 0 | null | 2011-01-30 17:58:19.52 UTC | 8 | 2021-10-04 09:45:29.42 UTC | null | null | null | null | 570,483 | null | 1 | 72 | ruby-on-rails-3 | 53,754 | <p>Can't you use <a href="http://www.ruby-doc.org/core/classes/Time.html#M000369" rel="noreferrer">time.wday</a>, 0 = sunday and so on</p> |
5,009,096 | Files showing as modified directly after a Git clone | <p>I'm having an issue with a repository at the moment, and though my Git-fu is usually good, I can't seem to solve this issue.</p>
<p>When I clone this repository, then <code>cd</code> into the repository, <code>git status</code> shows several files as changed. Note: I haven't opened the repository in any editor or anything.</p>
<p>I tried following this guide: <a href="http://help.github.com/dealing-with-lineendings/" rel="noreferrer">http://help.github.com/dealing-with-lineendings/</a>, but this didn't help at all with my issue.</p>
<p>I have tried <code>git checkout -- .</code> many times, but it seems not to do anything.</p>
<p>I'm on a Mac, and there are no submodules in the repository itself.</p>
<p>The filesystem is "Journaled HFS+" filesystem on the Mac and is not case-sensitive. The files are one-line and about 79 KB each (yes, you heard right), so looking at <code>git diff</code> isn't particularly helpful. I have heard about doing <code>git config --global core.trustctime false</code> which might help, which I will try when I get back to the computer with the repository on it.</p>
<p>I changed details of filesystem with facts! And I tried the <code>git config --global core.trustctime false</code> trick which didn't work very well.</p> | 5,022,417 | 19 | 0 | null | 2011-02-15 20:24:49.883 UTC | 73 | 2021-04-22 14:33:35.797 UTC | 2019-04-23 20:06:15.703 UTC | null | 63,550 | null | 261,393 | null | 1 | 254 | git|git-clone | 110,603 | <p>I got it. All the other developers are on Ubuntu (I think) and thus have case-sensitive file systems. I, however, do not (as I'm on a Mac). Indeed, all the files had lowercase twins when I took a look at them using <code>git ls-tree HEAD <path></code>.</p>
<p>I'll get one of them to sort it out.</p> |
29,625,912 | Draw custom line between two elements in TableLayout Android | <p>I have an activity with events organised in a timeline. But it looks ugly. </p>
<p><img src="https://i.stack.imgur.com/SOsdI.png" alt="enter image description here"></p>
<p>I want to design a more beautiful timeline like this one.
<img src="https://i.stack.imgur.com/IJCaV.png" alt="enter image description here"></p>
<p>Is there any simple way or a library to draw lines between elements like in my example?</p>
<pre><code><ScrollView
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="@+id/text_data"
android:layout_above="@+id/button_trimite"
android:id="@+id/scroll_timeline"
android:layout_marginBottom="7dp"
>
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/timelineTable"
>
</TableLayout>
</ScrollView>
</code></pre>
<p>This is my xml. But my TableLayout is generated dynamically because I need to sort my events.</p>
<pre><code>for (final Event e : events) {
if(e.getDate().equals(dataComp)) {
//tablerow with event entry
final TableRow row = new TableRow(getActivity());
row.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
if (indexForDrawable % 2 == 0)
row.setBackgroundResource(R.drawable.marcaj_event_albastru);
else
row.setBackgroundResource(R.drawable.marcaj_event_portocaliu);
TextView txtEvent = new TextView(getActivity());
txtEvent.setText(" "+ e.getHour() +"-"+e.getType()+"-"+e.getTitle());
txtEvent.setTextColor(Color.BLACK);
txtEvent.setTextSize(TypedValue.COMPLEX_UNIT_DIP, trEvent);
txtEvent.setTypeface(Typeface.create(tf, Typeface.BOLD));
row.addView(txtEvent);
row.setClickable(true);
final String date = e.getDate(), hour = e.getHour(), title = e.getTitle(),
type = e.getType(), descriere = e.getDescriere();
final int finalResource = resource;
final int finalIndexForDrawable = indexForDrawable;
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
row.setBackground(getActivity().getResources().getDrawable(finalResource));
showPopup2(date, hour, type, title, descriere, row, finalIndexForDrawable);
}
});
timelineTable.addView(row, new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
indexForDrawable++;
}
else {
//tablerow with date
final TableRow row = new TableRow(getActivity());
row.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
TextView txtEvent = new TextView(getActivity());
</code></pre>
<p>// txtEvent.setText("\n" + dataSplit1[0]+months.indexOf(dataSplit1<a href="https://i.stack.imgur.com/SOsdI.png" rel="nofollow noreferrer">1</a>));
txtEvent.setText("\n" + e.getDate().substring(0, 5));
txtEvent.setTextSize(TypedValue.COMPLEX_UNIT_DIP, trDate);
row.addView(txtEvent);
timelineTable.addView(row, new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
dataComp = e.getDate();</p>
<pre><code> //tablerow with event entry
final TableRow row3 = new TableRow(getActivity());
row3.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
if (indexForDrawable % 2 == 0)
row3.setBackgroundResource(R.drawable.marcaj_event_albastru);
else
row3.setBackgroundResource(R.drawable.marcaj_event_portocaliu);
TextView txtEvent3 = new TextView(getActivity());
txtEvent3.setText(" "+ e.getHour() +"-"+e.getType()+"-"+e.getTitle());
txtEvent3.setTextColor(Color.BLACK);
txtEvent3.setTextSize(TypedValue.COMPLEX_UNIT_DIP, trEvent);
txtEvent3.setTypeface(Typeface.create(tf, Typeface.BOLD));
row3.addView(txtEvent3);
row3.setClickable(true);
final String date3 = e.getDate(), hour3 = e.getHour(), title3 = e.getTitle(),
type3 = e.getType(), descriere3 = e.getDescriere();
timelineTable.addView(row3, new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
indexForDrawable++;
}
</code></pre> | 29,627,491 | 2 | 9 | null | 2015-04-14 11:14:00.833 UTC | 9 | 2016-09-19 01:30:20.1 UTC | 2015-04-14 11:37:48.05 UTC | null | 4,506,376 | null | 4,506,376 | null | 1 | 4 | android|timeline | 7,557 | <p>You may have to create your own <strong>custom adapter</strong> but I am using array adapter for your reference. Also giving item layout for list view, hope you will manage your <strong>code</strong> accordingly.</p>
<p><img src="https://i.stack.imgur.com/mCBrO.png" alt="list-items"></p>
<p><strong>items.xml</strong></p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<View
android:layout_width="2dp"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:background="@android:color/black" />
<View
android:id="@+id/view1"
android:layout_width="7dp"
android:layout_height="7dp"
android:layout_centerVertical="true"
android:layout_marginLeft="7dp"
android:background="@drawable/dot" />
</RelativeLayout>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:padding="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</code></pre>
<p><strong>dot.xml</strong> which is a drawable</p>
<pre><code><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<stroke
android:width="1dp"
android:color="@android:color/black" />
<solid android:color="@android:color/white" />
</code></pre>
<p></p>
<p>And in acivity you can use adapter like this:</p>
<pre><code>list.setAdapter(new ArrayAdapter<String>(this, R.layout.item, R.id.textView1, items));
</code></pre>
<p>Hope this helped!</p> |
12,343,187 | Should I run Tomcat by itself or Apache + Tomcat? | <p>I was wondering if it would be okay to run Tomcat as both the web server and container? On the other hand, it seems that the right way to go about scaling your webapp is to use Apache HTTP listening on port 80 and connecting that to Tomcat listening on another port?
Are both ways acceptable? What is being used nowdays? Whats the prime difference? How do most major websites go about this?</p>
<p>Thanks.</p> | 12,343,443 | 2 | 0 | null | 2012-09-09 21:35:01.567 UTC | 9 | 2012-09-09 22:16:28.303 UTC | null | null | null | null | 560,204 | null | 1 | 11 | apache|tomcat | 7,658 | <p>Placing an Apache (or any other webserver) in front of your application server(s) (Tomcat) is a good thing for a number of reasons.</p>
<p>First consideration is about static resources and caching. </p>
<p>Tomcat will probably serve also a lot of static content, or even on dynamic content it will send some caching directives to browsers. However, each browser that hits your tomcat for the first time will cause tomcat to send the static file. Since processing a request is a bit more expensive in Tomcat than it is in Apache (because of Apache being super-optimized and exploiting very low level stuff not always available in Tomcat, because Tomcat extracting much more informations from the request than Apache needs etc...), it may be better for the static files to be server by Apache.</p>
<p>Since however configuring Apache to serve part of the content and Tomcat for the rest or the URL space is a daunting task, it is usually easier to have Tomcat serve everything with the right cache headers, and Apache in front of it capturing the content, serving it to the requiring browser, and caching it so that other browser hitting the same file will get served directly from Apache without even disturbing Tomcat.</p>
<p>Other than static files, also many dynamic stuff may not need to be updated every millisecond. For example, a json loaded by the homepage that tells the user how much stuff is in your database, is an expensive query performed thousands of times that can safely be performed each hour or so without making your users angry. So, tomcat may serve the json with proper one hour caching directive, Apache will cache the json fragment and serve it to any browser requiring it for one hour. There are obviously a ton of other ways to implement it (a caching filter, a JPA cache that caches the query etc...), but sending proper cache headers and using Apache as a reverse proxy is quite easy, REST compliant and scales well. </p>
<p>Another consideration is load balancing. Apache comes with a nice load balancing module, that can help you scale your application on a number of Tomcat instances, supposed that your application can scale horizontally or run on a cluster.</p>
<p>A third consideration is about ulrs, headers etc.. From time to time you may need to change some urls, or remove or override some headers. For example, before a major update you may want to disable caching on browsers for some hours to avoid browsers keep using stale data (same as lowering the DNS TTL before switching servers), or move the old application on another url space, or rewrite old URLs to new ones when possible. While reconfiguring the servlets inside your web.xml files is possible, and filters can do wonders, if you are using a framework that interprets the URLs you may need to do a lot of work on your sitemap files or similar stuff.</p>
<p>Having Apache or another web server in front of Tomcat may help a lot changing only Apache configuration files with modules like mod_rewrite. </p>
<p>So, I always recommend having Apache httpd in front of Tomcat. The small overhead on connection handling is usually recovered thanks to caching of resources, and the additional configuration works is regained the first time you need to move URLs or handle some headers.</p> |
12,350,413 | Google maps auto-fit (auto center & autozoom) doesn't work | <p>I have a problem with a map on which I've used the <code>fitBounds</code> map methods, which should give the proper zoom and center the map giving it a latlon array. here's the code:</p>
<pre><code><script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<div id="map_canvas">
<script type="text/javascript">
var map;
var bounds = new google.maps.LatLngBounds(null);
function initialize() {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
<?php
foreach ($this->getProductCollection() as $_e):
$event = Mage::getModel('catalog/product')->load($_e->getId());
?>
var loc = new google.maps.LatLng("<?php echo $event->getEventLocationLatitude(); ?>","<?php echo $event->getEventLocationLongitude(); ?>");
bounds.extend(loc);
addMarker(loc, '<?php echo $event->getName(); ?>', "active");
bounds.extend(loc);
<?php endforeach; ?>
map.fitBounds(bounds);
map.panToBounds(bounds);
}
function addMarker(location, name, active) {
var marker = new google.maps.Marker({
position: location,
map: map,
title: name,
status: active
});
}
jQuery.noConflict();
jQuery(document).ready(function(){
initialize();
});
</script>
</code></pre>
<p></p>
<p>The markers are correctly placed on the map, but I get the maximum zoom available:</p>
<p><img src="https://i.stack.imgur.com/nrnvm.png" alt="enter image description here"></p>
<p>Any help?</p> | 12,351,178 | 1 | 2 | null | 2012-09-10 11:09:08.453 UTC | 6 | 2016-02-04 04:37:00.543 UTC | 2016-02-04 04:37:00.543 UTC | null | 2,405,040 | null | 998,967 | null | 1 | 19 | javascript|google-maps|google-maps-api-3|google-maps-markers | 40,906 | <p>I've updated your fiddle here: <a href="http://jsfiddle.net/KwayW/1/" rel="noreferrer">http://jsfiddle.net/KwayW/1/</a></p>
<p>It works now as expected.</p>
<p>Here's the full code (save this as test.html and open in browser):</p>
<pre><code><style>#map_canvas { width:500px; height: 400px; }</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<div id="map_canvas"></div>
<script>
var map;
var markersArray = [];
var image = 'img/';
var bounds = new google.maps.LatLngBounds();
var loc;
function init(){
var mapOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
loc = new google.maps.LatLng("45.478294","9.123949");
bounds.extend(loc);
addMarker(loc, 'Event A', "active");
loc = new google.maps.LatLng("50.83417876788752","4.298325777053833");
bounds.extend(loc);
addMarker(loc, 'Event B', "active");
loc = new google.maps.LatLng("41.3887035","2.1807378");
bounds.extend(loc);
addMarker(loc, 'Event C', "active");
map.fitBounds(bounds);
map.panToBounds(bounds);
}
function addMarker(location, name, active) {
var marker = new google.maps.Marker({
position: location,
map: map,
title: name,
status: active
});
}
$(function(){ init(); });
</script>
</code></pre> |
12,152,519 | Removing XML Nodes using XSLT | <p>I have the following XML:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Rowsets>
<Rowset>
<Columns>
<Column Description="FirstName" MaxRange="1" MinRange="0" Name="FirstName" SQLDataType="12" SourceColumn="FirstName"/>
<Column Description="LastName" MaxRange="1" MinRange="0" Name="LastName" SQLDataType="12" SourceColumn="LastName"/>
<Column Description="Phone" MaxRange="1" MinRange="0" Name="Phone" SQLDataType="1" SourceColumn="Phone"/>
</Columns>
<Row>
<FirstName>Michael</FirstName>
<LastName>David</LastName>
<Phone>1234567890</Phone>
</Row>
<Row>
<FirstName>David</FirstName>
<LastName>Michael</LastName>
<Phone>01234567890</Phone>
</Row>
<Row>
<FirstName>Yang</FirstName>
<LastName>Christina</LastName>
<Phone>2345678901</Phone>
</Row>
<Row>
<FirstName>Grey</FirstName>
<LastName>Meredith</LastName>
<Phone>3456789012</Phone>
</Row>
<Row>
<FirstName>David</FirstName>
<LastName>Shepherd</LastName>
<Phone>5678901234</Phone>
</Row>
</Rowset>
</code></pre>
<p></p>
<p>I want to remove <code><Phone></code> node from every Row as well as from Column description.</p>
<p>SO my resultant XML would look like following:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Rowsets>
<Rowset>
<Columns>
<Column Description="FirstName" MaxRange="1" MinRange="0" Name="FirstName" SQLDataType="12" SourceColumn="FirstName"/>
<Column Description="LastName" MaxRange="1" MinRange="0" Name="LastName" SQLDataType="12" SourceColumn="LastName"/>
</Columns>
<Row>
<FirstName>Michael</FirstName>
<LastName>David</LastName>
</Row>
<Row>
<FirstName>David</FirstName>
<LastName>Michael</LastName>
</Row>
<Row>
<FirstName>Yang</FirstName>
<LastName>Christina</LastName>
</Row>
<Row>
<FirstName>Grey</FirstName>
<LastName>Meredith</LastName>
</Row>
<Row>
<FirstName>David</FirstName>
<LastName>Shepherd</LastName>
</Row>
</Rowset>
</code></pre>
<p></p>
<p>How do I achieve that? I tried various XSLT but I am not able to do it.</p> | 12,152,983 | 1 | 0 | null | 2012-08-28 03:51:23.963 UTC | 2 | 2016-04-12 13:25:55.803 UTC | 2016-04-12 13:25:55.803 UTC | null | 105,672 | null | 1,481,396 | null | 1 | 22 | xml|xslt | 40,615 | <pre><code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Column[@SourceColumn='Phone']|Phone" />
</xsl:stylesheet>
</code></pre> |
12,236,533 | Migrating from ASP.NET Membership to SimpleMembership in MVC4 RTM | <p>The new MVC4 RTM internet application templates use the SimpleMembership providers as descibed here <a href="http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx/">SimpleMembership</a></p>
<p>My existing MVC website uses the ASP.Membership framework and ideally I would like to migrate the user data in these tables to the new SimpleMembership tables. My reasons for wanting to do this are: </p>
<ol>
<li>Cleaner integration with the rest of the my database which uses EF</li>
<li>Support for Azure and OAuth out of the box</li>
<li>Use latest MVC4 RTM Controllers/Views without needing to modify</li>
<li>I've always felt the existing membership implementation was a little bloated for what I needed</li>
</ol>
<p>So I wrote a SQL script today to migrate the data in the existing ASP.Net Membership tables into the new Simple Membership tables. This can be found <a href="http://gist.github.com/3585239">here</a></p>
<p>Testing the login in my MVC 4 website the password verification is failing. I believe the SimpleMembership uses a different password algo than the old Membership framework as new passwords created under the SimpleMemberShip framework look a lot longer.</p>
<p>So my question is since I was using the "hashed" password format in the old ASP.Net membership providers and the users original password is irretrievable, what options do I have to get the SimpleMembership provider working.</p>
<p>I guessing some options are:</p>
<ol>
<li>Get my users to reset their passwords</li>
<li>Getting the SimpleMembership provider to use the same password algo as the old ASP.Net Membership providers.</li>
<li>Revert the new MVC 4 RTM internet application templates to use the old ASP.Net MemberShip providers. This is the least desirable options for me as I would like to use the SimpleMemberShip framework.</li>
</ol>
<p>I would suspect many people are also looking to migrate their existing membership databases to the new SimpleMemberShip provider.</p>
<p>Any help greatly appreciated.</p>
<p>Cheers</p>
<p>Jim </p> | 13,446,014 | 3 | 2 | null | 2012-09-02 13:56:26.73 UTC | 16 | 2015-09-24 04:47:07.91 UTC | null | null | null | null | 409,176 | null | 1 | 27 | asp.net|asp.net-mvc|asp.net-mvc-3|asp.net-membership|asp.net-mvc-4 | 11,189 | <p>I'd like to surface Paul's comment in case anyone misses it and suggest his solution is the best I've seen. </p>
<p><a href="http://pretzelsteelersfan.blogspot.com/2012/11/migrating-legacy-apps-to-new.html">http://pretzelsteelersfan.blogspot.com/2012/11/migrating-legacy-apps-to-new.html</a></p>
<p>Thanks Paul</p> |
12,145,772 | Do nullable columns occupy additional space in PostgreSQL? | <p>I have a table with 7 columns and 5 of them will be null. I will have a null columns on <code>int</code>, <code>text</code>, <code>date</code>, <code>boolean</code>, and <code>money</code> data types. This table will contain millions of rows with many many nulls. I am afraid that the null values will occupy space.</p>
<p>Also, do you know if Postgres indexes null values? I would like to prevent it from indexing nulls.</p> | 12,147,130 | 3 | 0 | null | 2012-08-27 16:23:06.137 UTC | 9 | 2020-08-21 01:54:54.817 UTC | 2014-12-15 01:52:04.94 UTC | null | 939,860 | null | 184,773 | null | 1 | 29 | postgresql|database-design|indexing|null | 9,055 | <p>Basically, <code>NULL</code> values occupy <strong>1 bit</strong> in the NULL bitmap. But it's not that simple.</p>
<p>The <strong>null bitmap</strong> (per row) is only allocated if at least one column in that row holds a <code>NULL</code> value. This can lead to a seemingly paradoxic effect in tables with 9 or more columns: assigning the first <code>NULL</code> value to a column can take up more space on disk than writing a value to it. Conversely, removing the last NULL value from the row also removes the NULL bitmap.</p>
<p>Physically, the initial null bitmap occupies <strong>1 byte</strong> between the <code>HeapTupleHeader</code> (23 bytes) and actual column data or the row <code>OID</code> (if you should still be using that) - which <em>always</em> start at a multiple of <code>MAXALIGN</code> (typically <strong>8 bytes</strong>). This leaves <em>1 byte</em> of padding that is utilized by the initial null bitmap.</p>
<p>In effect, <strong>NULL storage is absolutely free for tables of 8 columns or less</strong> (including dropped, but not yet purged columns).<br />
After that, another <code>MAXALIGN</code> bytes (typically 8) are allocated for the next <code>MAXALIGN * 8</code> columns (typically 64). Etc.</p>
<p>More details <a href="https://www.postgresql.org/docs/current/storage-page-layout.html" rel="noreferrer">in the manual</a> and under these related questions:</p>
<ul>
<li><a href="https://stackoverflow.com/q/4229805">How much disk-space is needed to store a NULL value using postgresql DB?</a></li>
<li><a href="https://stackoverflow.com/q/5008753">Does not using NULL in PostgreSQL still use a NULL bitmap in the header?</a></li>
<li><a href="https://stackoverflow.com/q/10885706">How many records can I store in 5 MB of PostgreSQL on Heroku?</a></li>
</ul>
<p>Once you understand alignment padding of data types, you can further optimize storage:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/2966524/calculating-and-saving-space-in-postgresql/7431468#7431468">Calculating and saving space in PostgreSQL</a></li>
</ul>
<p>But the cases are rare where you can save substantial amounts of space. Normally it's not worth the effort.</p>
<p><a href="https://stackoverflow.com/a/12146452/939860">@Daniel</a> already covers effects on index size.</p>
<p><strong>Note</strong> that <strong>dropped columns</strong> (though now invisible) are kept in the system catalogs until the table is recreated. Those zombis can force the allocation of an (enlarged) NULL bitmap. See:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/15699989/dropping-column-in-postgres-on-a-large-dataset/15700213#15700213">Dropping column in Postgres on a large dataset</a></li>
</ul> |
12,594,541 | NPM global install "cannot find module" | <p>I wrote a module which I published to npm a moment ago (https://npmjs.org/package/wisp)</p>
<p>So it installs fine from the command line:</p>
<p><code>$ npm i -g wisp</code></p>
<p>However, when I run it from the command line, I keep getting an error that optimist isn't installed:</p>
<pre><code>$ wisp
Error: Cannot find module 'optimist'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/usr/local/lib/node_modules/wisp/wisp:12:10)
at Object.<anonymous> (/usr/local/lib/node_modules/wisp/wisp:96:4)
at Module._compile (module.js:449:26)
at Object.exports.run (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:68:25)
at compileScript (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/command.js:135:29)
at fs.stat.notSources.(anonymous function) (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/command.js:110:18)
</code></pre>
<p>However, I have specified in package.json as a dependancy:</p>
<pre><code>{
"name": "wisp",
"author": "Brendan Scarvell <[email protected]>",
"version": "0.1.0",
"description": "Global nodejs file server",
"dependencies": {
"optimist": "~0.3.4"
},
"repository": "git://github.com/tehlulz/wisp",
"bin": {
"wisp" : "./wisp"
}
}
</code></pre>
<p>Does anyone know what to do to get this running? I know its to do with the bin part adding the executable to bin and the node_modules in that directory being empty. No idea how to resolve this.</p> | 14,515,868 | 19 | 8 | null | 2012-09-26 04:25:59 UTC | 65 | 2021-12-29 01:26:58.093 UTC | 2012-09-26 07:44:51.65 UTC | null | 1,258,398 | null | 1,258,398 | null | 1 | 237 | node.js|npm | 342,927 | <p>For anyone else running into this, I had this problem due to my <code>npm</code> installing into a location that's not on my <code>NODE_PATH</code>.</p>
<pre><code>[root@uberneek ~]# which npm
/opt/bin/npm
[root@uberneek ~]# which node
/opt/bin/node
[root@uberneek ~]# echo $NODE_PATH
</code></pre>
<p>My NODE_PATH was empty, and running <code>npm install --global --verbose promised-io</code> showed that it was installing into <code>/opt/lib/node_modules/promised-io</code>:</p>
<pre><code>[root@uberneek ~]# npm install --global --verbose promised-io
npm info it worked if it ends with ok
npm verb cli [ '/opt/bin/node',
npm verb cli '/opt/bin/npm',
npm verb cli 'install',
npm verb cli '--global',
npm verb cli '--verbose',
npm verb cli 'promised-io' ]
npm info using [email protected]
npm info using [email protected]
[cut]
npm info build /opt/lib/node_modules/promised-io
npm verb from cache /opt/lib/node_modules/promised-io/package.json
npm verb linkStuff [ true, '/opt/lib/node_modules', true, '/opt/lib/node_modules' ]
[cut]
</code></pre>
<p>My script fails on <code>require('promised-io/promise')</code>:</p>
<pre><code>[neek@uberneek project]$ node buildscripts/stringsmerge.js
module.js:340
throw err;
^
Error: Cannot find module 'promised-io/promise'
at Function.Module._resolveFilename (module.js:338:15)
</code></pre>
<p>I probably installed node and npm from source using <code>configure --prefix=/opt</code>. I've no idea why this has made them incapable of finding installed modules. The fix for now is to point NODE_PATH at the right directory:</p>
<pre><code>export NODE_PATH=/opt/lib/node_modules
</code></pre>
<p>My <code>require('promised-io/promise')</code> now succeeds.</p> |
3,623,754 | What are the different techniques for memoization in Java? | <p>I know of this one <a href="http://onjava.com/pub/a/onjava/2003/08/20/memoization.html" rel="noreferrer">http://onjava.com/pub/a/onjava/2003/08/20/memoization.html</a> but is there anything else?</p> | 3,624,099 | 3 | 1 | null | 2010-09-02 04:08:27.16 UTC | 17 | 2017-06-26 10:25:52.073 UTC | 2012-06-13 12:32:11.493 UTC | null | 1,135,954 | null | 437,552 | null | 1 | 24 | java|memoization | 20,355 | <p>Memoization is also easy with plain simple typesafe Java.</p>
<p>You can do it from scratch with the following reusable classes.</p>
<p>I use these as caches whose lifespan are the request on a webapp.</p>
<p>Of course use the Guava <code>MapMaker</code> if you need an eviction strategy or more features like synchronization. </p>
<p>If you need to memoize a method with many parameters, just put the parameters in a list with both techniques, and pass that list as the single parameter.</p>
<pre><code>abstract public class Memoize0<V> {
//the memory
private V value;
public V get() {
if (value == null) {
value = calc();
}
return value;
}
/**
* will implement the calculation that
* is to be remembered thanks to this class
*/
public abstract V calc();
}
abstract public class Memoize1<P, V> {
//The memory, it maps one calculation parameter to one calculation result
private Map<P, V> values = new HashMap<P, V>();
public V get(P p) {
if (!values.containsKey(p)) {
values.put(p, calc(p));
}
return values.get(p);
}
/**
* Will implement the calculations that are
* to be remembered thanks to this class
* (one calculation per distinct parameter)
*/
public abstract V calc(P p);
}
</code></pre>
<p>And this is used like this </p>
<pre><code> Memoize0<String> configProvider = new Memoize0<String>() {
@Override
public String calc() {
return fetchConfigFromVerySlowDatabase();
}
};
final String config = configProvider.get();
Memoize1<Long, String> usernameProvider = new Memoize1<Long, String>() {
@Override
public String calc(Long id) {
return fetchUsernameFromVerySlowDatabase(id);
}
};
final String username = usernameProvider.get(123L);
</code></pre> |
3,486,055 | Android find GPS location once, show loading dialog | <p>I am writing an app that requires the user's current location (lastknownlocation won't be very helpful) and displays a list of all the closest "items" to them taken from the database.</p>
<p>I have got the finding of the closest items working well but only using a hardcoded latitude and longitude location for the time being but now it is time to implement finding the actual location.</p>
<p>Can anyone provide an example of how to have the app find the current fine location in the background and have the app wait. I only need the location once not updates as the person moves. I have implemented a location listener however I understand getting a GPS fix can be slow. I have seen other examples using last known location or implementing the location listener which continues to run and update however as my Activity needs the location coordinates before it can display anything the app just crashes. I need to show a Progress Dialog while its searching.</p>
<p>How can I have the locationlistener run once in the background and then remove location updates once it finds the location. I need the rest of the application to wait until it has a GPS location or timeout after say 20-30seconds. I would like a ProgressDialog up so the user knows that something is going on, but it just has to be the spinning loading animation not a percentage or anything. If possible I would like the user to be able to cancel the dialog if they are sick of waiting which then they can search by typing suburb etc instead.</p>
<p>I have been trying to do it with threads but it is getting way more complicated than I feel it should be and still not working anyway. On iPhone this is much more simple?</p>
<p>Can anyone provide a nice way of doing this, I have been ripping my hair out for a week on this and it is really putting me behind schedule for the rest of the app completion date.</p>
<p>In summary I want to:<br>
* Find current coordinates<br>
* Show Progress Dialog while getting location<br>
* Have app be able to wait for successful location or give up after a certain time?<br>
* If Successful: Dismiss Progress Dialog and use coordinates to run my other methods for finding items closeby.<br>
* If Failed to get location: Dismiss Progress Dialog and show error message, and encourage user to use menu to go to Search Activity.<br>
* Use these coordinates if the user chooses map view from the menu, to show current location on the map and pins dropped at all the nearby items by using their coordinates from the database.</p>
<p>Thanks guys, I hope I have explained myself well enough. Any questions just ask, I will be checking back regularly as I am keen to get this part completed.
Cheers</p>
<p><strong>EDIT</strong><br>
Code as requested</p>
<p><strong>locationList activity file</strong> </p>
<pre><code>protected void onStart()
{
super.onStart();
// ....
new LocationControl().execute(this);
}
private class LocationControl extends AsyncTask<Context, Void, Void>
{
private final ProgressDialog dialog = new ProgressDialog(branchAtmList.this);
protected void onPreExecute()
{
this.dialog.setMessage("Determining your location...");
this.dialog.show();
}
protected Void doInBackground(Context... params)
{
LocationHelper location = new LocationHelper();
location.getLocation(params[0], locationResult);
return null;
}
protected void onPostExecute(final Void unused)
{
if(this.dialog.isShowing())
{
this.dialog.dismiss();
}
useLocation(); //does the stuff that requires current location
}
}
public LocationResult locationResult = new LocationResult()
{
@Override
public void gotLocation(final Location location)
{
currentLocation = location;
}
};
</code></pre>
<p><strong>LocationHelper class</strong> </p>
<pre><code> package org.xxx.xxx.utils;
import java.util.Timer;
/*
imports
*/
public class LocationHelper
{
LocationManager locationManager;
private LocationResult locationResult;
boolean gpsEnabled = false;
boolean networkEnabled = false;
public boolean getLocation(Context context, LocationResult result)
{
locationResult = result;
if(locationManager == null)
{
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
//exceptions thrown if provider not enabled
try
{
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch (Exception ex) {}
try
{
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch (Exception ex) {}
//dont start listeners if no provider is enabled
if(!gpsEnabled && !networkEnabled)
{
return false;
}
if(gpsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
GetLastLocation();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location)
{
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extra) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location)
{
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extra) {}
};
private void GetLastLocation()
{
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
Location gpsLocation = null;
Location networkLocation = null;
if(gpsEnabled)
{
gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(networkEnabled)
{
networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
//if there are both values use the latest one
if(gpsLocation != null && networkLocation != null)
{
if(gpsLocation.getTime() > networkLocation.getTime())
{
locationResult.gotLocation(gpsLocation);
}
else
{
locationResult.gotLocation(networkLocation);
}
return;
}
if(gpsLocation != null)
{
locationResult.gotLocation(gpsLocation);
return;
}
if(networkLocation != null)
{
locationResult.gotLocation(networkLocation);
return;
}
locationResult.gotLocation(null);
}
public static abstract class LocationResult
{
public abstract void gotLocation(Location location);
}
}
</code></pre>
<p>This really seems like a big effort just to get the current location once? I do not require updates or anything? Is there not a simpler way of having the application wait for a result? I have been stuck on this for so long.</p> | 3,486,245 | 3 | 1 | null | 2010-08-15 03:15:30.61 UTC | 17 | 2011-09-15 05:24:33.31 UTC | 2011-09-07 15:03:59.817 UTC | null | 387,317 | null | 387,317 | null | 1 | 26 | android|gps|progressdialog|locationlistener | 43,849 | <p>Use an <strong>AsyncTask</strong> and use <strong>both network_provider as well as gps_provider</strong>, which means two listeners. gps takes longer to get a fix, maybe sometimes a minute and only works outdoors, while network gets a location pretty fast.</p>
<p>A good code example is here: <a href="https://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-in-an/3145655#3145655">What is the simplest and most robust way to get the user's current location on Android?</a></p>
<p>For AsyncTask, look <a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="nofollow noreferrer">http://developer.android.com/reference/android/os/AsyncTask.html</a></p>
<p>There are also many code example here on SO for it, for example here:
<a href="https://stackoverflow.com/questions/3430987/android-show-a-dialog-until-a-thread-is-done-and-then-continue-with-the-program/3431028#3431028">Android Show a dialog until a thread is done and then continue with the program</a></p>
<p>EDIT:
code concept:</p>
<p>add class variable</p>
<pre><code>boolean hasLocation = false;
</code></pre>
<p>call in onCreate (not in AsyncTask):</p>
<pre><code>locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
</code></pre>
<p>then in locationListener.onLocationChanged, change the value once a location is found:</p>
<pre><code>boolean hasLocation = false;
</code></pre>
<p>AsyncTask:
leave as it is, but <strong>don't call</strong> </p>
<pre><code>LocationHelper location = new LocationHelper();
location.getLocation(params[0], locationResult);
</code></pre>
<p>there, instead do </p>
<pre><code>Long t = Calendar.getInstance().getTimeInMillies();
while (!hasLocation && Calendar.getInstance().getTimeInMillies()-t<30000)) {
Thread.Sleep(1000);
};
</code></pre>
<p>probably with a delay in between would be sufficient.</p> |
3,465,377 | what's the use of string.Clone()? | <p>there are 2 examples of code:
# 1</p>
<pre><code> string str1 = "hello";
string str2 = str1; //reference to the same string
str1 = "bye"; //new string created
</code></pre>
<p>and # 2</p>
<pre><code>string str3 = "hello";
string str4 = (string)str3.Clone();//reference to the same string
str3 = "bye";//new string created
</code></pre>
<p>looks like they are identical aren't they? so what is the benefit to use Clone()? can you give me an example when I cannot use code#1 but code#2 ?</p> | 3,465,401 | 3 | 0 | null | 2010-08-12 06:59:49.937 UTC | 2 | 2020-10-23 17:10:17.083 UTC | 2010-08-13 07:57:24.963 UTC | null | 352,898 | null | 352,898 | null | 1 | 32 | c#|.net|string|.net-2.0 | 20,219 | <p>This is useful since string implements <em>ICloneable</em>, so you can create a copy of clones for a collection of <em>ICloneable</em> items. This is boring when the collection is of strings only, but it's useful when the collection contains multiple types that implement <em>ICloneable</em>.</p>
<p>As for copying a single string it has no use, since it returns by design a reference to itself.</p> |
8,953,424 | How to get the username in C/C++ in Linux? | <p>How can I get the actual "username" without using the environment (<code>getenv</code>, ...) in a program? Environment is C/C++ with Linux.</p> | 8,953,466 | 6 | 13 | null | 2012-01-21 13:39:59.58 UTC | 10 | 2021-07-05 14:01:52.537 UTC | 2021-02-23 13:54:02.823 UTC | null | 5,779,732 | null | 1,162,308 | null | 1 | 43 | c++|c|linux|posix | 105,554 | <p>The function <strong><code>getlogin_r()</code></strong> defined in <code>unistd.h</code> returns the username. See <code>man getlogin_r</code> for more information.</p>
<p>Its signature is:</p>
<pre><code>int getlogin_r(char *buf, size_t bufsize);
</code></pre>
<p>Needless to say, this function can just as easily be called in C or C++.</p> |
20,671,303 | Bootstrap 3 changing div order on small screens only | <p>Doing my 1st responsive design and is something like this possible in Bootstrap 3. Change this
<a href="https://i.stack.imgur.com/lABXp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lABXp.jpg" alt=""></a></p>
<p>To</p>
<p><a href="https://i.stack.imgur.com/nm3ra.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nm3ra.jpg" alt=""></a></p>
<p>Change the order essentially from a 3 column layout on large screens to moving the logo to left and stack the other two columns on smaller screens only. I would like to do it using the Bootstrap classes (col-xs-6 col-md-4 etc.) if possible and not have to duplicate content in a show/hide sort of fashion. I liked the grid layout bootstrap3 provides for large screens so would prefer to keep it if could sort out the layout on smaller screens.</p> | 20,672,273 | 6 | 4 | null | 2013-12-19 00:25:12.093 UTC | 11 | 2020-06-23 07:54:31.913 UTC | 2019-02-02 14:47:35.713 UTC | null | 10,607,772 | null | 589,961 | null | 1 | 22 | css|twitter-bootstrap|sorting|mobile | 73,772 | <h1>DEMO: <a href="http://jsbin.com/uZiKAha/1" rel="noreferrer">http://jsbin.com/uZiKAha/1</a></h1>
<h3>DEMO w/edit: <a href="http://jsbin.com/uZiKAha/1/edit" rel="noreferrer">http://jsbin.com/uZiKAha/1/edit</a></h3>
<p>Yes, this can be done without JS using BS3 nesting and pushing/pulling and all the floats clear:</p>
<pre><code> <div class="container">
<div class="row">
<div class="col-xs-6 col-sm-4 col-sm-push-4 boxlogo">
LOGO
</div>
<div class="col-xs-6 col-sm-8">
<div class="row">
<div class="col-sm-6 col-sm-pull-6 boxb">
B
</div>
<div class="col-sm-6 boxa">
A
</div>
</div>
<!--nested .row-->
</div>
</div>
</div>
</code></pre> |
26,101,774 | How to trim off Image in CSS? | <p>Ok, here is the problem, my app allow users to insert any image. It is up to them insert very big or very long image. But when I rentder image I want the <code>width="50px"</code> and <code>height="100px"</code>.</p>
<p>ok if I do</p>
<pre><code>.myImage{
width:50px;
height:100px;
}
</code></pre>
<p>then the image could be distorted cos the proportion is not accurate. So, here is what I think. First I want the image to have <code>width:50px</code> then if the <code>height>100px</code>, then CSS will trim off the bottom.
Ok, let see this example, user inserted a big image with <code>width=150px</code> and <code>height=600px</code>. So if I reduce the width to <code>50px</code>, the the height will be <code>200px</code>. I want to cut the bottom of the image so it will show only <code>(w: 50px, h: 100px)</code> see the picture:</p>
<p><img src="https://i.stack.imgur.com/RdOR5.png" alt="enter image description here"></p>
<p>So how to do that?</p> | 26,102,029 | 5 | 5 | null | 2014-09-29 14:03:52.203 UTC | 1 | 2014-09-29 14:21:07.677 UTC | null | null | null | null | 2,336,037 | null | 1 | 8 | html|css | 44,013 | <p>1) Trim image with <code><div></code> and <code>overflow:hidden</code>:</p>
<pre><code> div.trim {
max-height:100px;
max-width: 50px;
overflow: hidden;
}
<div class="trim"><img src="veryBigImage.png"/></div>
</code></pre>
<p>2) Use <code>max-width: 50px;</code> and <code>max-height: 100px</code> for image itself. So image will preserve it's dimensions</p> |
48,187,362 | How to iterate using ngFor loop Map containing key as string and values as map iteration | <p>I am new to angular 5 and trying to iterate the map containing another map in typescript.
How to iterate below this kind of map in angular
below is code for component:</p>
<pre><code>import { Component, OnInit} from '@angular/core';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
map = new Map<String, Map<String,String>>();
map1 = new Map<String, String>();
constructor() {
}
ngOnInit() {
this.map1.set("sss","sss");
this.map1.set("aaa","sss");
this.map1.set("sass","sss");
this.map1.set("xxx","sss");
this.map1.set("ss","sss");
this.map1.forEach((value: string, key: string) => {
console.log(key, value);
});
this.map.set("yoyoy",this.map1);
}
}
</code></pre>
<p>and its template html is :</p>
<pre><code><ul>
<li *ngFor="let recipient of map.keys()">
{{recipient}}
</li>
</ul>
<div>{{map.size}}</div>
</code></pre>
<p><a href="https://i.stack.imgur.com/AlXEP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AlXEP.png" alt="runtime error"></a></p> | 48,187,637 | 6 | 6 | null | 2018-01-10 12:19:48.87 UTC | 20 | 2022-07-01 08:58:08.19 UTC | 2020-05-24 13:46:44.48 UTC | null | 2,349,407 | null | 8,744,067 | null | 1 | 160 | javascript|angular|typescript|angular-cli | 172,948 | <p><strong>For Angular 6.1+</strong> , you can use default pipe <strong><a href="https://angular.io/api/common/KeyValuePipe" rel="noreferrer"><code>keyvalue</code></a></strong> ( <a href="https://stackoverflow.com/a/52532564/2349407"><strong>Do review and upvote also</strong></a> ) :</p>
<pre><code><ul>
<li *ngFor="let recipient of map | keyvalue">
{{recipient.key}} --> {{recipient.value}}
</li>
</ul>
</code></pre>
<p><strong><a href="https://stackblitz.com/edit/angular-map-keyvalue" rel="noreferrer">WORKING DEMO</a></strong></p>
<hr>
<p><strong>For the previous version :</strong> </p>
<p>One simple solution to this is convert map to array : <strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from" rel="noreferrer">Array.from</a></strong></p>
<p>Component Side :</p>
<pre><code>map = new Map<String, String>();
constructor(){
this.map.set("sss","sss");
this.map.set("aaa","sss");
this.map.set("sass","sss");
this.map.set("xxx","sss");
this.map.set("ss","sss");
this.map.forEach((value: string, key: string) => {
console.log(key, value);
});
}
getKeys(map){
return Array.from(map.keys());
}
</code></pre>
<p>Template Side :</p>
<pre><code><ul>
<li *ngFor="let recipient of getKeys(map)">
{{recipient}}
</li>
</ul>
</code></pre>
<p><strong><a href="https://stackblitz.com/edit/angular-map-array-from" rel="noreferrer">WORKING DEMO</a></strong></p> |
12,822,420 | iOS: How to use MPMoviePlayerController | <p>I've created a blank project (iOS) and put this in my viewDidLoad:</p>
<pre><code>NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"Movie" ofType:@"m4v"];
MPMoviePlayerViewController *playerController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:moviePath]];
[self presentMoviePlayerViewControllerAnimated:playerController];
[playerController.moviePlayer play];
</code></pre>
<p>When the app starts all I get is a <strong>white screen with error messages in the log</strong>:</p>
<pre><code> <Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextClipToRect: invalid context 0x0
<Error>: CGContextTranslateCTM: invalid context 0x0
<Error>: CGContextDrawShading: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0
Warning: Attempt to present <MPMoviePlayerViewController: 0x821e3b0> on <ViewController: 0x863aa40> whose view is not in the window hierarchy!
</code></pre>
<p>...and a bunch of lines regarding disabling autoplay.
I especially don't understand the line about the view not being part of the hierarchy since it's a blank "Single View Application" iOS project and the code is in ViewController.m. It IS in the view hierarchy.</p>
<p>I know for a fact that the movie file itself is not the problem because I got it from Apple's sample code on MPMoviePlayer. And although I (seemingly) tried everything written in the sample, I just couldn't get the player to work.</p>
<p>Here is another try, this time with MPMoviePlayerController (not MPMoviePlayerViewController):</p>
<pre><code>MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:url];
[player setContentURL:url];
[player setMovieSourceType:MPMovieSourceTypeFile];
[[player view] setFrame:self.view.bounds];
[player view].backgroundColor = [UIColor greenColor];
player.scalingMode = MPMovieScalingModeNone;
player.controlStyle = MPMovieControlModeDefault;
player.backgroundView.backgroundColor = [UIColor whiteColor];
player.repeatMode = MPMovieRepeatModeNone;
[self.view addSubview: [player view]];
[player play];
</code></pre>
<p>Similar result, with white screen and errors.
Please help....</p> | 12,950,958 | 4 | 2 | null | 2012-10-10 14:59:15.123 UTC | 13 | 2017-07-30 00:22:10.007 UTC | null | null | null | null | 1,147,286 | null | 1 | 30 | objective-c|ios|video|mpmovieplayercontroller|avfoundation | 70,163 | <p>Turns out all we have to do is this:</p>
<pre><code>NSURL *movieURL = [NSURL URLWithString:@"http://example.com/somefile.mp4"];
movieController = [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
[self presentMoviePlayerViewControllerAnimated:movieController];
[movieController.moviePlayer play];
</code></pre>
<ul>
<li><p><code>movieController</code> is an instance of <code>MPMoviePlayerViewController</code> declared in the .h file.</p></li>
<li><p><strong>Important</strong>: when defining the URL use NSURL's <code>URLWithString</code> method if you want to access the file through a network and use NSURL's <code>fileUrlWithPath</code> if you have the file locally!</p></li>
<li><p><code>[movieController.moviePlayer play]</code> <strong>is not required</strong> and the player will start regardless if you didn't set autoplay to NO, but I observed that if you put <code>play</code> in it it starts a bit quicker. This could be just a coincidence.</p></li>
<li><p>If you want to know <strong>when the user tapped the done button</strong> (the player will be dismissed automatically) you should know that <code>-viewDidAppear</code> is called on the view controller that appears when the player is dismissed. You could set a <code>BOOL</code> variable when the player starts and check for the <code>BOOL</code> in your <code>-viewDidAppear</code> so that you know that <code>-viewDidAppear</code> was called becaouse the player was dismissed. Alternatively you can register for <code>MPMoviePlayerDidExitFullScreen</code> notification, but that didn't work for me.</p></li>
</ul>
<p><strong>OR, if this is not working you can just do the following</strong></p>
<pre><code>self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"something" ofType:@"mp4"]]];
[self.moviePlayer.view setFrame:CGRectMake(0, 0, 320, 320)];
[self.moviePlayer play];
[self.view addSubview:self.moviePlayer.view];
</code></pre>
<ul>
<li><p>self.movieplayer is an instance of <strong>MPMoviePlayerController</strong> (not MPMoviePlayerViewController). In my experience it's important to declare it as a property (like so: <code>@property (strong, nonatomic) MPMoviePlayerController *moviePlayer;</code>) rather than a simple ivar, because sometimes it just doesn't work if it's an ivar</p></li>
<li><p>setting the frame is also important, because if we don't set it, the video will not appear at all. The frame can be anything as long as what you define is within the bounds of your view</p></li>
<li><p><strong>Important</strong>: As above, when defining the URL use NSURL's <code>URLWithString</code> method if you want to access the file <strong>through a network</strong> and use NSURL's <code>fileUrlWithPath</code> if you have the file <strong>locally</strong>!</p></li>
</ul> |
12,700,145 | Format telephone and credit card numbers in AngularJS | <p><strong>Question one (formatting telephone number):</strong></p>
<p>I'm having to format a telephone number in AngularJS but there is no filter for it. Is there a way to use filter or currency to format 10 digits to <code>(555) 555-5255</code>? and still preserve the data type of the field as integer?</p>
<p><strong>Question two (masking credit card number):</strong></p>
<p>I have a credit card field that is mapped to AngularJS, like:</p>
<pre><code><input type="text" ng-model="customer.creditCardNumber">
</code></pre>
<p>which is returning the whole number (<code>4111111111111111</code>). I will like to mask it with xxx the first 12 digits and only show the last 4. I was thinking on using filter: limit for this but am not clear as how. Any ideas? Is there a way to also format the number with dashes but still retain the data type as integer? sort of <code>4111-1111-1111-1111</code>.</p> | 12,728,924 | 17 | 2 | null | 2012-10-02 23:59:40.16 UTC | 33 | 2017-08-31 06:20:50.197 UTC | 2015-04-25 14:51:12.013 UTC | null | 3,621,464 | null | 1,607,197 | null | 1 | 69 | angularjs|number-formatting | 135,891 | <p>Also, if you need to format telephone number on output only, you can use a custom filter like this one:</p>
<pre><code>angular.module('ng').filter('tel', function () {
return function (tel) {
if (!tel) { return ''; }
var value = tel.toString().trim().replace(/^\+/, '');
if (value.match(/[^0-9]/)) {
return tel;
}
var country, city, number;
switch (value.length) {
case 10: // +1PPP####### -> C (PPP) ###-####
country = 1;
city = value.slice(0, 3);
number = value.slice(3);
break;
case 11: // +CPPP####### -> CCC (PP) ###-####
country = value[0];
city = value.slice(1, 4);
number = value.slice(4);
break;
case 12: // +CCCPP####### -> CCC (PP) ###-####
country = value.slice(0, 3);
city = value.slice(3, 5);
number = value.slice(5);
break;
default:
return tel;
}
if (country == 1) {
country = "";
}
number = number.slice(0, 3) + '-' + number.slice(3);
return (country + " (" + city + ") " + number).trim();
};
});
</code></pre>
<p>Then you can use this filter in your template:</p>
<pre><code>{{ phoneNumber | tel }}
<span ng-bind="phoneNumber | tel"></span>
</code></pre> |
12,715,340 | Using Directives Sorted in Wrong Order | <p>I'm using the Power Commands extension with Visual Studio 2012. I have the option checked to remove and sort usings on save. The problem is that the System.Xxx directives are being sorted last, and that's causing a style analysis error:</p>
<blockquote>
<p>SA1208: System using directives must be placed before all other using directives.</p>
</blockquote>
<p><strong>Before save:</strong></p>
<pre><code>using System;
using System.Diagnostics.CodeAnalysis;
using Foo;
</code></pre>
<p><strong>After save:</strong></p>
<pre><code>using Foo;
using System;
using System.Diagnostics.CodeAnalysis;
</code></pre>
<p>This worked correctly (System.Xxx first) with VS 2010. Anyone know how to correct this?</p>
<p>Note: Even if it didn't cause an SA error, I'd still prefer the system directives to be first.</p> | 12,715,422 | 1 | 3 | null | 2012-10-03 19:20:24.603 UTC | 11 | 2016-01-20 18:32:31.347 UTC | 2016-01-20 18:32:31.347 UTC | null | 2,642,204 | null | 279,516 | null | 1 | 71 | c#|visual-studio-2012|powercommands | 16,940 | <p>Goto the "Quick Launch" (Ctrl+Q) and type "using" and press <code>Enter</code>.</p>
<p>Then change the following setting:</p>
<p><img src="https://i.stack.imgur.com/twb5T.png" alt="Using Sorting option"></p>
<p>It's an annoying default setting, I have no idea why Microsoft chose that, it goes against all previous standards that I've ever seen.</p>
<p><strong>EDIT:</strong>
Thanks to <a href="https://stackoverflow.com/users/83111/oskar">Oskar</a> we have a <a href="https://connect.microsoft.com/VisualStudio/feedback/details/775702/organize-usings-no-longer-puts-system-references-first-bug-or-feature-change" rel="noreferrer">reason</a>:</p>
<blockquote>
<p>The reason for the change in default behavior is due to the fact that
Windows App Store applications prefer to have 'Windows.<em>' at the top
of the file rather than 'System.</em>'</p>
</blockquote> |
13,051,428 | How to display images in Markdown files on Github? | <p>I want to display some images in a Markdown file on Github. I found it works this way:</p>
<pre><code>
</code></pre>
<p>But i need to collaborate with others so i don't want the username and repo name hard coded .</p>
<p>I tried to use this:</p>
<pre><code>
</code></pre>
<p>It works on my local disk but not work on Github.</p>
<p>Is there anyone knows about this issue?</p> | 13,063,862 | 2 | 0 | null | 2012-10-24 14:35:15.21 UTC | 31 | 2021-03-14 08:01:31.297 UTC | 2019-11-19 10:16:37.987 UTC | null | 1,536,976 | null | 802,585 | null | 1 | 93 | github|markdown | 77,868 | <p>I found the answer myself.</p>
<p>Just simply append <strong>?raw=true</strong> to the image url will make the trick:</p>
<pre><code>
</code></pre> |
30,325,042 | How to compare two JSON strings when the order of entries keep changing | <p>I have a string like - <code>{"state":1,"cmd":1}</code> , I need to compare this with generated output but in the generated output the order keeps changing i.e. sometimes its <code>{"state":1,"cmd":1}</code> other times its <code>{"cmd":1,"state":1}</code>. </p>
<p>Currently I was using <code>equals()</code> method to compare, What can be better way in this scenario to validate the two strings. My concern is just that both entries are present in string, order is not imp.</p> | 30,325,551 | 4 | 11 | null | 2015-05-19 12:00:52.673 UTC | 4 | 2015-05-19 13:22:39.98 UTC | 2015-05-19 13:22:39.98 UTC | null | 67,579 | null | 4,688,819 | null | 1 | 16 | java|string|equals|json | 68,518 | <p><a href="http://jackson.codehaus.org">Jackson Json parser</a> has a nice feature that it can parse a Json String into a Map. You can then query the entries or simply ask on equality: </p>
<pre><code>import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
public class Test
{
public static void main(String... args)
{
String input1 = "{\"state\":1,\"cmd\":1}";
String input2 = "{\"cmd\":1,\"state\":1}";
ObjectMapper om = new ObjectMapper();
try {
Map<String, Object> m1 = (Map<String, Object>)(om.readValue(input1, Map.class));
Map<String, Object> m2 = (Map<String, Object>)(om.readValue(input2, Map.class));
System.out.println(m1);
System.out.println(m2);
System.out.println(m1.equals(m2));
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>The output is </p>
<pre><code>{state=1, cmd=1}
{cmd=1, state=1}
true
</code></pre> |
17,119,116 | How many ways can you insert a series of values into a BST to form a specific tree? | <p><a href="https://stackoverflow.com/q/17118761">This earlier question</a> asked how many ways there were to insert the values 1 - 7 into a binary search tree that would result in the following tree:</p>
<pre><code> 4
/ \
2 6
/ \ / \
1 3 5 7
</code></pre>
<p>(The answer is 80, by the way).</p>
<p>Suppose more generally that you're given an arbitrary BST holding some set of values and want to know how many possible ways there are to insert those values into a BST that would end up producing the resulting tree. Is there an efficient algorithm for determining this?</p>
<p>Thanks!</p> | 17,119,117 | 2 | 0 | null | 2013-06-15 00:35:20.263 UTC | 16 | 2016-06-13 20:43:13.55 UTC | 2017-05-23 10:30:44.547 UTC | null | -1 | null | 501,557 | null | 1 | 22 | algorithm|math|data-structures|permutation|binary-search-tree | 12,367 | <p>We can solve this using a clever recursive algorithm.</p>
<p>As our base case, if you are given an empty tree, there is exactly one way to build that tree - don't insert any values.</p>
<p>For the recursive case, let's suppose that you have a BST that looks like this:</p>
<pre><code> v
/ \
L R
</code></pre>
<p>Here, v is the root, and L and R are the right subtrees, respectively.</p>
<p>If we want to build up this binary search tree, we would have to start off by inserting v first - if we didn't, v wouldn't be the root. After we insert v, we need to insert the elements in an ordering that will cause the subtrees L and R to be rebuilt. The tricky part here is that we don't need to build up all of L before building up R or vice-versa; we could insert some elements from L, then some elements from R, then more elements from L, then more elements from R, etc.</p>
<p>Fortunately, though, there is a useful observation we can make. Suppose that S<sub>L</sub> is a sequence of elements that, if inserted into a BST, forms the BST L. Similarly, let S<sub>R</sub> be a sequence of elements that if inserted into a BST form the BST R. If we consider any possible interleaving of the sequences S<sub>L</sub> and S<sub>R</sub>, we will end up with a sequence of elements that, if inserted into a BST containing just v, will build up the tree</p>
<pre><code> v
/ \
L R
</code></pre>
<p>As an example, consider this tree:</p>
<pre><code> 4
/ \
2 6
/ \ / \
1 3 5 7
</code></pre>
<p>One possible sequence that builds the left subtree (holding 1, 2, 3) is 2, 1, 3. One possible sequence that builds the right subtree is 6, 5, 7. Any possible interleaving of those sequences, when inserted into a BST containing just the root node 4, will end up building out the above BST. For example, any of these sequences will work:</p>
<pre><code> 2, 1, 3, 6, 5, 7
2, 6, 1, 5, 3, 7
6, 5, 2, 1, 3, 7
...
</code></pre>
<p>Since given any sequences S<sub>L</sub> and S<sub>R</sub> that build up L and R we can interleave them in any order, we can write out a nice formula for the number of sequences that will build out a tree with v as its root, L as its left subtree, and R as its right subtree:</p>
<blockquote>
<p># ways = (# interleaves of S<sub>L</sub> and S<sub>R</sub>) × (# possible S<sub>L</sub>s) × (# possible S<sub>R</sub>s)</p>
</blockquote>
<p>If you think about it, the last two terms in this product can be found by recursively finding the number of insertion sequences that work for the left and right subtrees. This means that if we can figure out how many possible interleavings there are for the two sequences, then we can determine how many possible insertion sequences will build up a given tree by evaluating the above expression recursively!</p>
<p>So how many interleavings are there? If we're given two sequences of length m and n with no duplicates in them, then we can come up with the number of interleavings of those sequences with the following observation. Consider the sequence</p>
<pre><code>L L L ... L R R R ... R
m times n times
</code></pre>
<p>Any permutation of this sequence will give back a series of Ls and Rs where the number of Ls is equal to the number of elements in the sequence of length m and the number of Rs is equal to the number of elements in the sequence of length n. We can interpret this sequence as a way of describing how to build up the interleaving - any time we see L, we insert an element from the left sequence, and any time we see an R, we insert an element from the right sequence. For example, consider the sequences 4, 1, 0, 3 and 2, 7. Then the permutation LLRLRL gives the sequence</p>
<pre><code> 4, 1, 2, 0, 3, 7
L L R L R L
</code></pre>
<p>If we start off with a sequence of m L's and n R's, the number of distinct permutations comes back as</p>
<pre><code>(m + n)!
-------- = (m + n) choose m
m! n!
</code></pre>
<p>This holds because there are (m + n)! possible ways of reordering the Ls and the Rs if they were all distinct. Since they aren't, every ordering is counted m! n! too many times because we can permute the L's indistinguishably and the R's indistinguishably. Another way to think about this is to consider the set {1, 2, 3, ..., m + n} of indices in the interleaving, then to choose m of them to fill with elements from the first sequence, implicitly filling the rest of them with elements from the right sequence.</p>
<p>Okay... we now have a way of determining the number of ways of interleaving two sequences of length m and n. Therefore, we have the following:</p>
<blockquote>
<p># ways = (# interleaves of S<sub>L</sub> and S<sub>R</sub>) × (# possible S<sub>L</sub>s) × (# possible S<sub>R</sub>s)</p>
<p>= ((m + n) choose n) × (# possible S<sub>L</sub>s) × (# possible S<sub>R</sub>s)</p>
</blockquote>
<p>Where m is the number of elements in the left subtree and n is the number of elements in the right subtree. Yay!</p>
<p>We can therefore write out pseudocode for this algorithm:</p>
<pre><code>function countInsertionOrderings(Tree t) {
if t is null, return 1;
otherwise:
let m = numElementsIn(t.left);
let n = numElementsIn(t.right);
return choose(m + n, n) *
countInsertionOrderings(t.left) *
countInsertionOrderings(t.right);
}
</code></pre>
<p>This algorithm performs a total of O(n) multiplications, where n is the number of nodes in the tree, and visits every node exactly once (assuming the number of elements in the BST are cached at each node). This does <em>not</em> mean the algorithm runs in time O(n), though, because the work required to multiply these numbers together will grow rapidly as the numbers get larger and larger.</p>
<p>Hope this helps!</p> |
20,469,816 | Jquery, Remove class when width screen is 1050px | <p>This is the JS code i'm using:</p>
<pre><code>$("document").ready(function($){
var nav = $('#menu2');
$(window).scroll(function () {
if ($(this).scrollTop() > 90) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
});
</code></pre>
<p>But i can't seem to get this into my code.</p>
<pre><code>function checkWidth(init){
/*If browser resized, check width again */
if ($(window).width() < 514) {
$('html').addClass('mobile');
}
else {
if (!init) {
$('html').removeClass('mobile');
}}}$(document).ready(function() {
checkWidth(true);
$(window).resize(function() {
checkWidth(false);
});
</code></pre>
<p>And what i want is that when <code>.f-nav</code> is added to <code>#menu2</code>, when the screen is <code><1050</code> the classshould be removed.</p> | 20,470,584 | 5 | 8 | null | 2013-12-09 11:45:21.68 UTC | 1 | 2013-12-09 13:08:40.08 UTC | 2013-12-09 11:48:58.873 UTC | null | 2,254,448 | null | 3,082,607 | null | 1 | 7 | javascript|jquery|css | 42,093 | <p>To change <code>html</code> to <code>#menu2</code>, just replace one with the other. jQuery is pretty simple in this respect </p>
<pre class="lang-js prettyprint-override"><code>if ($(window).width() < 514) {
$('#menu2').addClass('f-nav');
} else {
$('#menu2').removeClass('f-nav');
}
</code></pre>
<p><a href="http://jsfiddle.net/5SM9u/" rel="noreferrer">JSFiddle</a></p> |
25,893,840 | How to avoid "unable to read memory" | <p>I have a struct:</p>
<pre><code>struct a {
a(){};
a(int one,int two): a(one),b(two){};
int a;
int b;
int c;
}
a * b;
cout << b->c;
</code></pre>
<p>And sometimes when i want to read (for ex.) <code>c</code> and in debbuger this value is called </p>
<blockquote>
<p>'unable to read memory'</p>
</blockquote>
<p>Then my program crashed.</p>
<p>And now, how to check that value is readable or not ?</p>
<p>Best Regards.</p> | 25,894,046 | 1 | 7 | null | 2014-09-17 14:51:19.32 UTC | 1 | 2020-08-13 09:15:11.47 UTC | 2014-09-17 14:58:27.39 UTC | null | 3,888,427 | null | 3,888,427 | null | 1 | 7 | c++ | 49,262 | <p>You haven't initialised the pointer to point to anything, so it's invalid. You can't, in general, test whether a pointer points to a valid object. It's up to you to make sure it does; for example:</p>
<pre><code>a obj(1,2); // an object
a * b = &obj; // a pointer, pointing to obj;
cout << b->a; // OK: b points to a valid object
</code></pre>
<p>You can make a pointer <em>null</em> if you don't want it to point to anything. You mustn't dereference it, but it is possible to test for a null pointer:</p>
<pre><code>a * b = nullptr; // or 0, in ancient dialects
if (b) cout << b->a; // OK: test prevents dereferencing
cout << b->a; // ERROR: b is null
</code></pre>
<p>But beware that this doesn't help in situations where a pointer might be invalid but not null; perhaps because it wasn't initialised, or because it pointed to an object that has been destroyed.</p>
<p>In general, avoid pointers except when you actually need them; and be careful not to use invalid pointers when you do. If you just want an object, then just use an object:</p>
<pre><code>a b(1,2); // an object
cout << b.a; // OK: b is a valid object
</code></pre> |
4,753,845 | Build Qt Tests with CMake | <p>Can anyone give me an example of some QT test code and a CMakeLists.txt that build with Cmake and ran with CTest. I can't seem to find any!</p>
<p>-Kurtis</p> | 4,757,074 | 2 | 0 | null | 2011-01-20 23:26:04.813 UTC | 8 | 2014-05-09 08:54:46.047 UTC | null | null | null | null | 527,288 | null | 1 | 28 | qt|cmake|ctest|qttest | 14,819 | <p>An example taken from <a href="https://github.com/KDAB/Charm" rel="noreferrer">Charm</a> (Tests/CMakeLists.txt):</p>
<pre><code>SET( TestApplication_SRCS TestApplication.cpp )
SET( TEST_LIBRARIES CharmCore ${QT_QTTEST_LIBRARY} ${QT_LIBRARIES} )
SET( SqLiteStorageTests_SRCS SqLiteStorageTests.cpp )
QT4_AUTOMOC( ${SqLiteStorageTests_SRCS} )
ADD_EXECUTABLE( SqLiteStorageTests ${SqLiteStorageTests_SRCS} )
TARGET_LINK_LIBRARIES( SqLiteStorageTests ${TEST_LIBRARIES} )
ADD_TEST( NAME SqLiteStorageTests COMMAND SqLiteStorageTests )
</code></pre>
<p>The only difference to a normal executable is that you call ADD_TEST macro.
Have a look at e.g. Charm to see it in action.</p> |
26,757,452 | Laravel Eloquent: Accessing properties and Dynamic Table Names | <p>I am using the Laravel Framework and this question is directly related to using Eloquent within Laravel.</p>
<p>I am trying to make an Eloquent model that can be used across the multiple different tables. The reason for this is that I have multiple tables that are essentially identical but vary from year to year, but I do not want to duplicate code to access these different tables.</p>
<ul>
<li>gamedata_2015_nations</li>
<li>gamedata_2015_leagues</li>
<li>gamedata_2015_teams</li>
<li>gamedata_2015_players</li>
</ul>
<p>I could of course have one big table with a year column, but with over 350,000 rows each year and many years to deal with I decided it would be better to split them into multiple tables, rather than 4 huge tables with an extra 'where' on each request.</p>
<p>So what I want to do is have one class for each and do something like this within a Repository class:</p>
<pre><code>public static function getTeam($year, $team_id)
{
$team = new Team;
$team->setYear($year);
return $team->find($team_id);
}
</code></pre>
<p>I have used this discussion on the Laravel forums to get me started: <a href="http://laravel.io/forum/08-01-2014-defining-models-in-runtime" rel="noreferrer">http://laravel.io/forum/08-01-2014-defining-models-in-runtime</a></p>
<p>So far I have this:</p>
<pre><code>class Team extends \Illuminate\Database\Eloquent\Model {
protected static $year;
public function setYear($year)
{
static::$year= $year;
}
public function getTable()
{
if(static::$year)
{
//Taken from https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L1875
$tableName = str_replace('\\', '', snake_case(str_plural(class_basename($this))));
return 'gamedata_'.static::$year.'_'.$tableName;
}
return Parent::getTable();
}
}
</code></pre>
<p>This seems to work, however i'm worried it's not working in the right way.</p>
<p>Because i'm using the static keyword the property $year is retained within the class rather than each individual object, so whenever I create a new object it still holds the $year property based on the last time it was set in a different object. I would rather $year was associated with a single object and needed to be set each time I created an object.</p>
<p>Now I am trying to track the way that Laravel creates Eloquent models but really struggling to find the right place to do this.</p>
<p>For instance if I change it to this:</p>
<pre><code>class Team extends \Illuminate\Database\Eloquent\Model {
public $year;
public function setYear($year)
{
$this->year = $year;
}
public function getTable()
{
if($this->year)
{
//Taken from https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L1875
$tableName = str_replace('\\', '', snake_case(str_plural(class_basename($this))));
return 'gamedata_'.$this->year.'_'.$tableName;
}
return Parent::getTable();
}
}
</code></pre>
<p>This works just fine when trying to get a single Team. However with relationships it doesn't work. This is what i've tried with relationships:</p>
<pre><code>public function players()
{
$playerModel = DataRepository::getPlayerModel(static::$year);
return $this->hasMany($playerModel);
}
//This is in the DataRepository class
public static function getPlayerModel($year)
{
$model = new Player;
$model->setYear($year);
return $model;
}
</code></pre>
<p>Again this works absolutely fine if i'm using static::$year, but if I try and change it to use $this->year then this stops working.</p>
<p>The actual error stems from the fact that $this->year is not set within getTable() so that the parent getTable() method is called and the wrong table name returned.</p>
<p>My next step was to try and figure out why it was working with the static property but not with the nonstatic property (not sure on the right term for that). I assumed that it was simply using the static::$year from the Team class when trying to build the Player relationship. However this is not the case. If I try and force an error with something like this:</p>
<pre><code>public function players()
{
//Note the hard coded 1800
//If it was simply using the old static::$year property then I would expect this still to work
$playerModel = DataRepository::getPlayerModel(1800);
return $this->hasMany($playerModel);
}
</code></pre>
<p>Now what happens is that I get an error saying gamedata_1800_players isn't found. Not that surprising perhaps. But it rules out the possibility that Eloquent is simply using the static::$year property from the Team class since it is clearly setting the custom year that i'm sending to the getPlayerModel() method.</p>
<p>So now I know that when the $year is set within a relationship and is set statically then getTable() has access to it, but if it is set non-statically then it gets lost somewhere and the object doesn't know about this property by the time getTable() is called.</p>
<p>(note the significance of it working different when simply creating a new object and when using relationships)</p>
<p>I realise i've given alot of detail now, so to simplify and clarify my question:</p>
<p>1) Why does static::$year work but $this->year not work for relationships, when both work when simply creating a new object.</p>
<p>2) Is there a way that I can use a non static property and achieve what I am already achieving using a static property?</p>
<p>Justification for this: The static property will stay with the class even after I have finished with one object and am trying to create another object with that class, which doesn't seem right.</p>
<p>Example:</p>
<pre><code> //Get a League from the 2015 database
$leagueQuery = new League;
$leagueQuery->setYear(2015);
$league = $leagueQuery->find(11);
//Get another league
//EEK! I still think i'm from 2015, even though nobodies told me that!
$league2 = League::find(12);
</code></pre>
<p>This may not be the worst thing in the world, and like I said, it is actually working using the static properties with no critical errors. However it is dangerous for the above code sample to work in that way, so I would like to do it properly and avoid such a danger.</p> | 26,883,036 | 4 | 4 | null | 2014-11-05 12:40:52.06 UTC | 23 | 2019-09-10 20:06:34.46 UTC | null | null | null | null | 255,940 | null | 1 | 16 | php|laravel|laravel-4|eloquent | 17,257 | <p>I assume you know how to navigate the Laravel API / codebase since you will need it to fully understand this answer...</p>
<p><em>Disclaimer</em>: Even though I tested some cases I can't guarantee It always works. If you run into a problem, let me know and I'll try my best to help you.</p>
<p>I see you have multiple cases where you need this kind of dynamic table name, so we will start off by creating a <code>BaseModel</code> so we don't have to repeat ourselves.</p>
<pre><code>class BaseModel extends Eloquent {}
class Team extends BaseModel {}
</code></pre>
<p>Nothing exciting so far. Next, we take a look at one of the <strong>static</strong> functions in <code>Illuminate\Database\Eloquent\Model</code> and write our own static function, let's call it <code>year</code>.
(Put this in the <code>BaseModel</code>)</p>
<pre><code>public static function year($year){
$instance = new static;
return $instance->newQuery();
}
</code></pre>
<p>This function now does nothing but create a new instance of the current model and then initialize the query builder on it. In a similar fashion to the way Laravel does it in the Model class.</p>
<p>The next step will be to create a function that actually sets the table on an <em>instantiated</em> model. Let's call this one <code>setYear</code>. And we'll also add an instance variable to store the year separately from the actual table name.</p>
<pre><code>protected $year = null;
public function setYear($year){
$this->year = $year;
if($year != null){
$this->table = 'gamedata_'.$year.'_'.$this->getTable(); // you could use the logic from your example as well, but getTable looks nicer
}
}
</code></pre>
<p>Now we have to change the <code>year</code> to actually call <code>setYear</code></p>
<pre><code>public static function year($year){
$instance = new static;
$instance->setYear($year);
return $instance->newQuery();
}
</code></pre>
<p>And last but not least, we have to override <code>newInstance()</code>. This method is used my Laravel when using <code>find()</code> for example.</p>
<pre><code>public function newInstance($attributes = array(), $exists = false)
{
$model = parent::newInstance($attributes, $exists);
$model->setYear($this->year);
return $model;
}
</code></pre>
<p>That's the basics. Here's how to use it:</p>
<pre><code>$team = Team::year(2015)->find(1);
$newTeam = new Team();
$newTeam->setTable(2015);
$newTeam->property = 'value';
$newTeam->save();
</code></pre>
<p>The next step are <strong>relationships</strong>. And that's were it gets real tricky.</p>
<p>The methods for relations (like: <code>hasMany('Player')</code>) don't support passing in objects. They take a class and then create an instance from it. The simplest solution I could found, is by creating the relationship object manually. (in <code>Team</code>)</p>
<pre><code>public function players(){
$instance = new Player();
$instance->setYear($this->year);
$foreignKey = $instance->getTable.'.'.$this->getForeignKey();
$localKey = $this->getKeyName();
return new HasMany($instance->newQuery(), $this, $foreignKey, $localKey);
}
</code></pre>
<p><em>Note:</em> the foreign key will still be called <code>team_id</code> (without the year) I suppose that is what you want.</p>
<p>Unfortunately, you will have to do this for every relationship you define. For other relationship types look at the code in <code>Illuminate\Database\Eloquent\Model</code>. You can basically copy paste it and make a few changes. If you use a lot of relationships on your <em>year-dependent</em> models you could also override the relationship methods in your <code>BaseModel</code>.</p>
<p>View the full <code>BaseModel</code> on <a href="http://pastebin.com/uzp0xSBy" rel="noreferrer">Pastebin</a></p> |
26,625,614 | Select query with offset limit is too much slow | <p>I have read from internet resources that a query will be slow when the offset increases. But in my case I think its too much slow. I am using <code>postgres 9.3</code></p>
<p>Here is the query (<code>id</code> is primary key):</p>
<pre><code>select * from test_table offset 3900000 limit 100;
</code></pre>
<p>It returns me data in around <code>10 seconds</code>. And I think its too much slow. I have around <code>4 million</code> records in table. Overall size of the database is <code>23GB</code>.</p>
<p>Machine configuration:</p>
<pre><code>RAM: 12 GB
CPU: 2.30 GHz
Core: 10
</code></pre>
<p>Few values from <code>postgresql.conf</code> file which I have changed are as below. Others are default.</p>
<pre><code>shared_buffers = 2048MB
temp_buffers = 512MB
work_mem = 1024MB
maintenance_work_mem = 256MB
dynamic_shared_memory_type = posix
default_statistics_target = 10000
autovacuum = on
enable_seqscan = off ## its not making any effect as I can see from Analyze doing seq-scan
</code></pre>
<p>Apart from these I have also tried by changing the values of <code>random_page_cost = 2.0</code> and <code>cpu_index_tuple_cost = 0.0005</code> and result is same.</p>
<p><code>Explain (analyze, buffers)</code> result over the query is as below:</p>
<pre><code>"Limit (cost=10000443876.02..10000443887.40 rows=100 width=1034) (actual time=12793.975..12794.292 rows=100 loops=1)"
" Buffers: shared hit=26820 read=378984"
" -> Seq Scan on test_table (cost=10000000000.00..10000467477.70 rows=4107370 width=1034) (actual time=0.008..9036.776 rows=3900100 loops=1)"
" Buffers: shared hit=26820 read=378984"
"Planning time: 0.136 ms"
"Execution time: 12794.461 ms"
</code></pre>
<p>How people around the world negotiates with this problem in postgres? Any alternate solution will be helpful for me as well.</p>
<p><strong>UPDATE::</strong> Adding <code>order by id</code> (tried with other indexed column as well) and here is the explain:</p>
<pre><code>"Limit (cost=506165.06..506178.04 rows=100 width=1034) (actual time=15691.132..15691.494 rows=100 loops=1)"
" Buffers: shared hit=110813 read=415344"
" -> Index Scan using test_table_pkey on test_table (cost=0.43..533078.74 rows=4107370 width=1034) (actual time=38.264..11535.005 rows=3900100 loops=1)"
" Buffers: shared hit=110813 read=415344"
"Planning time: 0.219 ms"
"Execution time: 15691.660 ms"
</code></pre> | 27,169,302 | 9 | 10 | null | 2014-10-29 08:22:07.007 UTC | 22 | 2022-04-10 20:18:46.037 UTC | 2014-11-25 08:20:28.87 UTC | null | 2,953,344 | null | 2,953,344 | null | 1 | 31 | postgresql|postgresql-9.1 | 27,108 | <p>It's slow because it needs to locate the top <code>offset</code> rows and scan the next 100. No amounts of optimization will change that when you're dealing with huge offsets.</p>
<p>This is because your query literally <em>instruct</em> the DB engine to visit lots of rows by using <code>offset 3900000</code> -- that's 3.9M rows. Options to speed this up somewhat aren't many.</p>
<p>Super-fast RAM, SSDs, etc. will help. But you'll only gain by a constant factor in doing so, meaning it's merely kicking the can down the road until you reach a larger enough offset.</p>
<p>Ensuring the table fits in memory, with plenty more to spare will likewise help by a larger constant factor -- <a href="https://stackoverflow.com/questions/27129165/improve-performance-of-first-query">except the first time</a>. But this may not be possible with a large enough table or index.</p>
<p>Ensuring you're doing index-only scans will work to an extent. (See velis' answer; it has a lot of merit.) The problem here is that, for all practical purposes, you can think of an index as a table storing a disk location and the indexed fields. (It's more optimized than that, but it's a reasonable first approximation.) With enough rows, you'll still be running into problems with a larger enough offset.</p>
<p>Trying to store and maintain the precise position of the rows is bound to be an expensive approach too.(This is suggested by e.g. benjist.) While technically feasible, it suffers from limitations similar to those that stem from using MPTT with a tree structure: you'll gain significantly on reads but will end up with excessive write times when a node is inserted, updated or removed in such a way that large chunks of the data needs to be updated alongside.</p>
<p>As is hopefully more clear, there isn't any real magic bullet when you're dealing with offsets this large. It's often better to look at alternative approaches.</p>
<p>If you're paginating based on the ID (or a date field, or any other indexable set of fields), a potential trick (used by blogspot, for instance) would be to make your query start at an arbitrary point in the index.</p>
<p>Put another way, instead of:</p>
<pre><code>example.com?page_number=[huge]
</code></pre>
<p>Do something like:</p>
<pre><code>example.com?page_following=[huge]
</code></pre>
<p>That way, you keep a trace of where you are in your index, and the query becomes very fast because it can head straight to the correct starting point without plowing through a gazillion rows:</p>
<pre><code>select * from foo where ID > [huge] order by ID limit 100
</code></pre>
<p>Naturally, you lose the ability to jump to e.g. page 3000. But give this some honest thought: when was the last time you jumped to a huge page number on a site instead of going straight for its monthly archives or using its search box?</p>
<p>If you're paginating but want to keep the page offset by any means, yet another approach is to forbid the use of larger page number. It's not silly: it's what Google is doing with search results. When running a search query, Google gives you an estimate number of results (you can get a reasonable number using <code>explain</code>), and then will allow you to brows the top few thousand results -- nothing more. Among other things, they do so for performance reasons -- precisely the one you're running into.</p> |
41,302,241 | Modal dialog with fixed header and footer and scrollable content | <p>I'm trying to create a modal dialog that has an fixed header and footer and that the content (in this case list of users) inside the modal dialog is scrollable...</p>
<p>My best attempt so far gave me the result on the image:</p>
<p><a href="https://i.stack.imgur.com/cJzqe.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/cJzqe.jpg" alt="my best"></a></p>
<p>I assume that after seeing the image I dont have to describe what the problem is... and I also assume that you will know what the solution has to look like... :)</p>
<p>But just to be sure I'll write it anyway... The modal dialog needs to have a fixed header (Area where the title "Edit board" "Board name" and "Board type" are located) and footer (Area where the "SAVE" button is located) haveto be fixed/unscrolable... the only thing that has to be scrollable is the list of users...</p>
<p><strong>CODE:</strong></p>
<p><strong>Html:</strong></p>
<pre><code><div id="addBoardModal" class="modal modal-fixed-footer">
<form class="Boards_new" autocomplete="off">
<div class="modal-header">
<h5>{{title}}</h5>
<div class="input-field">
<!--INPUT FORM-->
<div class="BoadType">
<!--RADIAL BUTTON THING-->
<div class="modal-content">
<div class="shareMembers" style="margin-top:18px;">
<div class="row">
<h5 class="left">Share</h5>
<!--LIST OF USERS !!!THIS HAS TO BE SCROLLABLE!!!-->
</div>
</div>
<div class="modal-footer">
<!--JSUT THIS SAVE BUTTON-->
</div>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>.modal {
@extend .z-depth-4;
display: none;
position: fixed;
left: 0;
right: 0;
background-color: #fafafa;
padding: 0;
max-height: 70%;
width: 55%;
margin: auto;
//overflow-y: auto;
border-radius: 2px;
will-change: top, opacity;
@media #{$medium-and-down} {
width: 80%; }
h1,h2,h3,h4 {
margin-top: 0; }
.modal-header{
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
width: 100%;
height: 15rem;
padding:24px;
}
.modal-header > .input-field{width:100%;}
.modal-content {
padding: 24px;
position: absolute;
width: 100%;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
.modal-close {cursor: pointer;}
.modal-footer {
border-radius: 0 0 2px 2px;
border-top: 1px solid rgba(0, 0, 0, 0.1);
background-color: #fafafa;
padding: 4px 6px;
height: 56px;
width: 100%;
.btn, .btn-flat {
float: right;
margin: 6px 0;
}
}
}
</code></pre>
<p>So if anyone could please tell me what am I doing wrong in my code or if I should be doing something diferently that would be nice...</p>
<p>I used these examples to code this...<a href="http://codepen.io/stuntbox/pen/lEdpq" rel="noreferrer">Example no.1</a> & <a href="https://gist.github.com/nate-strauser/530e40ee3bb9b5bb35d366b26e5e1331" rel="noreferrer">Example no.2</a></p>
<p><strong>NOTE:</strong> I'm using the Materialize framework</p> | 41,302,490 | 5 | 7 | null | 2016-12-23 13:18:39.15 UTC | 3 | 2021-04-05 00:06:03.613 UTC | null | null | null | null | 7,068,325 | null | 1 | 13 | html|css|material-design|materialize | 48,013 | <p>You can try <code>max-height</code> using <code>calc()</code> function, like:</p>
<pre><code>.modal-content {
height: auto !important;
max-height: calc(100vh - 340px) !important;
}
</code></pre>
<p>Have a look at the snippet below (<em>use full screen</em>):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal();
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
overflow: hidden;
}
.modal-header {
padding: 15px;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.modal-header h4 {
margin: 0;
}
.modal-content {
height: auto !important;
max-height: calc(100vh - 340px) !important;
}
.content-row {
display: flex;
align-items: center;
padding: 10px;
border-bottom: 1px solid #ddd;
}
.content-row:last-child {
border-bottom: none;
}
.icon {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
background: #33b5e5;
color: #fff;
}
.name {
padding: 0 10px;
}
.role {
padding: 0 10px;
flex: 1;
text-align: right;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.css" rel="stylesheet"/>
<!-- Modal Trigger -->
<a class="modal-trigger waves-effect waves-light btn" href="#modal1">Modal</a>
<!-- Modal Structure -->
<div id="modal1" class="modal modal-fixed-footer">
<div class="modal-header">
<h4>Modal Header</h4>
</div>
<div class="modal-content">
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
<div class="content-row">
<div class="icon">1</div>
<div class="name">Name</div>
<div class="role">Role</div>
</div>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">Agree</a>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script></code></pre>
</div>
</div>
</p>
<p>Hope this helps!</p> |
10,045,446 | Efficient implementation of immutable (double) LinkedList | <p>Having read this question <a href="https://stackoverflow.com/questions/9009627/immutable-or-not-immutable">Immutable or not immutable?</a> and reading answers to my previous questions on immutability, I am still a bit puzzled about efficient implementation of simple LinkedList that is immutable. In terms of array tha seems to be easy - copy the array and return new structure based on that copy.</p>
<p>Supposedly we have a general class of Node:</p>
<pre><code>class Node{
private Object value;
private Node next;
}
</code></pre>
<p>And class LinkedList based on the above allowing the user to add, remove etc. Now, how would we ensure immutability? Should we recursively copy all the references to the list when we insert an element?</p>
<p>I am also curious about answers in <a href="https://stackoverflow.com/questions/9009627/immutable-or-not-immutable">Immutable or not immutable?</a> that mention cerain optimization leading to log(n) time and space with a help of a binary tree. Also, I read somewhere that adding an elem to the front is 0(1) as well. This puzzles me greatly, as if we don't provide the copy of the references, then in reality we are modifying the same data structures in two different sources, which breaks immutability...</p>
<p>Would any of your answers alo work on doubly-linked lists? I look forward to any replies/pointers to any other questions/solution. Thanks in advance for your help.</p> | 10,045,677 | 3 | 0 | null | 2012-04-06 15:15:54.35 UTC | 10 | 2018-04-01 21:44:24.52 UTC | 2017-05-23 12:01:54.447 UTC | null | -1 | null | 1,094,640 | null | 1 | 10 | data-structures|linked-list|immutability | 11,046 | <blockquote>
<p>Supposedly we have a general class of Node and class LinkedList based on the above allowing the user to add, remove etc. Now, how would we ensure immutability? </p>
</blockquote>
<p>You ensure immutability by making every field of the object readonly, and ensuring that every object referred to by one of those readonly fields is also an immutable object. If the fields are all readonly and only refer to other immutable data, then clearly the object will be immutable!</p>
<blockquote>
<p>Should we recursively copy all the references to the list when we insert an element?</p>
</blockquote>
<p>You could. The distinction you are getting at here is the difference between <em>immutable</em> and <em>persistent</em>. An immutable data structure cannot be changed. A <em>persistent</em> data structure takes advantage of the fact that a data structure is immutable in order to re-use its parts.</p>
<p>A persistent immutable linked list is particularly easy:</p>
<pre class="lang-cs prettyprint-override"><code>abstract class ImmutableList
{
public static readonly ImmutableList Empty = new EmptyList();
private ImmutableList() {}
public abstract int Head { get; }
public abstract ImmutableList Tail { get; }
public abstract bool IsEmpty { get; }
public abstract ImmutableList Add(int head);
private sealed class EmptyList : ImmutableList
{
public override int Head { get { throw new Exception(); } }
public override ImmutableList Tail { get { throw new Exception(); } }
public override bool IsEmpty { get { return true; } }
public override ImmutableList Add(int head)
{
return new List(head, this);
}
}
private sealed class List : ImmutableList
{
private readonly int head;
private readonly ImmutableList tail;
public override int Head { get { return head; } }
public override ImmutableList Tail { get { return tail; } }
public override bool IsEmpty { get { return false; } }
public override ImmutableList Add(int head)
{
return new List(head, this);
}
}
}
...
ImmutableList list1 = ImmutableList.Empty;
ImmutableList list2 = list1.Add(100);
ImmutableList list3 = list2.Add(400);
</code></pre>
<p>And there you go. Of course you would want to add better exception handling and more methods, like <code>IEnumerable<int></code> methods. But there is a persistent immutable list. Every time you make a new list, you re-use the contents of an existing immutable list; list3 re-uses the contents of list2, which it can do safely because list2 is never going to change. </p>
<blockquote>
<p>Would any of your answers also work on doubly-linked lists?</p>
</blockquote>
<p>You can of course easily make a doubly-linked list that does a full copy of the entire data structure every time, but that would be dumb; you might as well just use an array and copy the entire array. </p>
<p>Making a <em>persistent</em> doubly-linked list is quite difficult but there are ways to do it. What I would do is approach the problem from the other direction. Rather than saying "can I make a persistent doubly-linked list?" ask yourself "what are the properties of a doubly-linked list that I find attractive?" List those properties and then see if you can come up with a persistent data structure that has those properties.</p>
<p>For example, if the property you like is that doubly-linked lists can be cheaply extended from either end, cheaply broken in half into two lists, and two lists can be cheaply concatenated together, then the persistent structure you want is an <em>immutable catenable deque</em>, not a doubly-linked list. I give an example of a immutable non-catenable deque here: </p>
<p><a href="http://blogs.msdn.com/b/ericlippert/archive/2008/02/12/immutability-in-c-part-eleven-a-working-double-ended-queue.aspx" rel="noreferrer">http://blogs.msdn.com/b/ericlippert/archive/2008/02/12/immutability-in-c-part-eleven-a-working-double-ended-queue.aspx</a></p>
<p>Extending it to be a catenable deque is left as an exercise; the paper I link to on finger trees is a good one to read.</p>
<p>UPDATE:</p>
<blockquote>
<p>according to the above we need to copy prefix up to the insertion point. By logic of immutability, if w delete anything from the prefix, we get a new list as well as in the suffix... Why to copy only prefix then, and not suffix?</p>
</blockquote>
<p>Well consider an example. What if we have the list (10, 20, 30, 40), and we want to insert 25 at position 2? So we want (10, 20, 25, 30, 40).</p>
<p>What parts can we reuse? The tails we have in hand are (20, 30, 40), (30, 40) and (40). Clearly we can re-use (30, 40).</p>
<p>Drawing a diagram might help. We have:</p>
<pre><code>10 ----> 20 ----> 30 -----> 40 -----> Empty
</code></pre>
<p>and we want</p>
<pre><code>10 ----> 20 ----> 25 -----> 30 -----> 40 -----> Empty
</code></pre>
<p>so let's make</p>
<pre><code>| 10 ----> 20 --------------> 30 -----> 40 -----> Empty
| /
| 10 ----> 20 ----> 25 -/
</code></pre>
<p>We can re-use (30, 40) because that part is in common to both lists. </p>
<p>UPDATE:</p>
<blockquote>
<p>Would it be possible to provide the code for random insertion and deletion as well?</p>
</blockquote>
<p>Here's a <em>recursive</em> solution:</p>
<pre class="lang-cs prettyprint-override"><code>ImmutableList InsertAt(int value, int position)
{
if (position < 0)
throw new Exception();
else if (position == 0)
return this.Add(value);
else
return tail.InsertAt(value, position - 1).Add(head);
}
</code></pre>
<p><strong>Do you see why this works?</strong></p>
<p>Now as an exercise, write a recursive DeleteAt.</p>
<p>Now, as an exercise, write a <em>non-recursive</em> InsertAt and DeleteAt. Remember, <em>you have an immutable linked list at your disposal</em>, so you can use one in your iterative solution!</p> |
10,008,949 | Is it possible to get an address from coordinates using google maps? | <p>I'm just curious. Maybe for a future project. I want to know if it's possible to retrieve an address from a giving coordinate via the Google API. </p> | 10,009,027 | 3 | 0 | null | 2012-04-04 10:02:44.97 UTC | 9 | 2019-05-28 08:11:48.557 UTC | 2013-12-07 07:14:12.21 UTC | null | 881,229 | null | 186,964 | null | 1 | 23 | google-maps|google-maps-api-3 | 51,016 | <p>yes. Just use Google Geocoding and Places API <a href="https://developers.google.com/maps/documentation/geocoding/" rel="noreferrer">https://developers.google.com/maps/documentation/geocoding/</a> and <a href="https://developers.google.com/maps/documentation/places/" rel="noreferrer">https://developers.google.com/maps/documentation/places/</a></p>
<p>Example (derived from <a href="https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse" rel="noreferrer">here</a>):</p>
<pre><code>var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
console.log(results[1]);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</code></pre> |
10,046,741 | Searching full name or first or last name in MySQL database with first and last name in separate columns | <p>I'm working with an existing database that has first name and last name seperated in the database. I need to create a function that will take one search input and return results. say my database has a structure like....</p>
<pre><code>nameFirst nameLast
Joe Smith
Joe Jones
Joe Brown
</code></pre>
<p>How could I, using MySql, take a search input that is say 'Joe Smith' and just get his row? But if I put just 'Joe' in the search field, return them all? Will I need to explode the string with a space? thanks!</p> | 10,046,839 | 3 | 3 | null | 2012-04-06 17:10:30.897 UTC | 7 | 2022-02-03 12:42:51.997 UTC | null | null | null | null | 1,283,726 | null | 1 | 25 | php|mysql | 38,908 | <pre><code>SELECT *
FROM table
WHERE CONCAT( nameFirst, ' ', nameLast ) LIKE '%Joe%'
</code></pre>
<p>Be sure to sanitize any user submitted parameters such as "Joe"</p> |
9,652,949 | What is the exact location of MySQL database tables in XAMPP folder? | <p>I have a MySQL database and I want to know the exact location where this data actually stored in the XAMPP folder, I went to this file location to try to get the information:</p>
<pre><code>xampp -> mysql -> data ->
</code></pre>
<p>Here I found a separate folder for each of my databases and within these folders I saw files stored with the <code>.frm format (FRM FILE)</code>.</p>
<p>When I copied my desired database with all tables in <code>.frm format</code> and try to use them on another PC, I was given an empty database of the same name.</p>
<p>Where are the data files for the database kept on the local server?</p> | 9,653,025 | 10 | 0 | null | 2012-03-11 06:27:57.243 UTC | 10 | 2021-11-18 14:50:03.15 UTC | 2017-06-22 09:14:18.963 UTC | null | 6,375,113 | null | 1,196,718 | null | 1 | 40 | mysql|database|data-migration | 219,689 | <p>I think the matter is your tables engine. I guess you are using InnoDB for your table. So you can not copy files easily to make a copy.<br>
Take a look at these links:<br>
<a href="http://dev.mysql.com/doc/refman/5.0/en/innodb-backup.html">http://dev.mysql.com/doc/refman/5.0/en/innodb-backup.html</a><br>
<a href="http://dev.mysql.com/doc/refman/5.0/en/innodb-migration.html">http://dev.mysql.com/doc/refman/5.0/en/innodb-migration.html</a> </p>
<p>Also I recommend you to use something like phpMyAdmin for creating your backup file and then restore the backup file on the next machine using the same IDE.</p> |
10,179,121 | SQL Sub queries in check constraint | <p>Can I make SQL sub queries in Check constraint ?</p>
<p>I've a <code>post</code> table with columns <code>id, owner</code><br />
I've another table <code>action</code> with columns <code>user_id, post_id</code><br />
Table <code>user</code> with columns <code>id</code></p>
<p><code>post_id -> post.id</code> and <code>user_id -> user.id</code> also <code>post.owner -> user.id</code></p>
<p>Now I want to constraint <code>post(post_id).id != user_id</code> on table <code>action</code></p>
<p>How is that possible ?</p> | 10,179,366 | 1 | 2 | null | 2012-04-16 17:55:32.617 UTC | 6 | 2019-03-20 12:39:25.617 UTC | null | null | null | null | 1,234,019 | null | 1 | 56 | postgresql|foreign-key-relationship|plpgsql|check-constraints | 32,645 | <p>It is not supported to look beyond the current row in a CHECK constraint.</p>
<p><a href="http://www.postgresql.org/docs/9.1/interactive/sql-createtable.html">http://www.postgresql.org/docs/9.1/interactive/sql-createtable.html</a> says:</p>
<blockquote>
<p>A check constraint specified as a column constraint should reference
that column's value only, while an expression appearing in a table
constraint can reference multiple columns.</p>
<p>Currently, CHECK expressions cannot contain subqueries nor refer to
variables other than columns of the current row.</p>
</blockquote>
<p>There are good reasons for this restriction, but if you like to juggle flaming torches while riding a unicycle through heavy traffic, you can subvert the restriction using functions. The situations in which this will <em>not</em> come back to bite you are rare; you would be much safer to enforce the invariant in trigger code instead.</p>
<p><a href="http://www.postgresql.org/docs/9.1/interactive/triggers.html">http://www.postgresql.org/docs/9.1/interactive/triggers.html</a></p> |
9,956,766 | Convert string to decimal number in ruby | <p>I need to work with decimals.
In my program, the user need to put a number with decimals to convert that number.</p>
<p>The problem is: If I try to convert the argument into a number I get a integer without decimals.</p>
<pre><code># ARGV[0] is: 44.33
size = ARGV[0]
puts size.to_i
# size is: 44
# :(
</code></pre> | 9,956,784 | 4 | 0 | null | 2012-03-31 14:32:24.473 UTC | 7 | 2018-07-24 08:50:14.737 UTC | 2013-07-09 16:48:36.13 UTC | null | 1,013,719 | null | 1,248,295 | null | 1 | 65 | ruby|numbers|decimal | 91,766 | <p>You call <code>to_i</code>, you get integer.</p>
<p>Try calling <code>to_f</code>, you should get a float.</p>
<p>For more string conversion methods, <a href="http://ruby-doc.org/core-1.9.3/String.html#method-i-to_c" rel="noreferrer">look here</a>.</p> |
10,238,769 | How can I make the Android emulator show the soft keyboard? | <p>I'm debugging an issue with the soft keyboard display not displaying when it should. However, I don't have a device handy for testing. The problem is that <strong>the emulator <em>never</em> shows the soft keyboard</strong>.</p>
<p>Some skins have a keyboard constantly displayed on the right, some don't, but none that I've tried so far has ever shown a keyboard on the device screen.</p>
<p>Is there some setting that I missed?</p> | 18,627,515 | 9 | 2 | null | 2012-04-20 00:37:36.16 UTC | 12 | 2021-08-29 14:10:16.45 UTC | 2014-10-29 16:20:09.32 UTC | null | 85,950 | null | 85,950 | null | 1 | 103 | android|android-emulator | 120,531 | <p>I found out how to do this on <strong>the Android emulator itself</strong> (Menu, "Settings" App - not the settings of the emulator outside). All you need to do is:</p>
<p>open settings app -> Language & Input -> Go to the "Keyboard & Input Methods -> click Default</p>
<p>This will bring up a Dialog in which case you can then disable the Hardware Keyboard by switching the hardware keyboard from on to off. This will disable the Hardware keyboard and enable the softkeyboard.</p> |
9,686,538 | Align labels in form next to input | <p>I have very basic and known scenario of form where I need to align labels next to inputs correctly. However I don't know how to do it.</p>
<p>My goal would be that labels are aligned next to inputs to the right side. Here is picture example of desired result.</p>
<p><img src="https://i.stack.imgur.com/0vfJu.png" alt="enter image description here"></p>
<p>I have made a fiddle for your convenience and to clarify what I have now - <a href="http://jsfiddle.net/WX58z/">http://jsfiddle.net/WX58z/</a></p>
<p>Snippet:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="block">
<label>Simple label</label>
<input type="text" />
</div>
<div class="block">
<label>Label with more text</label>
<input type="text" />
</div>
<div class="block">
<label>Short</label>
<input type="text" />
</div></code></pre>
</div>
</div>
</p> | 9,686,575 | 8 | 0 | null | 2012-03-13 14:57:02.197 UTC | 39 | 2020-10-09 18:50:42.59 UTC | 2016-01-07 21:06:02.74 UTC | null | 3,853,934 | null | 440,611 | null | 1 | 160 | html|css|alignment | 418,645 | <blockquote>
<p><strong>WARNING: OUTDATED ANSWER</strong></p>
<p>Nowadays you should definitely avoid using fixed widths. You could use flexbox or CSS grid to come up with a responsive solution. See the other answers.</p>
</blockquote>
<hr />
<p>One possible solution:</p>
<ul>
<li>Give the labels <code>display: inline-block</code>;</li>
<li>Give them a fixed width</li>
<li>Align text to the right</li>
</ul>
<p>That is:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
display: inline-block;
width: 140px;
text-align: right;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="block">
<label>Simple label</label>
<input type="text" />
</div>
<div class="block">
<label>Label with more text</label>
<input type="text" />
</div>
<div class="block">
<label>Short</label>
<input type="text" />
</div></code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/WX58z/1/" rel="noreferrer">JSFiddle</a></p> |
8,129,040 | proguard Missing type parameter | <p>i try obfuscate my code of android app with <code>ProGuard</code>. But after this my app give exception at running: </p>
<pre><code>11-15 01:46:26.818: W/System.err(21810): java.lang.RuntimeException: Missing type parameter.
11-15 01:46:26.828: W/System.err(21810): at da.<init>(Unknown Source)
11-15 01:46:26.828: W/System.err(21810): at gc.<init>(Unknown Source)
11-15 01:46:26.828: W/System.err(21810): at fx.f(Unknown Source)
11-15 01:46:26.828: W/System.err(21810): at com.yourshows.activity.UnwatchedActivity.onResume(Unknown Source)
</code></pre>
<p>I checked a <code>mapping</code> file and found this: </p>
<pre><code>com.google.gson.reflect.TypeToken -> da:
</code></pre>
<p>I think it's lines in my app like:</p>
<pre><code> Type mapType = new TypeToken<Map<Integer, WatchedEpisodes>>(){}.getType(); // define generic type
jsData = gson.fromJson(r, mapType);
</code></pre>
<p>I can not understand what conclusions should I do? Do not use variable name less then three characters or what?</p>
<p>UPD: <a href="http://groups.google.com/group/google-gson/browse_thread/thread/e97b877cea1920aa" rel="noreferrer">answer</a></p> | 8,181,232 | 3 | 1 | null | 2011-11-14 22:21:54.407 UTC | 13 | 2022-06-06 16:21:16.677 UTC | 2011-12-16 04:42:01.797 UTC | null | 210,916 | null | 968,927 | null | 1 | 32 | android|proguard | 16,034 | <p>answer is: use this proguard.cfg</p>
<pre><code>##---------------Begin: proguard configuration common for all Android apps ----------
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
-repackageclasses ''
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-dontnote com.android.vending.licensing.ILicensingService
# Explicitly preserve all serialization members. The Serializable interface
# is only a marker interface, so it wouldn't save them.
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
private static final java.io.ObjectStreamField[] serialPersistentFields;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();
}
# Preserve all native method names and the names of their classes.
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembernames class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembernames class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
# Preserve static fields of inner classes of R classes that might be accessed
# through introspection.
-keepclassmembers class **.R$* {
public static <fields>;
}
# Preserve the special static methods that are required in all enumeration classes.
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep public class * {
public protected *;
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
##---------------End: proguard configuration common for all Android apps ----------
##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
##---------------End: proguard configuration for Gson ----------
</code></pre>
<p>Big thanks to owner this project --> <a href="http://code.google.com/p/google-gson/" rel="noreferrer">google-gson</a></p>
<hr>
<p><strong>UPD</strong>:
<code>google/gson</code> has their example of proguard configuration for android applications.</p>
<p><a href="https://github.com/google/gson/tree/master/examples/android-proguard-example" rel="noreferrer">see on github</a></p>
<p>They propose to use this template of configuration</p>
<pre><code>##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# For using GSON @Expose annotation
-keepattributes *Annotation*
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
##---------------End: proguard configuration for Gson ----------
</code></pre> |
7,807,360 | How to Get Pixel Color in Android | <p>I'm using Intent to call and show an image from Gallery, and now I made it enable to get me the coordinates of the image in a TextView using these:</p>
<pre><code>final TextView textView = (TextView)findViewById(R.id.textView);
final TextView textViewCol = (TextView)findViewById(R.id.textViewColor);
targetImage.setOnTouchListener(new ImageView.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int x=0;
int y=0;
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
ImageView imageView = ((ImageView)v);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
if(pixel == Color.RED){
textViewCol.setText("It is RED");
}
/*if(redValue == 255){
if(blueValue == 0)
if(greenValue==0)
textViewCol.setText("It is Red");
}*/
return true; }
});
</code></pre>
<p>Now what I need to do is; to get the <code>color (RGB value)</code> of the exact coordinates the user selects and later on assign each to <code>#FF0000</code>, <code>#00FF00</code> and <code>#0000FF</code> but for now, please help to get the Pixel color based on what I have.</p>
<p>Cheers.</p> | 7,807,442 | 3 | 0 | null | 2011-10-18 12:41:14.643 UTC | 23 | 2018-08-07 12:50:16.053 UTC | 2018-08-07 12:50:16.053 UTC | null | 4,286,992 | null | 989,062 | null | 1 | 60 | android|pixel | 102,523 | <p>You can get the pixel from the view like this:</p>
<pre><code>ImageView imageView = ((ImageView)v);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y);
</code></pre>
<p>Now you can get each channel with:</p>
<pre><code>int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
</code></pre>
<p>The Color functions return the value in each channel. So all you have to do is check if Red is 255 and green and blue are 0, than set the textView text to "it is red". Just pay attention that saying that something is red is not simply that the red channel is the greater than zero. 'Cos 255-Green and 255-Red is yellow, of course.
You can also just compare the pixel to different color.
for example:</p>
<pre><code>if(pixel == Color.MAGENTA){
textView.setText("It is Magenta");
}
</code></pre>
<p>Hope it helps.</p> |
11,462,901 | cluster presentation dendrogram alternative in r | <p>I know dendrograms are quite popular. However if there are quite large number of observations and classes it hard to follow. However sometime I feel that there should be better way to present the same thing. I got an idea but do not know how to implement it. </p>
<p>Consider the following dendrogram.</p>
<pre><code>> data(mtcars)
> plot(hclust(dist(mtcars)))
</code></pre>
<p><img src="https://i.stack.imgur.com/6Vnnv.jpg" alt="enter image description here"></p>
<p>Can plot it like a scatter plot. In which the distance between two points is plotted with line, while sperate clusters (assumed threshold) are colored and circle size is determined by value of some variable.</p>
<p><img src="https://i.stack.imgur.com/fdeCr.jpg" alt="enter image description here"></p> | 11,466,725 | 1 | 4 | null | 2012-07-13 01:22:18.087 UTC | 9 | 2013-11-03 17:50:01.9 UTC | 2013-11-03 17:50:01.9 UTC | null | 508,666 | null | 1,502,364 | null | 1 | 7 | r|hierarchical-clustering|dendrogram|phylogeny | 3,343 | <p>You are describing a fairly typical way of going about cluster analysis:</p>
<ul>
<li>Use a clustering algorithm (in this case hierarchical clustering)</li>
<li>Decide on the number of clusters</li>
<li>Project the data in a two-dimensional plane using some form or principal component analysis</li>
</ul>
<p>The code:</p>
<pre><code>hc <- hclust(dist(mtcars))
cluster <- cutree(hc, k=3)
xy <- data.frame(cmdscale(dist(mtcars)), factor(cluster))
names(xy) <- c("x", "y", "cluster")
xy$model <- rownames(xy)
library(ggplot2)
ggplot(xy, aes(x, y)) + geom_point(aes(colour=cluster), size=3)
</code></pre>
<p>What happens next is that you get a skilled statistician to help explain what the x and y axes mean. This usually involves projecting the data to the axes and extracting the factor loadings.</p>
<p>The plot:</p>
<p><img src="https://i.stack.imgur.com/psTfS.png" alt="enter image description here"></p> |
11,523,888 | HTML: HTML5 Placeholder attribute in password field issue- shows normal text? | <p>I am making a Login form, in which there are two fields- </p>
<p>simplified:</p>
<pre><code><input type="text">
<input type="password" placeholder="1234567" >
</code></pre>
<p><strike>In my tests (FF, Chrome) the placeholer shows grey text.
How can I have the placeholder text in password 'dots' ?</strike>
And have placeholder support in IE?</p>
<p><strike>eg. the user sees a fake grey password, not the text 1233467.</strike></p>
<p>(I have jquery available)</p>
<p>Thankyou very much,</p>
<p>Harley</p>
<p><strong>EDIT: Looks like this is the wrong way to use placeholder. However, how can I get IE support? Thanks</strong></p> | 11,524,221 | 3 | 8 | null | 2012-07-17 13:48:01.48 UTC | 3 | 2020-04-01 21:47:22.03 UTC | 2012-07-17 14:05:29.053 UTC | null | 1,458,383 | null | 1,458,383 | null | 1 | 10 | javascript|html|passwords|placeholder | 47,932 | <p>Try using the password dot code in the placeholder like so:</p>
<pre><code>placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;"
</code></pre>
<p>For support in IE please refer to other threads such as
<a href="https://stackoverflow.com/questions/6052544/showing-placeholder-text-for-password-field-in-ie">Showing Placeholder text for password field in IE</a> or <a href="https://stackoverflow.com/questions/5258120/placeholder-works-for-text-but-not-password-box-in-ie-firefox-using-this-javascr">placeholder works for text but not password box in IE/Firefox using this javascript</a></p> |
12,043,913 | Python and Powers Math | <p>I've been learning Python but I'm a little confused. Online instructors tell me to use the operator ** as opposed to ^ when I'm trying to raise to a certain number. Example:</p>
<pre><code>print 8^3
</code></pre>
<p>Gives an output of 11. But what I'm look for (I'm told) is more akin to: print 8**3 which gives the correct answer of 512. But why?</p>
<p>Can someone explain this to me? Why is it that 8^3 does not equal 512 as it is the correct answer? In what instance would 11 (the result of 8^3)? </p>
<p>I did try to search SO but I'm only seeing information concerning getting a modulus when dividing. </p> | 12,043,968 | 3 | 3 | null | 2012-08-20 19:31:45.493 UTC | 5 | 2020-06-30 15:10:03.073 UTC | null | null | null | null | 1,527,653 | null | 1 | 43 | python|math|multiplication|exponent | 97,656 | <p>Operator <code>^</code> is a <a href="http://wiki.python.org/moin/BitwiseOperators" rel="noreferrer"><em>bitwise operator</em></a>, which does <strong>bitwise exclusive or</strong>.</p>
<p><a href="http://docs.python.org/reference/expressions.html#the-power-operator" rel="noreferrer">The power operator</a> is <code>**</code>, like <strong><code>8**3</code></strong> which equals to <code>512</code>.</p> |
11,779,679 | Setting Android Theme background color | <p>I'm trying to modify the default background theme color, which should be easy but surprisingly I can't get it working. Please note that I want the change to be across the entire app, not just for a single activity. Here is my code: </p>
<p>styles.xml</p>
<pre><code><resources>
<color name="white_opaque">#FFFFFFFF</color>
<color name="pitch_black">#FF000000</color>
<style name="AppTheme" parent="android:Theme.Light">
<item name="android:background">@color/white_opaque</item>
<item name="android:windowBackground">@color/white_opaque</item>
<item name="android:colorBackground">@color/white_opaque</item>
</style>
</resources>
</code></pre>
<p>and of course in the manifest</p>
<pre><code><application
.
.
.
android:theme="@style/AppTheme" >
</application>
</code></pre>
<p>Android doc which I consulted on modifying themes:
<a href="http://developer.android.com/guide/topics/ui/themes.html" rel="noreferrer">http://developer.android.com/guide/topics/ui/themes.html</a></p>
<p>I've tried switching between white_opaque and pitch_black for all the xml attributes but it doesn't change a thing. Any suggestions?</p> | 11,781,005 | 3 | 3 | null | 2012-08-02 14:32:41.883 UTC | 12 | 2020-01-22 08:13:49.283 UTC | 2020-01-22 08:13:49.283 UTC | null | 11,348,074 | null | 948,781 | null | 1 | 125 | android|android-theme | 186,358 | <p>Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.</p>
<p>The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now. </p> |
3,919,850 | Conversion from 'myItem*' to non-scalar type 'myItem' requested | <p>I have this C++ code:</p>
<pre><code>#include <iostream>
using namespace std;
struct MyItem
{
int value;
MyItem* nextItem;
};
int main() {
MyItem item = new MyItem;
return 0;
}
</code></pre>
<p>And I get the error:</p>
<pre><code>error: conversion from `MyItem*' to non-scalar type `MyItem' requested
</code></pre>
<p>Compiling with g++. What does that mean? And what's going on here?</p> | 3,919,855 | 4 | 0 | null | 2010-10-12 23:38:44.457 UTC | 5 | 2021-01-01 06:50:02.733 UTC | 2014-11-22 18:06:50.303 UTC | null | 635,608 | null | 351,980 | null | 1 | 31 | c++|new-operator | 105,260 | <p>Try:</p>
<pre><code>MyItem * item = new MyItem;
</code></pre>
<p>But do not forget to delete it after usage:</p>
<pre><code>delete item;
</code></pre> |
3,426,360 | Azure SQL Database Web vs Business Edition | <p>Is there any difference between the Web Edition and Business Edition of Azure SQL Database other than the maximum supported database sizes? I'm assuming the naming has some significance but all of the information I find simply talks about the max db size. I want to know if there are any other differences such as SLA, replication, scalability, etc.</p>
<p>Any clues?</p> | 3,521,506 | 4 | 1 | null | 2010-08-06 17:49:26.327 UTC | 15 | 2015-06-29 14:52:37.74 UTC | 2015-06-29 14:52:37.74 UTC | null | 4,102,957 | null | 43,406 | null | 1 | 63 | azure|azure-sql-database | 18,310 | <p>The two editions are identical except for capacity. Both offer the same replication and SLA.</p>
<p><strong>EDIT April 3, 2014 - Updated to reflect SQL Database size limit now at 500GB</strong></p>
<p><strong>EDIT June 17, 2013: Since I originally posted this answer, a few things have changed with pricing (but the sizing remains the only difference between web & business editions)</strong></p>
<p>Web Edition scales to 5GB, whereas Business Edition scales to 500GB. Also: with the new MSDN plans (announced at TechEd 2013; see ScottGu's <a href="http://weblogs.asp.net/scottgu/archive/2013/06/03/windows-azure-announcing-major-improvements-for-dev-test-in-the-cloud.aspx" rel="noreferrer">blog post</a> for more details), you'll now get monthly monetary credits toward any services you want to apply your credits to, including SQL Database (up to $150 per month, depending on MSDN tier - see <a href="http://www.windowsazure.com/en-us/pricing/member-offers/msdn-benefits/" rel="noreferrer">this page</a> for details around the new MSDN benefits).</p>
<p>Both allow you to set maximum size, and both are billed on an amortized schedule, where your capacity is evaluated daily. Full pricing details are <a href="http://www.windowsazure.com/en-us/pricing/details/sql-database/" rel="noreferrer">here</a>. You'll see that the base pricing begins at $4.995 (up to 100MB), then jumps to $9.99 (up to 1GB), and then starts tiered pricing for additional GB's.</p>
<p>Regardless of edition, you have the exact same set of features - it's all about capacity limits. You can easily change maximum capacity, or even change edition, with T-SQL. For instance, you might start with a Web edition:</p>
<pre><code>CREATE DATABASE Test (EDITION='WEB', MAXSIZE=1GB)
</code></pre>
<p>Your needs grow, so you bump up to 5GB:</p>
<pre><code> ALTER DATABASE Test MODIFY (EDITION='WEB', MAXSIZE=5GB)
</code></pre>
<p>Now you need even more capacity, so you need to switch to one of the Business Edition tiers:</p>
<pre><code>ALTER DATABASE Test MODIFY (EDITION='BUSINESS', MAXSIZE=10GB)
</code></pre>
<p>If you ever need to reduce your database size, that works just fine as well - just alter right back to Web edition:</p>
<pre><code>ALTER DATABASE Test MODIFY (EDITION='WEB', MAXSIZE=5GB)
</code></pre> |
3,483,318 | Performing regex queries with PyMongo | <p>I am trying to perform a regex query using PyMongo against a MongoDB server. The document structure is as follows</p>
<pre><code>{
"files": [
"File 1",
"File 2",
"File 3",
"File 4"
],
"rootFolder": "/Location/Of/Files"
}
</code></pre>
<p>I want to get all the files that match the pattern *File. I tried doing this as such</p>
<pre><code>db.collectionName.find({'files':'/^File/'})
</code></pre>
<p>Yet I get nothing back. Am I missing something, because according to the MongoDB docs this should be possible? If I perform the query in the Mongo console it works fine, does this mean the API doesn't support it or am I just using it incorrectly?</p> | 3,483,399 | 4 | 0 | null | 2010-08-14 12:42:24.147 UTC | 43 | 2021-03-18 19:05:47.427 UTC | 2021-03-18 19:05:47.427 UTC | null | 3,964,927 | null | 42,069 | null | 1 | 145 | mongodb|pymongo | 89,167 | <p>Turns out regex searches are done a little differently in pymongo but is just as easy. </p>
<p>Regex is done as follows :</p>
<pre><code>db.collectionname.find({'files':{'$regex':'^File'}})
</code></pre>
<p>This will match all documents that have a files property that has a item within that starts with File</p> |
3,527,621 | how to pause and resume a surfaceView thread | <p>I have a surfaceView setup and running, but when I resume it I get an error that the thread has already been started. What's the proper way to handle when the app goes to the background and then back to the foreground? I've tinkered around and managed to get the app to come back without crashing... but the surfaceView doesn't draw anything anymore. My code:</p>
<pre><code> @Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e("sys","surfaceCreated was called.");
if(systemState==BACKGROUND){
thread.setRunning(true);
}
else {
thread.setRunning(true);
thread.start();
Log.e("sys","started thread");
systemState=READY;
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e("sys","surfaceDestroyed was called.");
thread.setRunning(false);
systemState=BACKGROUND;
}
</code></pre> | 3,596,395 | 7 | 0 | null | 2010-08-20 01:41:27.67 UTC | 23 | 2018-06-18 15:37:49.81 UTC | 2018-06-18 15:37:49.81 UTC | null | 11,732,320 | null | 385,051 | null | 1 | 15 | android|multithreading|surfaceview | 41,342 | <p>The easy solution is to simply kill and restart the thread. Create methods resume() - creates thread object and starts it - and pause() - kills thread (see Lunarlander example) - in your SurfaceView class and call these from surfaceCreated and surfaceDestroyed to start and stop the thread.</p>
<p>Now in the Activity that runs the SurfaceView, you will also need to call the resume() and pause() methods in the SurfaceView from the Activity's (or fragment's) onResume() and onPause(). It's not an elegant solution, but it will work.</p> |
3,402,295 | HTML table with horizontal scrolling (first column fixed) | <p>I have been trying to think of a way to make a table with a fixed first column (and the rest of the table with a horizontal overflow) I saw a post which had a similar question. but the fixed column bit did not seem to be resolved. Help?</p> | 3,416,518 | 7 | 2 | null | 2010-08-04 03:06:02.457 UTC | 35 | 2022-06-03 16:28:56.687 UTC | 2013-12-10 18:20:59.16 UTC | null | 1,708,520 | null | 380,213 | null | 1 | 75 | html|overflow|html-table|fixed | 227,122 | <p>I have a similar table styled like so:</p>
<pre><code><table style="width:100%; table-layout:fixed">
<tr>
<td style="width: 150px">Hello, World!</td>
<td>
<div>
<pre style="margin:0; overflow:scroll">My preformatted content</pre>
</div>
</td>
</tr>
</table>
</code></pre> |
3,426,498 | Online Internet Explorer Simulators | <p>(Tried to find simular questions / duplicates, failed)</p>
<p>I develop on a mac. I love my mac. I develop using Chrome, Firefox, and Safari. I love them all for different reasons.</p>
<p>But I have to develop for Internet Explorer users as well. </p>
<p>I know, I am not unique here.</p>
<p>I enjoy using the webkit inspector / firebug to mess with CSS. One of the biggest issues I've found when testing ie6-8 is the inability to edit CSS on the fly. The back and forth to a VM or an actual pc, trying something in CSS, saving, reloading in IE, failing, and repeating, leads to a slow development process.</p>
<p>So, on to my actual question.</p>
<p>Is there any sort of online emulator/simulator for various internet explorer versions? Something that somehow renders the page using the ie engine, but still allows me to use my inspector? </p>
<p>Is this even possible?</p> | 3,426,579 | 12 | 2 | null | 2010-08-06 18:07:36.263 UTC | 22 | 2021-08-26 22:41:15.093 UTC | null | null | null | null | 190,902 | null | 1 | 74 | internet-explorer|internet-explorer-8|internet-explorer-6|internet-explorer-7|cross-browser | 219,036 | <p>You could try <a href="http://getfirebug.com/firebuglite" rel="noreferrer">Firebug Lite</a></p>
<p>It's a pure JavaScript-implementation of Firebug that runs directly in any browser (at least in all major ones: IE6+, Firefox, Opera, Safari and Chrome)</p>
<p>You'll still need the VM to actually run IE, but at least you'll get a quicker testing cycle.</p> |
7,862,316 | iOS5 NSURLConnection methods deprecated | <p>I'm trying to write an iOS app that makes asynchronous requests to get data over the network. It seems like a lot of people recommend using NSURLConnection for this, and frequently mention the delegate method connection:didReceiveData:.</p>
<p>Unfortunately, I cannot for the life of me find out where this delegate method is documented. For one, it is not in <a href="http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html">the protocol reference for NSURLConnectionDelegate</a>. It is listed in <a href="http://developer.apple.com/library/ios/#documentation/cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html">the NSURLConnection Class Reference</a>, but has apparently been deprecated as of iOS5. The documentation does not explain why it was deprecated, or what developers should use instead to achieve similar functionality.</p>
<p>What am I missing? A lot of what I've read seems to imply that big changes were made to NSURLConnection for iOS5. Where are these changes documented? Is the documentation of delegate methods complete?</p>
<p>Thanks</p> | 7,862,856 | 4 | 1 | null | 2011-10-22 20:18:11.237 UTC | 13 | 2018-03-20 07:30:39.233 UTC | null | null | null | null | 996,334 | null | 1 | 66 | ios|ios5 | 18,862 | <p>Fishing around the header files tells me that the methods were moved from an informal protocol (which is a deprecated Obj-C pattern) into a formal delegate protocol called <code>NSURLConnectionDataDelegate</code> that's in <code>NSURLConnection.h</code>, but doesn't have a public documentation. </p>
<p>The rest of the documentation keeps using the methods as before, so my guess is this is an omission in the documentation. I.e. the methods (mostly) aren't going anywhere, they were just reshuffled into several protocols and the documentation team has been slacking off. Try making your delegate object conform to the appropriate protocol, and implement the methods with the signatures from the header file.</p> |
8,004,765 | CSS \9 in width property | <p>What is the meaning of this? I am guessing it is a browser hack, but I have not been able to find what exactly it does.</p>
<pre><code>width: 500px\9;
</code></pre>
<p>What is the significance of <code>\9</code>?</p> | 8,004,962 | 4 | 5 | null | 2011-11-04 04:06:03.307 UTC | 43 | 2020-05-06 08:36:12.967 UTC | 2016-01-06 12:30:38.48 UTC | null | 1,660,032 | null | 507,737 | null | 1 | 218 | css|width|css-hack | 80,015 | <p><code>\9</code> is a "CSS hack" specific to Internet Explorer 7, 8, & 9.</p>
<p>This simply means that the one specific line of CSS ending with a <code>\9;</code> in place of the <code>;</code> is only valid in IE 7, 8, & 9.</p>
<p>In your example,</p>
<p><code>width: 500px\9;</code> means that a width of 500 pixels (same result as <code>width: 500px;</code>) will only be applied while using IE 7, 8, & 9.</p>
<p>All other browsers will ignore <code>width: 500px\9;</code> entirely, and therefore not apply <code>width: 500px;</code> to the element at all.</p>
<p>If your CSS looked like this...</p>
<pre><code>#myElement {
width: 300px;
width: 500px\9;
}
</code></pre>
<p>The result would be <code>#myElement</code> 500 pixels wide in IE 7, 8, & 9, while in all other browsers, <code>#myElement</code> would be 300 pixels wide.</p>
<p><a href="https://web.archive.org/web/20160702085511/http://webdesignandsuch.com/ie9-specific-css-hack/" rel="noreferrer">More info</a></p>
<hr>
<p><strong>EDIT:</strong></p>
<p>This answer was written in 2011. It should now be noted that this hack also works in IE 10.</p> |
7,850,125 | Convert "this" pointer to string | <p>In a system where registered objects must have unique names, I want to use/include the object's <code>this</code> pointer in the name. I want the simplest way to create <code>???</code> where:</p>
<p><code>std::string name = ???(this);</code></p> | 7,850,160 | 5 | 12 | null | 2011-10-21 13:31:10.853 UTC | 10 | 2011-10-21 14:44:38.393 UTC | null | null | null | null | 197,229 | null | 1 | 23 | c++|pointers|stl | 53,697 | <p>You could use string representation of the address:</p>
<pre><code>#include <sstream> //for std::stringstream
#include <string> //for std::string
const void * address = static_cast<const void*>(this);
std::stringstream ss;
ss << address;
std::string name = ss.str();
</code></pre> |
4,541,190 | How to close a thread from within? | <p>For every client connecting to my server I spawn a new thread, like this:</p>
<pre><code># Create a new client
c = Client(self.server.accept(), globQueue[globQueueIndex], globQueueIndex, serverQueue )
# Start it
c.start()
# And thread it
self.threads.append(c)
</code></pre>
<p>Now, I know I can close <em>all</em> the threads using this code:</p>
<pre><code> # Loop through all the threads and close (join) them
for c in self.threads:
c.join()
</code></pre>
<p>But how can I close the thread from <em>within</em> that thread?</p> | 4,541,213 | 4 | 1 | null | 2010-12-27 19:20:38.46 UTC | 18 | 2019-03-27 15:08:13.83 UTC | 2017-01-10 20:53:45.807 UTC | null | 355,230 | null | 233,428 | null | 1 | 60 | python|multithreading | 193,400 | <p>When you start a thread, it begins executing a function you give it (if you're extending <code>threading.Thread</code>, the function will be <code>run()</code>). To end the thread, just return from that function.</p>
<p>According to <a href="https://docs.python.org/3/library/threading.html" rel="noreferrer">this</a>, you can also call <code>thread.exit()</code>, which will throw an exception that will end the thread silently.</p> |
4,340,040 | HTML5 Canvas Vector Graphics? | <p>Please tell me what libraries for drawing and handling of vector graphics within HTML5 Canvas do you know?</p>
<p>Thank you!!!</p> | 4,413,041 | 5 | 1 | null | 2010-12-02 21:19:59.623 UTC | 35 | 2022-03-10 07:54:35.043 UTC | null | null | null | null | 352,555 | null | 1 | 47 | html|canvas|vector-graphics | 54,610 | <p>There are a few options. I haven't used either of these libraries, but from what I can tell Cake seems generally more impressive, and imported, while also being three times as large. There is also the Burst Engine, currently an extension of processing.js, which is even smaller. I'm sure there are several more out there.</p>
<p><a href="http://processingjs.org/" rel="nofollow noreferrer"><strong>Processing.js</strong></a></p>
<p>"Processing.js is the sister project of the popular Processing visual programming language..."</p>
<p>size: 412 KB</p>
<p><a href="http://raphaeljs.com/" rel="nofollow noreferrer"><strong>Raphael</strong></a></p>
<p>"Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. If you want to create your own specific chart or image crop and rotate widget, for example, you can achieve it simply and easily with this library.
Raphaël uses the SVG W3C Recommendation and VML as a base for creating graphics. This means every graphical object you create is also a DOM object, so you can attach JavaScript event handlers or modify them later. Raphaël’s goal is to provide an adapter that will make drawing vector art compatible cross-browser and easy."</p>
<p>Size: 60 KB</p>
<p><a href="http://snapsvg.io/" rel="nofollow noreferrer"><strong>Snap.svg</strong></a></p>
<p>The successor to Raphaël. Written by the same developer but intended only for modern browsers.</p>
<p>"Snap provides web developers with a clean, streamlined, intuitive, and powerful API for animating and manipulating both existing SVG content, and SVG content generated with Snap.</p>
<p>By providing a simple and intuitive JavaScript API for animation, Snap can help make your SVG content more interactive and engaging."</p>
<p>Size: 66 KB</p>
<p><a href="http://code.google.com/p/cakejs/" rel="nofollow noreferrer"><strong>Cake</strong></a></p>
<p>"CAKE is a scenegraph library for the canvas tag. You could say that it's like SVG sans the XML and not be too far off."</p>
<p>Size:212 KB</p>
<p><a href="http://paperjs.org" rel="nofollow noreferrer"><strong>Paper.js</strong></a></p>
<p>"Paper.js is an open source vector graphics scripting framework that runs on top of the HTML5 Canvas."</p>
<p>Size: 627.91 KB</p>
<p><a href="https://github.com/rwldrn/burst-core" rel="nofollow noreferrer"><strong>The Burst Engine</strong></a></p>
<p>"The Burst Engine is an OpenSource vector animation engine for the HTML5 Canvas element. Burst provides similar web functionality to Flash and contains a layer based animation system like After Effects. Burst uses a very light-weight JavaScript frame, meaning your animations will download unnoticably quick and can be controlled using very simple JavaScript commands, allowing for chaining and callbacks. ... Burst is currently an extension of the excellent animation port Processing.js by John Resig. Development of an independant Burst Engine is under-way. This will reduce load-time and memory usage when you want to use Burst without using jQuery or Processing.js.</p>
<p>NOTE: Future versions of Burst will also run as a Native Processing applications, allowing you to run a Burst animation in a Java applet or as a binary executable."</p>
<p>It also seems it was last updated in 2010.</p>
<p>Size: 52.6 KB</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics" rel="nofollow noreferrer"><strong>drawing directly to the canvas with .context</strong></a></p>
<p>This is NOT an external library, but drawing directly to the canvas through javascript.</p> |
4,159,950 | How do I delete a remote branch in Git? | <p>I created a branch <code>notmaster</code> to commit as well as push some changes. When I was finished with that branch, I merged the changes back into <code>master</code>, pushed them out, and then deleted the local <code>notmaster</code>.</p>
<pre><code>$ git branch -a
* master
remotes/origin/master
remotes/origin/notmaster
</code></pre>
<p>Is there anyway to delete the remote <code>notmaster</code>?</p>
<hr>
<p>A little more clarity, with the <a href="https://stackoverflow.com/a/4159972/478288">solution from Ionut</a>:</p>
<p>The usual method failed for me:</p>
<pre><code>$ git push origin :notmaster
error: dst refspec notmaster matches more than one.
</code></pre>
<p>That's because I had a tag with the same name as the branch. This was a poor choice on my behalf and caused the ambiguity. So in that case:</p>
<pre><code>$ git push origin :refs/heads/notmaster
</code></pre> | 4,159,972 | 6 | 1 | null | 2010-11-11 22:35:04.147 UTC | 18 | 2017-12-06 07:19:57.38 UTC | 2017-05-23 12:26:05.15 UTC | null | -1 | null | 478,288 | null | 1 | 93 | git | 22,296 | <p><code>git push origin :notmaster</code>, which basically means "push nothing to the notmaster remote".</p> |
4,639,372 | Export to csv in jQuery | <p>I am dynamically generating a div which is like :</p>
<pre><code><div id='PrintDiv'>
<table id="mainTable">
<tr>
<td>
Col1
</td>
<td>
Col2
</td>
<td>
Col3
</td>
</tr>
<tr>
<td>
Val1
</td>
<td>
Val2
</td>
<td>
Val3
</td>
</tr>
<tr>
<td>
Val11
</td>
<td>
Val22
</td>
<td>
Val33
</td>
</tr>
<tr>
<td>
Val111
</td>
<td>
Val222
</td>
<td>
Val333
</td>
</tr>
</table>
</div>
</code></pre>
<p>And there are lot more elements on the page as well.
Now, how can i get a csv file like this :</p>
<pre><code>Col1,Col2,Col3
Val1,Val2,Val3
Val11,Val22,Val33
Val111,Val222,Val333
</code></pre>
<p>using jQuery ?</p>
<p>need a file save dailog box too,like this :</p>
<p><img src="https://i.stack.imgur.com/Mr3Tl.png" alt="alt text"></p>
<p>Thanks.</p> | 7,588,465 | 8 | 5 | null | 2011-01-09 13:31:41.54 UTC | 40 | 2020-09-06 00:03:15.237 UTC | 2014-08-07 18:16:54.367 UTC | null | 237,838 | null | 368,472 | null | 1 | 46 | javascript|asp.net|jquery|csv | 130,124 | <p>You can do that in the client side only, in browser that accept <a href="http://en.wikipedia.org/wiki/Data_URI" rel="nofollow noreferrer">Data URIs</a>:</p>
<pre><code>data:application/csv;charset=utf-8,content_encoded_as_url
</code></pre>
<p>In your example the Data URI must be:</p>
<pre><code>data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333
</code></pre>
<p>You can call this URI by:</p>
<ul>
<li>using <code>window.open</code></li>
<li>or setting the <code>window.location</code></li>
<li>or by the <code>href</code> of an anchor</li>
<li>by adding the <code>download</code> attribute it will work in chrome, still have to test in IE.</li>
</ul>
<p>To test, simply copy the URIs above and paste in your browser address bar. Or test the anchor below in a HTML page:</p>
<pre><code><a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>
</code></pre>
<p>To create the content, getting the values from the table, you can use <a href="http://www.kunalbabre.com/projects/table2CSV.php" rel="nofollow noreferrer">table2CSV</a> and do:</p>
<pre><code>var data = $table.table2CSV({delivery:'value'});
$('<a></a>')
.attr('id','downloadFile')
.attr('href','data:text/csv;charset=utf8,' + encodeURIComponent(data))
.attr('download','filename.csv')
.appendTo('body');
$('#downloadFile').ready(function() {
$('#downloadFile').get(0).click();
});
</code></pre>
<p>Most, if not all, versions of IE don't support navigation to a data link, so a hack must be implemented, often with an <code>iframe</code>. Using an <code>iFrame</code> <a href="https://stackoverflow.com/a/26003382/378151">combined with <code>document.execCommand('SaveAs'..)</code></a>, you can get similar behavior on most currently used versions of IE.</p> |
4,614,671 | PHP session is not working | <p>I am working with wamp2.0 - PHP 5.3, apache 2.2.11 but my sessions are not storing data.</p>
<p>I have a page that accepts a parameter, which (simplified version) I wanna store in a session, so when I come to</p>
<pre><code>http://www.example.com/home.php?sessid=db_session_id
</code></pre>
<p>The script looks like:</p>
<pre><code>session_start();
$sessid = @$_GET['sessid'];
if ($sessid) {
$_SESSION['sessid'] = $sessid;
}
var_dump($_SESSION);
</code></pre>
<p>and outputs:</p>
<pre><code>array(1) { [0]=> string(13) "db_session_id" }
</code></pre>
<p>which is fine, but then, when I go to <a href="http://www.example.com/home.php" rel="nofollow">link</a> (without the sessid parameter) the <code>$_SESSION</code> array is empty. I've event tried to comment the <code>$_SESSION['sessid'] = $sessid;</code> line before going to the page without the parameter, but still it didin't work.</p>
<p>I've checked the <code>session_id()</code> output and the session id remains the same.</p>
<p>Session settings from phpinfo()</p>
<pre><code>Session Support enabled
Registered save handlers files user
Registered serializer handlers php php_binary wddx
Directive Local Value Master Value
session.auto_start Off Off
session.bug_compat_42 On On
session.bug_compat_warn On On
session.cache_expire 180 180
session.cache_limiter nocache nocache
session.cookie_domain no value no value
session.cookie_httponly Off Off
session.cookie_lifetime 0 0
session.cookie_path / /
session.cookie_secure Off Off
session.entropy_file no value no value
session.entropy_length 0 0
session.gc_divisor 1000 1000
session.gc_maxlifetime 1440 1440
session.gc_probability 1 1
session.hash_bits_per_character 5 5
session.hash_function 0 0
session.name PHPSESSID PHPSESSID
session.referer_check no value no value
session.save_handler files files
session.save_path c:/wamp/tmp c:/wamp/tmp
session.serialize_handler php php
session.use_cookies On On
session.use_only_cookies On On
session.use_trans_sid 0 0
</code></pre>
<p><strong>EDIT:</strong></p>
<blockquote>
<p>The sessions are deleted by an iframe. I don't know why, but when
commented, the sessions work fine. Thing is, the iframe has to stay
there (which of course is bad, but I can't do anything about it).
Well...do you know about any workarounds to get the sessions working
with an iframe?</p>
</blockquote> | 14,274,023 | 9 | 9 | null | 2011-01-06 11:59:57.25 UTC | 0 | 2017-09-23 20:35:21.897 UTC | 2012-12-18 11:33:36.487 UTC | null | 367,456 | null | 513,768 | null | 1 | 6 | php|session|iframe|wamp | 45,786 | <p>A frame can access the session only if it's relative to the same domain. For example:</p>
<pre><code><?
$_SESSION["foo"]="foo";
?><html>
<body>
<iframe src ="test.php" width="200" height="200"></iframe>
</body>
</html>
<?
print_r($_SESSION);
?>
</code></pre>
<p>Should work outside and inside the iframe. If your still having problems try:</p>
<pre><code> <?php session_start();
$sessid = $_GET['sessid'];
if (isset($sessid) && $sessid != "" && $sessid != NULL) {
$_SESSION['sessid'] = $sessid;
}
print_r($_SESSION);?>
</code></pre> |
14,465,297 | Connected Component Labeling - Implementation | <p>I have asked a similar question some days ago, but I have yet to find an efficient way of solving my problem.
I'm developing a simple console game, and I have a 2D array like this:</p>
<pre><code>1,0,0,0,1
1,1,0,1,1
0,1,0,0,1
1,1,1,1,0
0,0,0,1,0
</code></pre>
<p>I am trying to find all the areas that consist of neighboring 1's (4-way connectivity). So, in this example the 2 areas are as following:</p>
<pre><code>1
1,1
1
1,1,1,1
1
</code></pre>
<p>and :</p>
<pre><code> 1
1,1
1
</code></pre>
<p>The algorithm, that I've been working on, finds all the neighbors of the neighbors of a cell and works perfectly fine on this kind of matrices. However, when I use bigger arrays (like 90*90) the program is very slow and sometimes the huge arrays that are used cause stack overflows.</p>
<p>One guy on my other question told me about connected-component labelling as an efficient solution to my problem.</p>
<p>Can somebody show me any C++ code which uses this algorithm, because I'm kinda confused about how it actually works along with this disjoint-set data structure thing...</p>
<p>Thanks a lot for your help and time.</p> | 14,466,081 | 5 | 2 | null | 2013-01-22 18:14:37.457 UTC | 17 | 2019-09-14 11:39:12.47 UTC | 2019-09-14 11:39:12.47 UTC | null | 195,787 | user1981497 | null | null | 1 | 26 | algorithm|image-processing|multidimensional-array|area|neighbours | 30,266 | <p>I'll first give you the code and then explain it a bit:</p>
<pre class="lang-cpp prettyprint-override"><code>// direction vectors
const int dx[] = {+1, 0, -1, 0};
const int dy[] = {0, +1, 0, -1};
// matrix dimensions
int row_count;
int col_count;
// the input matrix
int m[MAX][MAX];
// the labels, 0 means unlabeled
int label[MAX][MAX];
void dfs(int x, int y, int current_label) {
if (x < 0 || x == row_count) return; // out of bounds
if (y < 0 || y == col_count) return; // out of bounds
if (label[x][y] || !m[x][y]) return; // already labeled or not marked with 1 in m
// mark the current cell
label[x][y] = current_label;
// recursively mark the neighbors
for (int direction = 0; direction < 4; ++direction)
dfs(x + dx[direction], y + dy[direction], current_label);
}
void find_components() {
int component = 0;
for (int i = 0; i < row_count; ++i)
for (int j = 0; j < col_count; ++j)
if (!label[i][j] && m[i][j]) dfs(i, j, ++component);
}
</code></pre>
<p>This is a common way of solving this problem.</p>
<p>The direction vectors are just a nice way to find the neighboring cells (in each of the four directions).</p>
<p>The <b>dfs</b> function performs a <em>depth-first-search</em> of the grid. That simply means it will visit all the cells reachable from the starting cell. Each cell will be marked with <strong>current_label</strong></p>
<p>The <strong>find_components</strong> function goes through all the cells of the grid and starts a component labeling if it finds an unlabeled cell (marked with 1).</p>
<p>This can also be done iteratively using a stack.
If you replace the stack with a queue, you obtain the <em>bfs</em> or <em>breadth-first-search</em>.</p> |
14,422,340 | MANIFEST.in, package_data, and data_files clarification? | <p>I am trying to create a Python package, and I have a directory structure like this:</p>
<pre><code>mypkg/
├── __init__.py
├── module1
│ ├── x.py
│ ├── y.py
│ └── z.txt
└── module2
├── a.py
└── b.py
</code></pre>
<p>Then I added all the files in <code>MANIFEST.in</code> and when I check the created archive, it had all the files. </p>
<p>When I do <code>python setup.py install</code> in the <code>dist-packages/mypkg/module1</code>. I see only the Python files and not <code>z.txt</code>.</p>
<p>I have <code>z.txt</code> in both <code>MANIFEST.in</code> and <code>setup.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>setup (
packages = [
'mypkg',
'mypkg.module1',
'mypkg.module2',
],
package_data = {
'mypkg': ['module1/z.txt']
},
include_package_data = True,
...
)
</code></pre>
<p>I tried adding the file as <code>data_files</code> as well but that created a directory in <code>/usr/local</code>. I want to keep it inside the source code directory as the code uses that data.</p>
<p>I have read the posts listed below but I keep getting confused about what is the right way to keep <code>z.txt</code> in the right location after <code>setup.py install</code>.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/3596979/manifest-in-ignored-on-python-setup-py-install-no-data-files-installed/3597263#3597263">MANIFEST.in ignored on "python setup.py install" - no data files installed?</a></li>
<li><a href="https://stackoverflow.com/questions/9689816/installing-data-files-into-site-packages-with-setup-py">Installing data files into site-packages with setup.py</a></li>
<li><a href="http://blog.codekills.net/2011/07/15/lies,-more-lies-and-python-packaging-documentation-on--package_data-/" rel="noreferrer">http://blog.codekills.net/2011/07/15/lies,-more-lies-and-python-packaging-documentation-on--package_data-/</a></li>
</ul> | 14,427,680 | 2 | 2 | null | 2013-01-20 06:45:04.583 UTC | 4 | 2017-11-15 13:07:22.753 UTC | 2017-11-15 13:07:22.753 UTC | null | 219,519 | null | 1,979,362 | null | 1 | 32 | python|setuptools|distutils | 8,013 | <p>Update: It got fixed when I started using setuptools instead of distutils.core. I think it was some problem with distutils not agreeing with manifest while setuptools worked without any changes in the code. I recommend using setuptools in the future. Using the link <a href="http://peak.telecommunity.com/DevCenter/setuptools#developer-s-guide" rel="nofollow">here : setup tools- developers guide</a></p> |
14,370,972 | How to attach a process in gdb | <p>I have a simple C program that forks a process and then runs an executable. </p>
<p>I want to attach the child process to gdb. </p>
<p>I run the main program in a console and open another console to find the pid of the child process, then I start gdb with the following command:</p>
<pre><code>gdb attach 12271
</code></pre>
<p>where <code>12271</code> is the child process id, but the attach fails with:</p>
<pre><code>No such file or directory.
</code></pre>
<p>Any idea why?</p> | 14,371,557 | 3 | 2 | null | 2013-01-17 01:47:36.36 UTC | 6 | 2020-10-28 15:49:00.767 UTC | 2018-01-27 21:32:28.337 UTC | null | 320,594 | null | 1,029,808 | null | 1 | 79 | unix|gdb | 134,725 | <p>Try one of these:</p>
<pre><code>gdb -p 12271
gdb /path/to/exe 12271
gdb /path/to/exe
(gdb) attach 12271
</code></pre> |
14,517,546 | How can a C++ header file include implementation? | <p>Ok, not a C/C++ expert by any means, but I thought the point of a header file was to declare the functions, then the C/CPP file was to define the implementation.</p>
<p>However, reviewing some C++ code tonight, I found this in a class's header file...</p>
<pre><code>public:
UInt32 GetNumberChannels() const { return _numberChannels; } // <-- Huh??
private:
UInt32 _numberChannels;
</code></pre>
<p>So why is there an implementation in a header? Does it have to do with the <code>const</code> keyword? Does that inline a class method? What exactly is the benefit/point of doing it this way vs. defining the implementation in the CPP file?</p> | 14,517,957 | 7 | 11 | null | 2013-01-25 07:50:04.703 UTC | 39 | 2019-08-08 07:32:57.39 UTC | 2018-02-04 00:51:54.45 UTC | null | 168,179 | null | 168,179 | null | 1 | 111 | c++|header-files | 120,972 | <blockquote>
<p>Ok, not a C/C++ expert by any means, but I thought the point of a header file was to declare the functions, then the C/CPP file was to define the implementation.</p>
</blockquote>
<p>The true purpose of a header file is to share code amongst multiple source files. It is <strong>commonly</strong> used to separate declarations from implementations for better code management, but that is not a requirement. It is possible to write code that does not rely on header files, and it is possible to write code that is made up of just header files (the STL and Boost libraries are good examples of that). Remember, when the <strong>preprocessor</strong> encounters an <code>#include</code> statement, it replaces the statement with the contents of the file being referenced, then the <strong>compiler</strong> only sees the completed pre-processed code.</p>
<p>So, for example, if you have the following files:</p>
<p>Foo.h:</p>
<pre><code>#ifndef FooH
#define FooH
class Foo
{
public:
UInt32 GetNumberChannels() const;
private:
UInt32 _numberChannels;
};
#endif
</code></pre>
<p>Foo.cpp:</p>
<pre><code>#include "Foo.h"
UInt32 Foo::GetNumberChannels() const
{
return _numberChannels;
}
</code></pre>
<p>Bar.cpp:</p>
<pre><code>#include "Foo.h"
Foo f;
UInt32 chans = f.GetNumberChannels();
</code></pre>
<p>The <strong>preprocessor</strong> parses Foo.cpp and Bar.cpp separately and produces the following code that the <strong>compiler</strong> then parses:</p>
<p>Foo.cpp:</p>
<pre><code>class Foo
{
public:
UInt32 GetNumberChannels() const;
private:
UInt32 _numberChannels;
};
UInt32 Foo::GetNumberChannels() const
{
return _numberChannels;
}
</code></pre>
<p>Bar.cpp:</p>
<pre><code>class Foo
{
public:
UInt32 GetNumberChannels() const;
private:
UInt32 _numberChannels;
};
Foo f;
UInt32 chans = f.GetNumberChannels();
</code></pre>
<p>Bar.cpp compiles into Bar.obj and contains a reference to call into <code>Foo::GetNumberChannels()</code>. Foo.cpp compiles into Foo.obj and contains the actual implementation of <code>Foo::GetNumberChannels()</code>. After compiling, the <strong>linker</strong> then matches up the .obj files and links them together to produce the final executable.</p>
<blockquote>
<p>So why is there an implementation in a header?</p>
</blockquote>
<p>By including the method implementation inside the method declaration, it is being implicitly declared as inlined (there is an actual <code>inline</code> keyword that can be explicitly used as well). Indicating that the compiler should inline a function is only a hint which does not guarantee that the function will actually get inlined. But if it does, then wherever the inlined function is called from, the contents of the function are copied directly into the call site, instead of generating a <code>CALL</code> statement to jump into the function and jump back to the caller upon exiting. The compiler can then take the surrounding code into account and optimize the copied code further, if possible. </p>
<blockquote>
<p>Does it have to do with the const keyword?</p>
</blockquote>
<p>No. The <code>const</code> keyword merely indicates to the compiler that the method will not alter the state of the object it is being called on at runtime.</p>
<blockquote>
<p>What exactly is the benefit/point of doing it this way vs. defining the implementation in the CPP file?</p>
</blockquote>
<p>When used effectively, it allows the compiler to usually produce faster and better optimized machine code.</p> |
14,893,399 | Rebase feature branch onto another feature branch | <p>I have two (private) feature branches that I'm working on.</p>
<pre><code>a -- b -- c <-- Master
\ \
\ d -- e <-- Branch1
\
f -- g <-- Branch2
</code></pre>
<p>After working on these branches a little while I've discovered that I need the changes from Branch2 in Branch1. I'd like to rebase the changes in Branch2 onto Branch1. I'd like to end up with the following:</p>
<pre><code>a -- b -- c <-- Master
\
d -- e -- f -- g <-- Branch1
</code></pre>
<p>I'm pretty sure I need to rebase the second branch <em>onto</em> the first, but I'm not entirely sure about the correct syntax and which branch I should have checked out.</p>
<p>Will this command produce the desired result?</p>
<pre><code>(Branch1)$ git rebase --onto Branch1 Branch2
</code></pre> | 14,893,561 | 4 | 5 | null | 2013-02-15 11:09:24.41 UTC | 102 | 2021-06-17 11:00:27.183 UTC | 2018-08-21 14:10:20.31 UTC | null | 582,821 | null | 537,542 | null | 1 | 406 | git|git-rebase|feature-branch | 299,866 | <ol>
<li><p>Switch to Branch2</p>
<pre><code>git checkout Branch2
</code></pre></li>
<li><p>Apply the current (Branch2) changes on top of the Branch1 changes, staying
in Branch2:</p>
<pre><code>git rebase Branch1
</code></pre></li>
</ol>
<p>Which would leave you with the desired result in Branch2: </p>
<pre><code>a -- b -- c <-- Master
\
d -- e <-- Branch1
\
d -- e -- f' -- g' <-- Branch2
</code></pre>
<p><em>You can delete Branch1.</em></p> |
2,757,911 | How to decode the url in php where url is encoded with encodeURIComponent() | <p>How to decode the url in php where url is encoded with encodeURIComponent()? </p>
<p>I have tried the urldecode() but then also..i don't the url which i have encoded...</p>
<p>I have to do this in php..</p> | 2,757,939 | 2 | 0 | null | 2010-05-03 12:19:48.133 UTC | 9 | 2018-10-25 00:03:21.517 UTC | null | null | null | null | 310,921 | null | 1 | 21 | php|javascript|urlencode|urldecode | 33,513 | <p>You should use <code>rawurldecode()</code>.<br>
See the <a href="http://www.php.net/manual/en/function.rawurldecode.php" rel="noreferrer">Manual</a></p> |
2,903,481 | Using scala.util.control.Exception | <p>Does anybody have good examples of using <a href="http://www.scala-lang.org/api/2.12.0/scala/util/control/Exception$.html" rel="nofollow noreferrer"><code>scala.util.control.Exception</code> version 2.12.0</a> (<a href="http://www.scala-lang.org/api/2.8.0/scala/util/control/Exception$.html" rel="nofollow noreferrer">version 2.8.0</a>), ? I am struggling to figure it out from the types. </p> | 2,903,826 | 2 | 0 | null | 2010-05-25 09:37:34.673 UTC | 9 | 2017-03-03 11:47:25.57 UTC | 2017-03-03 11:47:25.57 UTC | null | 3,165,552 | null | 9,204 | null | 1 | 31 | scala|scala-2.8 | 5,389 | <p>Indeed - I also find it pretty confusing! Here's a problem where I have some property which may be a parseable date:</p>
<pre><code>def parse(s: String) : Date = new SimpleDateFormat("yyyy-MM-dd").parse(s)
def parseDate = parse(System.getProperty("foo.bar"))
type PE = ParseException
import scala.util.control.Exception._
val d1 = try {
parseDate
} catch {
case e: PE => new Date
}
</code></pre>
<p>Switching this to a functional form:</p>
<pre><code>val date =
catching(classOf[PE]) either parseDate fold (_ => new Date, identity(_) )
</code></pre>
<p>In the above code, turns <code>catching(t) either expr</code> will result in an <code>Either[T, E]</code> where <code>T</code> is the throwable's type and <code>E</code> is the expression's type. This can then be converted to a specific value via a <code>fold</code>.</p>
<p>Or another version again:</p>
<pre><code>val date =
handling(classOf[PE]) by (_ => new Date) apply parseDate
</code></pre>
<p>This is perhaps a little clearer - the following are equivalent: </p>
<pre><code>handling(t) by g apply f
try { f } catch { case _ : t => g }
</code></pre> |
2,265,089 | Android game loop, how to control speed and frame rate | <p>I've written a game for Android, and I've tested it on the Dev Phone 1. It works perfectly, the speed is just right. However, I'm sure phone CPU's are getting faster. They may already be faster than the dev phone.</p>
<p>How do I make sure that my game runs at the exact same speed no matter what the device or how fast it runs? Do you know of any techniques? Should I check some kind of timer at the top of the loop each time?</p>
<p>I guess I'm referring to frame rate - but mostly the speed at which my game runs through the main game loop.</p>
<p>Any theory or experience would be great! Thank you.</p> | 2,265,447 | 1 | 1 | null | 2010-02-15 09:56:46.51 UTC | 11 | 2010-02-15 11:06:48.65 UTC | null | null | null | null | 179,518 | null | 1 | 19 | android|cpu-speed | 18,004 | <p>If you are targeting certain frame rate, the basic idea is that you should have a timer or thread that executes your game's tick method at desired intervals. With timers the implementation is pretty trivial: just schedule a timer to execute at regular intervals. When using threads you have to put the thread to sleep between consecutive ticks if it runs faster than the desired frame rate.</p>
<p>However, this alone doesn't lead to the best possible results as the interval can vary a bit between the frames. There is a very good article on this issue: <a href="http://gafferongames.com/game-physics/fix-your-timestep/" rel="noreferrer">http://gafferongames.com/game-physics/fix-your-timestep/</a>.</p>
<p>Also, there are already slower and faster Android phones than the dev phone 1. So you have to prepare for the both cases if you are targeting all Android devices. If your game is not that CPU heavy, it might be that you can achieve the desired frame rate on all the devices. But if you don't limit the frame rate, your game will be too fast on the faster Android phones.</p> |
53,747,772 | Is it possible to make a parameterized scripted pipeline in Jenkins by listing the parameters in actual script, not in job config | <p>In a <a href="https://jenkins.io/doc/book/pipeline/#pipeline-syntax-overview" rel="noreferrer">declarative pipeline</a>, I can specify the parameter that the pipeline expects right in the pipeline script like so:</p>
<pre><code>pipeline {
parameters([
string(name: 'DEPLOY_ENV', defaultValue: 'TESTING' )
])
}
</code></pre>
<p>is it possible do to in a scripted pipline? I know I can do this : </p>
<p><a href="https://i.stack.imgur.com/0Wq57.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0Wq57.png" alt="enter image description here"></a></p>
<p>BUT, IS IT POSSIBLE TO DO THIS: </p>
<pre><code>node{
parameters([
string(name: 'DEPLOY_ENV', defaultValue: 'TESTING' )
])
}
</code></pre> | 53,750,165 | 4 | 0 | null | 2018-12-12 16:52:51.53 UTC | 4 | 2022-03-30 09:51:51.737 UTC | 2018-12-13 17:58:24.39 UTC | null | 366,749 | null | 738,807 | null | 1 | 27 | jenkins|jenkins-pipeline | 42,918 | <p>I found a solution by experimentation so want to share it:</p>
<pre><code>properties(
[
parameters([
string(defaultValue: '/data', name: 'Directory'),
string(defaultValue: 'Dev', name: 'DEPLOY_ENV')
])
]
)
node {
// params.DEPLOY_ENV ...
}
</code></pre> |
40,522,634 | Can I pass parameters in computed properties in Vue.Js | <p>is this possible to pass parameter in computed properties in Vue.Js. I can see when having getters/setter using computed, they can take a parameter and assign it to a variable. like here from <a href="https://v2.vuejs.org/v2/guide/computed.html" rel="noreferrer">documentation</a>:</p>
<pre class="lang-vue prettyprint-override"><code>computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
</code></pre>
<p>Is this also possible:</p>
<pre class="lang-vue prettyprint-override"><code>computed: {
fullName: function (salut) {
return salut + ' ' + this.firstName + ' ' + this.lastName
}
}
</code></pre>
<p>Where computed property takes an argument and returns the desired output. However, when I try this, I am getting this error:</p>
<blockquote>
<p>vue.common.js:2250 Uncaught TypeError: fullName is not a function(…)</p>
</blockquote>
<p>Should I be using methods for such cases?</p> | 40,539,522 | 10 | 1 | null | 2016-11-10 08:06:34.323 UTC | 49 | 2022-08-17 13:58:03.93 UTC | 2022-07-13 22:47:35.917 UTC | null | 6,277,151 | null | 1,610,034 | null | 1 | 317 | javascript|vue.js|vuejs2 | 313,618 | <p>Most probably you want to use a method</p>
<pre><code><span>{{ fullName('Hi') }}</span>
methods: {
fullName(salut) {
return `${salut} ${this.firstName} ${this.lastName}`
}
}
</code></pre>
<hr />
<h2>Longer explanation</h2>
<p>Technically you can use a computed property with a parameter like this:</p>
<pre><code>computed: {
fullName() {
return salut => `${salut} ${this.firstName} ${this.lastName}`
}
}
</code></pre>
<p>(Thanks <code>Unirgy</code> for the base code for this.)</p>
<p>The difference between a computed property and a method is that <strong>computed properties are cached</strong> and change only when their dependencies change. A <strong>method will evaluate every time it's called</strong>.</p>
<p>If you need parameters, there are usually no benefits of using a computed property function over a method in such a case. Though it allows you to have a parametrized getter function bound to the Vue instance, you lose caching so not really any gain there, in fact, you may break reactivity (AFAIU). You can read more about this in Vue documentation <a href="https://v2.vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods" rel="noreferrer">https://v2.vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods</a></p>
<p>The only useful situation is when you <strong>have to</strong> use a getter and need to have it parametrized. For instance, this situation happens in <strong>Vuex</strong>. In Vuex it's the only way to synchronously get parametrized result from the store (actions are async). Thus this approach is listed by official Vuex documentation for its getters
<a href="https://vuex.vuejs.org/guide/getters.html#method-style-access" rel="noreferrer">https://vuex.vuejs.org/guide/getters.html#method-style-access</a></p> |
48,828,478 | How do you use Keras LeakyReLU in Python? | <p>I am trying to produce a CNN using Keras, and wrote the following code:</p>
<pre><code>batch_size = 64
epochs = 20
num_classes = 5
cnn_model = Sequential()
cnn_model.add(Conv2D(32, kernel_size=(3, 3), activation='linear',
input_shape=(380, 380, 1), padding='same'))
cnn_model.add(Activation('relu'))
cnn_model.add(MaxPooling2D((2, 2), padding='same'))
cnn_model.add(Conv2D(64, (3, 3), activation='linear', padding='same'))
cnn_model.add(Activation('relu'))
cnn_model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
cnn_model.add(Conv2D(128, (3, 3), activation='linear', padding='same'))
cnn_model.add(Activation('relu'))
cnn_model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
cnn_model.add(Flatten())
cnn_model.add(Dense(128, activation='linear'))
cnn_model.add(Activation('relu'))
cnn_model.add(Dense(num_classes, activation='softmax'))
cnn_model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adam(), metrics=['accuracy'])
</code></pre>
<p>I want to use Keras's <strong>LeakyReLU</strong> activation layer instead of using <code>Activation('relu')</code>. However, I tried using <code>LeakyReLU(alpha=0.1)</code> in place, but this is an activation layer in Keras, and I get an error about using an activation layer and not an activation function.</p>
<p>How can I use <strong>LeakyReLU</strong> in this example?</p> | 48,828,561 | 3 | 0 | null | 2018-02-16 14:02:47.503 UTC | 3 | 2022-07-07 13:11:35.607 UTC | 2021-02-26 19:54:53.013 UTC | null | 4,685,471 | null | 9,340,209 | null | 1 | 42 | python|machine-learning|keras|neural-network | 71,016 | <p>All advanced activations in Keras, including <code>LeakyReLU</code>, are available as <a href="https://keras.io/layers/advanced-activations/" rel="noreferrer">layers</a>, and not as activations; therefore, you should use it as such:</p>
<pre><code>from keras.layers import LeakyReLU
# instead of cnn_model.add(Activation('relu'))
# use
cnn_model.add(LeakyReLU(alpha=0.1))
</code></pre> |
27,743,339 | Strange behaviour of images in RecyclerView | <p>I am using android.support.v7.widget.RecyclerView to show simple items containing text and in some cases also images. Basically I followed the tutorial from here <a href="https://developer.android.com/training/material/lists-cards.html" rel="noreferrer">https://developer.android.com/training/material/lists-cards.html</a> and just changed the type of mDataset from String[] to JSONArray and the xml of the ViewHolder. My RecyclerView is located in a simple Fragment:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
android:id="@+id/my_hopps_recycler_view"
android:scrollbars="vertical"
android:layout_centerInParent="true"
android:layout_width="200dp"
android:layout_height="wrap_content"/>
</RelativeLayout>
</code></pre>
<p>In this fragment I am loading all information from a webserver. After receiving the information I initialize the items in the RecyclerView. I use a LinearLayoutManager which is set in the onCreate method of my Fragment. After adding the Adapter, I call the setHasFixedSize(true) method on my RecyclerView. My Adapter class looks like this:</p>
<pre><code>import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import saruul.julian.MyFragment;
import saruul.julian.R;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
/**
* Fragment holding the RecyclerView.
*/
private MyFragment myFragment;
/**
* The data to display.
*/
private JSONArray mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView text;
ImageView image;
public ViewHolder(View v) {
super(v);
text = (TextView) v.findViewById(R.id.my_view_text);
image = (ImageView) v.findViewById(R.id.my_view_image);
}
}
public MyAdapter(MyFragment callingFragment, JSONArray myDataset) {
myFragment = callingFragment;
mDataset = myDataset;
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_view, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
try {
JSONObject object = mDataset.getJSONObject(position);
if ( object.has("image") ){
if ( !hopp.getString("image").equals("") ){
try {
byte[] decodedString = Base64.decode(StringEscapeUtils.unescapeJson(object.getString("image")), Base64.DEFAULT);
holder.image.setImageBitmap(BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
holder.image.setVisibility(View.VISIBLE);
} catch ( Exception e ){
e.printStackTrace();
}
}
}
if ( object.has("text") ){
holder.text.setText(object.getString("text"));
}
} catch ( Exception e ){
e.printStackTrace();
}
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.length();
}
}
</code></pre>
<p>And my xml for a view inside my RecyclerView:</p>
<pre><code><android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:id="@+id/my_hopp_people_reached"/>
<ImageView
android:id="@+id/my_hopp_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:adjustViewBounds="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:id="@+id/my_hopp_text"/>
<ImageButton
android:id="@+id/my_hopp_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:src="@drawable/ic_action_discard"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
</code></pre>
<p>So now here is my problem: Everything works fine. Text and picture are shown correctly in my RecyclerView. However if I reach the end of the list by scrolling down and scroll up again, pictures are shown in items which should not contain pictures.
At the moment I have got nine items. The last two of them contain a picture. So I scroll down and just see text in the first seven items. Reaching the end of the list shows me two pictures as expected. But if I scroll up again those pictures appear in other items. </p>
<p>Scrolling up and down changes the pictures always in the same order:</p>
<ul>
<li>The first scrolling up (after being down once) creates a picture in the second item.</li>
<li>Scrolling down creates a picture in the 7th item.</li>
<li>Scrolling up creates a picture in the first item.</li>
<li>Scrolling down creates nothing.</li>
<li>Scrolling up creates a picture in the third item and the picture in the second item was overwritten with the other picture.</li>
<li>Scrolling down creates a picture in the 6th item and lets the picture in the 7th item disappear.</li>
<li>And so on ...</li>
</ul>
<p>I already discovered that the onBindViewHolder(ViewHolder holder, int position) method is called everytime an item appears again on the screen. I checked for the position and the given information in my mDataset. Everything works fine here: The position is right and the given information too. The text in all items does not change and is always shown correctly.
Does anyone have any kind of this problem and knows some solution?</p> | 27,743,634 | 3 | 0 | null | 2015-01-02 13:58:25.467 UTC | 16 | 2018-03-08 13:15:28.8 UTC | 2018-03-08 13:15:28.8 UTC | null | 6,618,622 | null | 3,647,974 | null | 1 | 34 | android|imageview|arrays|android-recyclerview|android-cardview | 38,970 | <p>I think you need to add an <code>else</code> clause to your <code>if ( object.has("image") )</code> statement in the <code>onBindViewHolder(ViewHolder holder, int position)</code> method, setting the image to null:</p>
<pre><code>holder.image.setImageDrawable(null);
</code></pre>
<p>I think <a href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#onBindViewHolder(VH,%20int)">the documentation for onBindViewHolder</a> describe it best why this is necessary:</p>
<blockquote>
<p>Called by RecyclerView to display the data at the specified position. This method should update the contents of the itemView to reflect the item at the given position.</p>
</blockquote>
<p>You should always assume that the ViewHolder passed in needed to be completely updated :)</p> |
50,536,292 | Difference between antMatcher and mvcMatcher | <p>What is difference of <code>HttpSecurity</code>'s <code>antMatcher()</code> and <code>mvcMatcher()</code> functions?</p>
<p>Could anyone explain when to use them ?</p> | 57,373,627 | 3 | 0 | null | 2018-05-25 20:16:21.08 UTC | 13 | 2021-02-16 23:23:27.313 UTC | 2019-08-06 09:53:00.193 UTC | null | 4,390,212 | null | 9,172,501 | null | 1 | 53 | spring|spring-security | 23,156 | <p>As this methods' signatures clearly say is also stated in the <a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/builders/HttpSecurity.html" rel="noreferrer">official documentation</a> -</p>
<blockquote>
<p><code>antMatcher(String antPattern)</code> - Allows configuring the <code>HttpSecurity</code> to only be invoked when matching the provided ant pattern.</p>
<p><code>mvcMatcher(String mvcPattern)</code> - Allows configuring the <code>HttpSecurity</code> to only be invoked when matching the provided Spring MVC pattern.</p>
</blockquote>
<p>Generally <code>mvcMatcher</code> is more secure than an <code>antMatcher</code>. As an example:</p>
<ul>
<li><strong><code>antMatchers("/secured")</code></strong> matches only <em>the exact</em> <code>/secured</code> URL</li>
<li><strong><code>mvcMatchers("/secured")</code></strong> matches <code>/secured</code> as well as <code>/secured/</code>, <code>/secured.html</code>, <code>/secured.xyz</code></li>
</ul>
<p>and therefore is more general and can also handle some possible configuration mistakes.</p>
<p><code>mvcMatcher</code> uses the same rules that Spring MVC uses for matching (when using <code>@RequestMapping</code> annotation).</p>
<blockquote>
<p>If the current request will not be processed by Spring MVC, a reasonable default using the pattern as a ant pattern will be used. <a href="https://docs.spring.io/spring-security/site/docs/4.2.12.RELEASE/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.RequestMatcherConfigurer.html" rel="noreferrer">Source</a></p>
</blockquote>
<p>It may be added that <code>mvcMatchers</code> API (since 4.1.1) is <em>newer</em> than the <code>antMatchers</code> API (since 3.1).</p> |
34,524,390 | Regex to match a variable in Batch scripting | <pre><code>@echo off
SET /p var=Enter:
echo %var% | findstr /r "^[a-z]{2,3}$">nul 2>&1
if errorlevel 1 (echo does not contain) else (echo contains)
pause
</code></pre>
<p>I'm trying to valid a input which should contain 2 or 3 letters. But I tried all the possible answer, it only runs <code>if error level 1 (echo does not contain)</code>.</p>
<p>Can someone help me please. thanks a lot.</p> | 34,525,752 | 4 | 0 | null | 2015-12-30 06:49:00.44 UTC | 2 | 2020-04-18 05:05:32.66 UTC | 2015-12-30 06:59:23.093 UTC | null | 4,158,862 | null | 3,666,807 | null | 1 | 19 | regex|batch-file | 56,331 | <p><code>findstr</code> has no full REGEX Support. Especially no <code>{Count}</code>. You have to use a workaround:</p>
<pre><code>echo %var%|findstr /r "^[a-z][a-z]$ ^[a-z][a-z][a-z]$"
</code></pre>
<p>which searches for <code>^[a-z][a-z]$</code> OR <code>^[a-z][a-z][a-z]$</code></p>
<p>(Note: there is no space between <code>%var%</code> and <code>|</code> - it would be part of the string)</p> |
34,878,848 | Control bar border (color) thickness with ggplot2 stroke | <p>Is it possible to use the stroke argument introduced with <code>ggplot2 2.0</code> to adjust the thickness of borders around bars? If not, is there a way to control bar-border thickness along the lines of point-border thickness? <a href="https://stackoverflow.com/questions/19506630/control-point-border-thickness-in-ggplot">Stroke applies to borders around certain shapes -- see the second answer</a></p>
<p>A very modest MWE, showing fill only:</p>
<pre><code>factor <- c("One", "Two", "Three", "Four")
value <- c(1, 2, 3, 4)
factor2 <- c("A", "B", "A", "B")
df <- data.frame(factor = factor(factor, levels = factor),
value = value, factor2 = factor2)
ggplot(df, aes(x = factor, y = value, color = factor2)) +
geom_bar(stat = "identity")
</code></pre>
<p><a href="https://i.stack.imgur.com/lIqKI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lIqKI.png" alt="Colored borders, but what about size of borders"></a></p>
<p><strong>EDIT after COMMENT</strong>
OK, thanks to MLavoie's comment, it was so simple. Here is the code I have ended with, and, no, I am not actually using this plot other than to teach about <code>ggplot</code> and its capabilities.</p>
<pre><code>ggplot(df, aes(x = factor, y = value, color = factor2)) +
scale_color_manual(values = c("darkgreen", "slateblue4")) +
geom_bar(stat = "identity", aes(fill = "transparent", size = ifelse(factor2 == "A", 2, 1))) +
guides(fill = FALSE) +
guides(size = FALSE) +
guides(color = FALSE)
</code></pre>
<p><a href="https://i.stack.imgur.com/uzit9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uzit9.png" alt="Modifying bar borders by thickness and shade"></a></p> | 34,884,392 | 1 | 0 | null | 2016-01-19 14:04:15.41 UTC | 6 | 2020-02-22 03:42:29.817 UTC | 2017-05-23 11:47:13.79 UTC | null | -1 | null | 2,583,119 | null | 1 | 18 | r|ggplot2|geom-bar | 42,083 | <p>well as I suggested by the OP, I will just recopy my comment as an answer.</p>
<p>you just need to set <code>size</code> in your <code>geom_bar()</code> expression:</p>
<pre><code>geom_bar(stat = "identity", aes(fill = "transparent", size = ifelse(factor2 == "A", 2, 1)), size=2)
</code></pre> |
29,148,274 | Define the selected option with the old input in Laravel / Blade | <p>I have this code:</p>
<pre><code><select required="required" class="form-control" name="title">
<option></option>
@foreach ($titles as $key => $val)
@if (stristr($key, 'isGroup'))
<optgroup label="{{ $val }}">
@else
<option value="{{ $key }}">{{ $val }}</option>
@endif
@endforeach
</select>
</code></pre>
<p>So when the form have errors i use the line <code>Redirect::route('xpto')->withInput()->withErrors($v)</code>. But i can't re-populate the select fields. Any way to do this without using JavaScript for example?</p> | 29,148,393 | 22 | 0 | null | 2015-03-19 15:11:14.15 UTC | 14 | 2022-07-26 15:56:09.683 UTC | 2015-03-19 15:21:37.417 UTC | null | 4,124,475 | null | 4,124,475 | null | 1 | 61 | laravel|laravel-4|laravel-blade | 173,617 | <p>The solution is to compare <code>Input::old()</code> with the <code>$key</code>variable using <a href="https://laravel.com/docs/8.x/blade#if-statements" rel="noreferrer">Blade Directives - If Statements</a>.</p>
<pre><code>@if (Input::old('title') == $key)
<option value="{{ $key }}" selected>{{ $val }}</option>
@else
<option value="{{ $key }}">{{ $val }}</option>
@endif
</code></pre> |
36,429,732 | How make lodash _.replace all occurrence in a string? | <p>How to replace each occurrence of a string pattern in a string by another string? </p>
<pre><code>var text = "azertyazerty";
_.replace(text,"az","qu")
</code></pre>
<p>return <code>quertyazerty</code></p> | 36,429,733 | 4 | 0 | null | 2016-04-05 14:48:01.547 UTC | 6 | 2020-06-04 00:36:00.873 UTC | 2019-01-30 03:50:03.227 UTC | null | 1,033,581 | null | 2,733,216 | null | 1 | 40 | javascript|string|lodash | 68,114 | <p>you have to use the RegExp with global option offered by lodash.</p>
<p>so just use </p>
<pre><code>var text = "azertyazerty";
_.replace(text,new RegExp("az","g"),"qu")
</code></pre>
<p>to return <code>quertyquerty</code></p> |
65,003,024 | Replicating claims as headers is deprecated and will removed from v4.0 - Laravel Passport Problem in lcobucci/jwt package | <p>I'm using <code>laravel/passport:7.5.1</code> package in my laravel project and recently faced with this exception. Any Idea? I temperory downgrade the <code>lcobucci/jwt:3.4.0</code> package to <code>lcobucci/jwt:3.3.3</code></p>
<pre><code>Replicating claims as headers is deprecated and will removed from v4.0. Please manually set the header if you need it replicated.
</code></pre>
<p><strong>Stack Trace:</strong></p>
<pre><code>"exception": {
"trace": [
"/var/www/app/vendor/lcobucci/jwt/src/Builder.php:334",
"/var/www/app/vendor/lcobucci/jwt/src/Builder.php:185",
"/var/www/app/vendor/lcobucci/jwt/src/Builder.php:201",
"/var/www/app/vendor/league/oauth2-server/src/Entities/Traits/AccessTokenTrait.php:34",
"/var/www/app/vendor/league/oauth2-server/src/ResponseTypes/BearerTokenResponse.php:28",
"/var/www/app/vendor/league/oauth2-server/src/AuthorizationServer.php:202",
"/var/www/app/vendor/laravel/passport/src/PersonalAccessTokenFactory.php:114",
"/var/www/app/vendor/laravel/passport/src/PersonalAccessTokenFactory.php:71",
"/var/www/app/vendor/laravel/passport/src/HasApiTokens.php:67",
"/var/www/app/app/Http/Controllers/Auth/Shop/GetTokenController.php:84",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php:45",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Route.php:219",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Route.php:176",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Router.php:680",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:30",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php:41",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php:58",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:104",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Router.php:682",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Router.php:657",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Router.php:623",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Router.php:612",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:176",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:30",
"/var/www/app/vendor/barryvdh/laravel-debugbar/src/Middleware/InjectDebugbar.php:65",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/vendor/app/dms-pubsub/src/Middlewares/CaptureCorrelationIdMiddleware.php:40",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/app/Http/Middleware/TrimData.php:31",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/vendor/fideloper/proxy/src/TrustProxies.php:57",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php:21",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php:21",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php:27",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php:62",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:163",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:104",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:151",
"/var/www/app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:116",
"/var/www/app/public/index.php:55"
],
"class": "ErrorException",
"file": "/var/www/app/vendor/lcobucci/jwt/src/Builder.php:334",
"message": "Replicating claims as headers is deprecated and will removed from v4.0. Please manually set the header if you need it replicated.",
"code": 0
}
</code></pre> | 65,005,348 | 3 | 1 | null | 2020-11-25 10:43:13.367 UTC | 6 | 2021-04-12 01:39:08.547 UTC | 2020-11-25 11:04:31.843 UTC | null | 2,696,125 | null | 2,696,125 | null | 1 | 52 | php|laravel|laravel-passport|thephpleague | 33,575 | <p>I'm deeply sorry for causing confusion or issues. Please check <a href="https://github.com/lcobucci/jwt/issues/550#issuecomment-733557709" rel="noreferrer">https://github.com/lcobucci/jwt/issues/550#issuecomment-733557709</a> for my full explanation on why this approach was taken and why it isn't considered a BC-break in my PoV.</p> |
26,357,340 | ASP.MVC HandleError attribute doesn't work | <p>I know it's a common issue but I've crawled many discussions with no result.</p>
<p>I'm trying to handle errors with the HandleError ASP.MVC attrbiute. I'm using MVC 4.</p>
<p>My Error page is places in Views/Shared/Error.cshtml and looks like that:</p>
<pre><code>Test error page
<hgroup class="title">
<h1 class="error">Error.</h1>
<h2 class="error">An error occurred while processing your request.</h2>
</hgroup>
</code></pre>
<p>My FilterConfig.cs in the App-Start folder is:</p>
<pre><code>public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
</code></pre>
<p>My controller:</p>
<pre><code>public class TestController : Controller
{
[HandleError(View = "Error")]
public ActionResult Index()
{
throw new Exception("oops");
}
}
</code></pre>
<p>And finally my Web.config in has the following node:</p>
<pre><code><customErrors mode="On" defaultRedirect="Error">
</customErrors>
</code></pre>
<p>When I call the controller action I get a white screen with a following text: </p>
<blockquote>
<h2>Server Error in '/' Application.</h2>
<p>Runtime Error Description: An exception occurred while processing
your request. Additionally, another exception occurred while executing
the custom error page for the first exception. The request has been
terminated.</p>
</blockquote>
<p>If defaultRedirect="Error" is not set in the Web.config then I get yellow screen with a following text:</p>
<blockquote>
<h2>Server Error in '/' Application.</h2>
<p>Runtime Error Description: An application error occurred on the
server. The current custom error settings for this application prevent
the details of the application error from being viewed. </p>
<p>Details: To enable the details of this specific error message to be
viewable on the local server machine, please create a
tag within a "web.config" configuration file located in the root
directory of the current web application. This tag
should then have its "mode" attribute set to "RemoteOnly". To enable
the details to be viewable on remote machines, please set "mode" to
"Off".</p>
<p>
</p>
<p>Notes: The current error page you are seeing can be replaced by a
custom error page by modifying the "defaultRedirect" attribute of the
application's configuration tag to point to a custom
error page URL.</p>
<p>
</p>
</blockquote>
<p>Does anybody know what can be wrong?</p>
<p>EDIT:</p>
<p>Errors were caused by using strongly typed layout. When error is thrown MVC's error handling mechanism is creating HandleErrorInfo object which is passed to the Error view. However if we use strongly typed layout then types doesn't match.</p>
<p>Solution in my case is using Application_Error method in Global.asax, which was perfectly described by the SBirthare below.</p> | 26,359,455 | 5 | 0 | null | 2014-10-14 09:34:17.147 UTC | 9 | 2017-06-13 00:33:21.523 UTC | 2014-10-14 13:39:12.88 UTC | null | 3,775,079 | null | 3,775,079 | null | 1 | 9 | c#|.net|asp.net-mvc|asp.net-mvc-4 | 17,194 | <p>Over the years I have struggled to implement "handling custom errors" in ASP.NET MVC smoothly.</p>
<p>I have had successfully used Elmah before however was overwhelmed with the numerous cases that needs to be handled and tested differently (i.e. local vs IIS).</p>
<p>Recently in one of my project which is now live, I have used following approach (seems to be working fine in local and production env).</p>
<p>I do not specify <code>customErrors</code> or any settings in web.config at all.</p>
<p>I override <code>Application_Error</code> and handle all cases there, invoking specific actions in <code>ErrorController</code>.</p>
<p>I am sharing this if it helps and also to get a feedback (though things are working, you never know when it starts breaking ;))</p>
<p><strong>Global.asax.cs</strong></p>
<pre><code>public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
protected void Application_Error(object sender, EventArgs e)
{
System.Diagnostics.Trace.WriteLine("Enter - Application_Error");
var httpContext = ((MvcApplication)sender).Context;
var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
var currentController = " ";
var currentAction = " ";
if (currentRouteData != null)
{
if (currentRouteData.Values["controller"] != null &&
!String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
{
currentController = currentRouteData.Values["controller"].ToString();
}
if (currentRouteData.Values["action"] != null &&
!String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
{
currentAction = currentRouteData.Values["action"].ToString();
}
}
var ex = Server.GetLastError();
if (ex != null)
{
System.Diagnostics.Trace.WriteLine(ex.Message);
if (ex.InnerException != null)
{
System.Diagnostics.Trace.WriteLine(ex.InnerException);
System.Diagnostics.Trace.WriteLine(ex.InnerException.Message);
}
}
var controller = new ErrorController();
var routeData = new RouteData();
var action = "CustomError";
var statusCode = 500;
if (ex is HttpException)
{
var httpEx = ex as HttpException;
statusCode = httpEx.GetHttpCode();
switch (httpEx.GetHttpCode())
{
case 400:
action = "BadRequest";
break;
case 401:
action = "Unauthorized";
break;
case 403:
action = "Forbidden";
break;
case 404:
action = "PageNotFound";
break;
case 500:
action = "CustomError";
break;
default:
action = "CustomError";
break;
}
}
else if (ex is AuthenticationException)
{
action = "Forbidden";
statusCode = 403;
}
httpContext.ClearError();
httpContext.Response.Clear();
httpContext.Response.StatusCode = statusCode;
httpContext.Response.TrySkipIisCustomErrors = true;
routeData.Values["controller"] = "Error";
routeData.Values["action"] = action;
controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}
}
</code></pre>
<p><strong>ErrorController.cs</strong></p>
<pre><code>public class ErrorController : Controller
{
public ActionResult PageNotFound()
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
return View();
}
public ActionResult CustomError()
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return View();
}
}
</code></pre>
<p>This is all I have. No <code>HandleErrorAttribute</code> registered. </p>
<p>I found this approach less confusing and simple to extend. Hope this helps someone.</p> |
26,369,834 | Stored procedure error PLS-00201: identifier 'UTL_HTTP' must be declared | <p>I am trying to create a stored procedure that request some XML data from a service. I have found several examples on-line and all of them point to using this UTL_HTTP package. However, every time I tried to compile my store procedure with that I get the error:</p>
<pre><code>PLS-00201: identifier 'UTL_HTTP' must be declared
</code></pre>
<p>Here is the basic skeleton of the code I want to use.</p>
<pre><code>PROCEDURE GET_XML_DATA2 AS
BEGIN
DECLARE
v_soap_request VARCHAR2(32767);
v_soap_response VARCHAR2(32767);
v_http_request UTL_HTTP.req; --Fails here
v_http_response UTL_HTTP.resp; -- Fails here too
v_action VARCHAR2(4000) := '';
BEGIN
null;
END;
END GET_XML_DATA2;
</code></pre>
<p>It fails in the indicated lines and does not compile. I am using Oracle Express Edition and I have already tried to grant my user execute rights to that package. It did not work.
What else can I look at? What else could be causing this?
Thanks! </p> | 26,370,666 | 1 | 0 | null | 2014-10-14 20:36:41.58 UTC | 3 | 2014-10-14 21:29:16.323 UTC | null | null | null | null | 892,060 | null | 1 | 9 | oracle|stored-procedures | 43,074 | <p>As you already figured out yourself, this seems to be a permission problem. Your user does somehow not have access to the UTL_HTTP package. Make sure your user has the EXECUTE permission on the package:</p>
<pre><code>GRANT EXECUTE ON SYS.UTL_HTTP TO my_user;
</code></pre>
<p>Note that you might have to do this as SYS.</p>
<p>Using SQL Developer (which I can recommend if you're doing PL/SQL development), see if you can then look at the package somehow. If that does not help, please post the permissions that your user currently has.</p> |
27,964,611 | How to set onclick listener for a button in a fragment in android | <p>My app contains a form as shown in the following image:</p>
<p><img src="https://i.stack.imgur.com/O366nl.png" alt="register screenshot"></p>
<p>When I click on menu options button, the drawer opens as shown in the following image:
<img src="https://i.stack.imgur.com/aDUt0l.png" alt="select screenshot"></p>
<p>I want the drawer to open when the button <strong>select location</strong> is pressed.</p>
<p>My codes are</p>
<p>RegisterBlood.java</p>
<pre><code> ...
public class RegisterBlood extends Activity implements OnItemClickListener {
DrawerLayout dLayout, dLayout2;
ListView dList, dList2;
ArrayAdapter<String> adapter, adapter2;
String[] state_data2;
String city = "", state = "";
Button location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectlocation);
Bundle args = new Bundle();
Fragment detail = new RegisterBloodFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail)
.commit();
...
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, state_data);
dList.setAdapter(adapter);
dList.setSelector(android.R.color.holo_blue_dark);
// dLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
dList.setOnItemClickListener(this);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
// your action...
if (!dLayout.isDrawerOpen(dList)) {
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, state_data2);
dList.setAdapter(adapter);
dLayout.openDrawer(dList);
dList.setOnItemClickListener(this);
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_BACK) {
// your action...
if (dLayout.isDrawerOpen(dList)) {
dLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
return true;
}
return super.onKeyDown(keyCode, e);
}
@Override
public void onItemClick(AdapterView<?> arg0, View v, final int position,
long id) {
// TODO Auto-generated method stub
...
dLayout2 = (DrawerLayout) findViewById(R.id.drawer_layout);
dList2 = (ListView) findViewById(R.id.left_drawer);
adapter2 = new ArrayAdapter<String>(RegisterBlood.this,
android.R.layout.simple_list_item_1, city_data);
dList2.setAdapter(adapter2);
dList2.setSelector(android.R.color.holo_blue_dark);
dLayout2.openDrawer(dList2);
dLayout2.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
dList2.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position2,
long id) {
dLayout2.closeDrawers();
state = state_data2[position];
city = city_data[position2];
Bundle args = new Bundle();
args.putString("Menu", city_data[position2] + " ("
+ state_data2[position] + ")");
Fragment detail = new RegisterBloodFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, detail).commit();
}
});
}}
</code></pre>
<p>RegisterBloodFragment.java</p>
<pre><code>...
public class RegisterBloodFragment extends Fragment implements OnClickListener {
Button location;
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
View view = inflater.inflate(R.layout.registerblood, container, false);
String menu = getArguments().getString("Menu");
location= (Button) view.findViewById(R.id.etlocation);
location.setText(menu);
//Context c=getActivity();
//location.setOnClickListener(c.getApplicationContext().set);
return view;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
"Yes",
Toast.LENGTH_SHORT).show();
}
}
</code></pre>
<p>registerblood.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/silver"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="10dp"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:paddingTop="10dp" >
<EditText
android:id="@+id/bregetName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:ems="10"
android:hint="Name" />
<EditText
android:id="@+id/bregetBloodGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:ems="10"
android:hint="Blood Group" />
<Button
android:id="@+id/etlocation"
style="@android:style/Widget.EditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:ems="10"
android:hint="select location" >
</Button>
<Button
android:id="@+id/bregbtnSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10sp"
android:layout_marginTop="10sp"
android:background="@drawable/button"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:text="Submit"
android:textColor="#FFFFFF"
android:textSize="24sp" />
</LinearLayout>
</code></pre>
<p>selectlocation.xml</p>
<pre><code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#fff"/>
</code></pre>
<p></p>
<p><strong>My question is:</strong></p>
<p>How to add <code>onclicklistener</code> for select location button in <code>RegisterBlood.java</code> or call <code>onClickListener</code> which is in <code>RegisterBlood.java</code> from <code>RegisterBloodFragment.java</code> ?</p>
<p>Please help me out.</p> | 27,964,693 | 3 | 0 | null | 2015-01-15 13:33:02.983 UTC | 4 | 2020-01-16 13:26:11.64 UTC | 2017-04-02 21:44:33.257 UTC | null | 1,644,131 | null | 3,948,601 | null | 1 | 9 | android|android-fragments|onclick|drawer | 62,230 | <p>Since the button is a part of the fragment's layout, set the listener there:</p>
<pre><code>@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
View view = inflater.inflate(R.layout.registerblood, container, false);
String menu = getArguments().getString("Menu");
location = (Button) view.findViewById(R.id.etlocation);
location.setText(menu);
location.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
RegisterBlood activity = (RegisterBlood) getActivity();
// Now you can contact your activity through activity e.g.:
activity.onKeyDown(KeyEvent.KEYCODE_MENU, null);
}
</code></pre> |
40,772,997 | How to convert List<V> into Map<K, List<V>>, with Java 8 streams and custom List and Map suppliers? | <p>It's easy to convert <code>List<V></code> into <code>Map<K, List<V>></code>. For example:</p>
<pre><code>public Map<Integer, List<String>> getMap(List<String> strings) {
return
strings.stream()
.collect(Collectors.groupingBy(String::length));
}
</code></pre>
<p>But I want to do it with my own <code>List</code> and <code>Map</code> <strong>suppliers</strong>.</p>
<p>I have come up with this:</p>
<pre><code>public Map<Integer, List<String>> getMap(List<String> strings) {
return strings.stream()
.collect(Collectors.toMap(
String::length,
item -> {List<String> list = new ArrayList<>(); list.add(item); return list;},
(list1, list2) -> {list1.addAll(list2); return list1;},
HashMap::new));
}
</code></pre>
<p><strong>Question:</strong> Is there an easier, less verbose, or more efficient way of doing it? For example, something like this (which doesn't work):</p>
<pre><code>return strings.stream()
.collect(Collectors.toMap(
String::length,
ArrayList::new,
HashMap::new));
</code></pre>
<p>And what if I only need to define the <code>List</code> supplier, but not the <code>Map</code> supplier?</p> | 40,773,235 | 3 | 2 | null | 2016-11-23 19:49:20.003 UTC | 16 | 2019-10-16 03:59:34.44 UTC | 2016-11-23 21:09:02.343 UTC | null | 1,743,880 | null | 3,411,681 | null | 1 | 39 | java|java-stream|collectors | 49,221 | <p>You could have the following:</p>
<pre><code>public Map<Integer, List<String>> getMap(List<String> strings) {
return strings.stream().collect(
Collectors.groupingBy(String::length, HashMap::new, Collectors.toCollection(ArrayList::new))
);
}
</code></pre>
<p>The collector <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-java.util.function.Supplier-java.util.stream.Collector-" rel="noreferrer"><code>groupingBy(classifier, mapFactory, downstream)</code></a> can be used to specify which type of map is wanted, by passing it a supplier of the wanted map for the <code>mapFactory</code>. Then, the downstream collector, which is used to collect elements grouped to the same key, is <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toCollection-java.util.function.Supplier-" rel="noreferrer"><code>toCollection(collectionFactory)</code></a>, which enables to collect into a collection obtained from the given supplier.</p>
<p>This makes sure that the map returned is a <code>HashMap</code> and that the lists, in each value, are <code>ArrayList</code>. Note that if you want to return specific implementations of map and collection, then you most likely want the method to return those specific types as well, so you can use their properties.</p>
<p>If you only want to specify a collection supplier, and keep <code>groupingBy</code> default map, you can just omit the supplier in the code above and use the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-java.util.stream.Collector-" rel="noreferrer">two arguments overload</a>:</p>
<pre><code>public Map<Integer, List<String>> getMap(List<String> strings) {
return strings.stream().collect(
Collectors.groupingBy(String::length, Collectors.toCollection(ArrayList::new))
);
}
</code></pre>
<hr>
<p>As a side-note, you could have a generic method for that:</p>
<pre><code>public <K, V, C extends Collection<V>, M extends Map<K, C>> M getMap(List<V> list,
Function<? super V, ? extends K> classifier, Supplier<M> mapSupplier, Supplier<C> collectionSupplier) {
return list.stream().collect(
Collectors.groupingBy(classifier, mapSupplier, Collectors.toCollection(collectionSupplier))
);
}
</code></pre>
<p>The advantage with this declaration is that you can now use it to have specific <code>HashMap</code> of <code>ArrayList</code>s as result, or <code>LinkedHashMap</code> of <code>LinkedLists</code>s, if the caller wishes it:</p>
<pre><code>HashMap<Integer, ArrayList<String>> m = getMap(Arrays.asList("foo", "bar", "toto"),
String::length, HashMap::new, ArrayList::new);
LinkedHashMap<Integer, LinkedList<String>> m2 = getMap(Arrays.asList("foo", "bar", "toto"),
String::length, LinkedHashMap::new, LinkedList::new);
</code></pre>
<p>but, at that point, it may be simpler to directly use the <code>groupingBy</code> in the code...</p> |
46,622,291 | Mapping Firebase Auth users to Firestore Documents | <p>I'm trying to use <strong>Firebase</strong>'s <code>Firestore</code> database to handle <code>User</code>s in my Android app. </p>
<p>Initially I want to use the <strong>id</strong> returned from the <code>Auth</code> package (a string), and set that as the id for the <code>users</code> <code>Collection</code> in the database. When creating a <code>Document</code> inside of the <code>Collection</code> <code>users</code>, I set a <code>uid</code> field to that auth package string.</p>
<p>I realize there is no way of setting that string to an indexable value so that queries like:</p>
<pre><code>// get Auth package uid string
db.collection("users").document(auth_uid_string);
</code></pre>
<p>would work.</p>
<p>So the alternative, I guess, is to use <code>Query.whereEqualTo("uid", auth_uid_string)</code> which would give me the user in a list, because firestore doesn't assume the query is for a unique value.</p>
<p>I want to avoid the above solution, and devise a way to store the <code>users</code> of the app in <code>firestore</code>, and use the <code>auth</code> package to verify that I fetch the correct user. Is such a solution possible? Or should I try a <em>different</em> firebase service, or even just run a postgres server in heroku or something?</p> | 46,876,181 | 1 | 0 | null | 2017-10-07 16:06:41.353 UTC | 13 | 2018-05-25 14:21:44.013 UTC | 2017-10-09 05:26:13.123 UTC | null | 153,407 | null | 4,443,226 | null | 1 | 31 | firebase|firebase-authentication|user-management|google-cloud-firestore | 18,235 | <p>I am not sure how to do this in android, but with JS I am doing the following:</p>
<pre><code>firebase.firestore().collection('users').doc(currentUser.uid).set(currentUser)
</code></pre>
<p><code>currentUser</code> is the user object that the authentication function returns (I use <code>signInWithCredential</code>)
It is working perfectly. I am sure you can implement a similar approach in android.</p> |
46,438,557 | How to extract the file jre-9/lib/modules? | <p>In <code>JRE-9/lib</code> directory (at least on Windows), there is a new file called <code>modules</code> whose size is about 107 MB. Is it possible to extract that file or maybe list java modules within it?</p>
<p>I can see that a new tool called <code>jmod</code> is available at <code>jdk-9/bin/jmod.exe</code>, but that is for reading <code>.jmod</code> files which is located at <code>jdk-9/jmods</code> and it cannot read the file <code>modules</code>.</p> | 46,441,042 | 6 | 0 | null | 2017-09-27 02:28:16.103 UTC | 11 | 2021-05-25 10:51:28.15 UTC | 2017-09-27 05:26:59.187 UTC | null | 1,746,118 | null | 597,657 | null | 1 | 27 | java|java-9|java-module|jdk-tools|jmod | 8,288 | <p>The <code>modules</code> file is a container file. It's internal to the JDK and the format is not documented (it may change at any time). For troubleshooting purposes, the <code>jimage</code> tool in the bin directory can be used to list or extract the contents.</p> |
37,342,997 | Render multiple components in React Router | <p>I'm used to application layouts with multiple yield areas, i.e. for content area and for top bar title. I'd like to achieve something similar in React Router. For example:</p>
<pre><code><Router>
<Route path="/" component = { AppLayout }>
<Route path="list"
component = { ListView }
topBarComponent = { ListTopBar }/>
</Route>
</Router>
</code></pre>
<p><em>AppLayout:</em></p>
<pre><code><div className="appLayout box">
<div className="appLayout topBar">
{ -- display ListTopBar here -- }
</div>
<div className="appLayout content">
{ -- display ListView here -- }
</div>
</div>
</code></pre>
<p>Both child components should receive the same props.</p>
<p>How can I approach this?</p> | 37,343,236 | 11 | 0 | null | 2016-05-20 09:28:24.837 UTC | 5 | 2022-09-15 18:49:26.673 UTC | null | null | null | null | 876,409 | null | 1 | 15 | javascript|meteor|react-router|reactjs | 39,760 | <p>To passe multiple component you can do like this :</p>
<pre><code><Route path="groups" components={{main: Groups, sidebar: GroupsSidebar}} />
<Route path="users" components={{main: Users, sidebar: UsersSidebar}}>
</code></pre>
<p>See the doc here :
<a href="https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#named-components" rel="noreferrer">https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#named-components</a></p> |
32,167,640 | Visual Studio 2015 diagnostics tool does not support current debugging configuration | <p>After using VS2015 snapshot and profiling tools, I can't seem to get the diagnostics tools to work again. Every project, even new ones just say the following </p>
<blockquote>
<p>The Diagnostic Tools window does not support the current debugging
configuration.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/iu3e5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iu3e5.png" alt="enter image description here"></a></p>
<p>Tried creating new and different type projects, running as administrator, deleting program data, app data, repairing and re-installing from uninstall.</p>
<p>Anyone experienced this?, shame as they've improved this tool a lot in this version.</p> | 32,182,718 | 6 | 0 | null | 2015-08-23 14:20:18.19 UTC | 3 | 2019-12-30 23:39:56.84 UTC | 2019-10-03 20:03:04.527 UTC | null | 44,729 | null | 760,986 | null | 1 | 61 | c#|visual-studio|debugging|visual-studio-2015|visual-studio-debugging | 28,438 | <p>So I resolved my issue. The Diagnostic Tools window currently does not support:</p>
<ul>
<li>Windows Store projects that are using JavaScript </li>
<li>Windows Store projects that are running on a Windows Phone </li>
<li>Debugging with Use Managed or Native Compatibility Mode</li>
</ul>
<p>In my case I had 'Use Managed Compatibility Mode' enabled. To change this go to the following and uncheck the 'Use Managed Compatibility Mode' or 'Use Managed Native Mode'.</p>
<blockquote>
<p>Tools –> Options –> Debugging -> General -> (Un-check) 'Use Managed Compatibility
Mode'</p>
</blockquote> |
5,700,558 | How can I bind nested ViewModels from View to Controller in MVC3? | <p>I am developing an ASP.NET MVC 3 application in C# and I use Razor. I am now dealing with a problem concerning the binding of objects through ViewModels passed/received to/from the View by the Controller.
Let's make it clear. I have the following ViewModels:</p>
<pre><code>public class ContainerViewModel
{
public int ContainerId {get; set;}
public string ContainerName {get; set;}
public List<ItemPostModel> ItemData {get; set;}
}
public class ItemPostModel
{
public int ItemId {get; set;}
public string ItemName {get; set;}
public int ItemValue {get; set;}
}
</code></pre>
<p>The <strong>ContainerViewModel</strong> is used to pass the data to the View. Its properties <strong>ContainerId</strong> and <strong>ContainerName</strong> are used just for display purposes. The <strong><code>List<ItemPostModel></code></strong> property has to be filled using a <strong>Form</strong>. The View looks something like this (it is a simplified version):</p>
<pre><code><strong>@Model.ContainerName</strong>
@using (Html.BeginForm())
{
<fieldset>
@foreach(var item in Model.ItemData)
{
@Html.TextBox(item.ItemId);
@Html.TextBox(item.ItemName);
@Html.TextBox(item.ItemValue);
<p>
<input type="submit" value="Save" />
</p>
}
</fieldset>
}
</code></pre>
<p>The <strong>Controller</strong> corresponding <strong>action methods</strong> are as follows:</p>
<pre><code>public ActionResult UpdateItems()
{
//fill in the ContainerViewModel lcontainer
return View("UpdateItems", lcontainer);
}
[HttpPost]
public ActionResult UpdateItems(int containerId, ItemPostModel itemData)
{
//store itemData into repository
}
</code></pre>
<p>The problem is that with this code the <strong>ItemPostModel itemData</strong> passed to the <strong>Post ActionMethod UpdateItems</strong> is always empty. The <strong>containerId</strong> is correctly passed. Same result if I use the following code in the Controller (obviously not DRY);</p>
<pre><code>[HttpPost]
public ActionResult UpdateItems(ContainerViewModel container)
{
//extract itemData from ContainerViewModel container
//store itemData into repository
}
</code></pre>
<p>How can I <em>"teach"</em> the application that I want the form elements stored in the <strong><code>List<ItemPostModel></code></strong>? Shall I modify the <strong>ModelBinder</strong> or there is a simpler way to perform this task? Thanks everybody for your answers.</p> | 5,700,800 | 1 | 0 | null | 2011-04-18 08:54:55.037 UTC | 17 | 2012-02-20 13:45:45.817 UTC | 2012-02-20 13:45:45.817 UTC | null | 675,082 | null | 675,082 | null | 1 | 25 | c#|asp.net-mvc-3|binding|viewmodel | 9,796 | <p>Don't write loops in a view. Use editor templates:</p>
<pre><code><strong>@Model.ContainerName</strong>
@using (Html.BeginForm())
{
<fieldset>
@Html.EditorFor(x => x.ItemData)
<input type="submit" value="Save" />
</fieldset>
}
</code></pre>
<p>and inside the corresponding editor template (<code>~/Views/Shared/EditorTemplates/ItemPostModel.cshtml</code>):</p>
<pre><code>@model ItemPostModel
@Html.TextBox(x => x.ItemId)
@Html.TextBox(x => x.ItemName)
@Html.TextBox(x => x.ItemValue)
</code></pre>
<p>And in the controller action you might need to specify the prefix:</p>
<pre><code>[HttpPost]
public ActionResult UpdateItems(
int containerId,
[Bind(Prefix = "ItemData")]ItemPostModel itemData
)
{
//store itemData into repository
}
</code></pre>
<p>and that should be pretty much all. The editor template will take care of generating the proper input field names for the binding to work.</p> |
Subsets and Splits