Id int64 34.6M 60.5M | Title stringlengths 15 150 | Body stringlengths 33 36.7k | Tags stringlengths 3 112 | CreationDate stringdate 2016-01-01 00:21:59 2020-02-29 17:55:56 | Y stringclasses 3 values |
|---|---|---|---|---|---|
37,906,119 | Non-whitespace before first tag error | <p>I can not build cordova application,and I receive the following error:</p>
<pre><code>Error: Non-whitespace before first tag.
Line: 0
Column: 1
Char:
</code></pre>
<p>I am using <code>cordova 6.2.0</code>, and trying to build the <code>android</code> platform.</p>
| <android><cordova> | 2016-06-19 10:13:42 | HQ |
37,906,472 | Read-only Slack channel | <p>Is it possible to configure a Slack channel to be public but read-only for all and only e.g. Jenkins user can write messages in it?</p>
<p><em>(Apologies if it is off-topic for SO)</em></p>
| <slack> | 2016-06-19 10:57:36 | HQ |
37,906,514 | Git granularity -- resolving diffs within a line | <p>Is git line-based or diff granularity can be increased to a word/letter resolution? It is worth for multiple statements per line or using git for writing plain texts.</p>
| <git><diff> | 2016-06-19 11:03:40 | HQ |
37,906,664 | Database Variable Java (Static vs enum) | <p>I'm just going through my code and tidying things up, standardising things etc.</p>
<p>Just a quick questionin my Database class I have declared the database variables at the start of the class. see below:</p>
<pre><code> private static final String DATABASE = ".....";
private static final String DRIVER = "....";
</code></pre>
<p>Is this the best way to do this or would I be best creating an enum and accessing them through that?</p>
<p>Do it really matter at the end of the day?</p>
<p>Thanks
Ian</p>
| <java><variables><enums><static> | 2016-06-19 11:20:45 | LQ_CLOSE |
37,907,495 | Getting error: Uncaught Syntax Error: Unexpected token | <p>I need to add class to all the links that have "href=login". And i tried to use this javascript</p>
<pre><code>jQuery(document).ready(function($){
$(.pageWidth).find('a[href*="/login/"]').addClass('OverlayTrigger');})
</code></pre>
<p>Unfortunately, i tried so many times and it always getting this error</p>
<blockquote>
<p>Uncaught Syntax Error: Unexpected token</p>
</blockquote>
<p>How can i fix this? What's the problem here?
Thank you!</p>
| <javascript> | 2016-06-19 12:58:45 | LQ_CLOSE |
37,907,568 | ratingbar not working (not clickable) when using ratingBarStyleSmall style | <p>ratingbar didn't change when the user click on it ?</p>
<p>her is my xml code </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.soulhis.testmaterialdesign.Test">
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ratingBar4"
android:layout_centerVertical="true"
style="?android:attr/ratingBarStyleSmall"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</code></pre>
<p>the problem occur just when using ratingBarStyleSmall
tested on android jellybean api level 17 </p>
| <android><xml><ratingbar> | 2016-06-19 13:06:30 | HQ |
37,908,160 | Is this a possible bug in .Net Native compilation and optimization? | <p>I discovered an issue with (what might be) over-optimization in <code>.Net Native</code> and <code>structs</code>. I'm not sure if the compiler is too aggressive, or I'm too blind to see what I've done wrong. </p>
<p>To reproduce this, follow these steps:</p>
<p><strong>Step 1</strong>: Create a new Blank Universal (win10) app in <em>Visual Studio 2015 Update 2</em> targeting build 10586 with a min build of 10240. Call the project <em>NativeBug</em> so we have the same namespace.</p>
<p><strong>Step 2</strong>: Open <code>MainPage.xaml</code> and insert this label</p>
<pre><code><Page x:Class="NativeBug.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<!-- INSERT THIS LABEL -->
<TextBlock x:Name="_Label" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</Page>
</code></pre>
<p><strong>Step 3</strong>: Copy/paste the following into <code>MainPage.xaml.cs</code></p>
<pre><code>using System;
using System.Collections.Generic;
namespace NativeBug
{
public sealed partial class MainPage
{
public MainPage()
{
InitializeComponent();
var startPoint = new Point2D(50, 50);
var points = new[]
{
new Point2D(100, 100),
new Point2D(100, 50),
new Point2D(50, 100),
};
var bounds = ComputeBounds(startPoint, points, 15);
_Label.Text = $"{bounds.MinX} , {bounds.MinY} => {bounds.MaxX} , {bounds.MaxY}";
}
private static Rectangle2D ComputeBounds(Point2D startPoint, IEnumerable<Point2D> points, double strokeThickness = 0)
{
var lastPoint = startPoint;
var cumulativeBounds = new Rectangle2D();
foreach (var point in points)
{
var bounds = ComputeBounds(lastPoint, point, strokeThickness);
cumulativeBounds = cumulativeBounds.Union(bounds);
lastPoint = point;
}
return cumulativeBounds;
}
private static Rectangle2D ComputeBounds(Point2D fromPoint, Point2D toPoint, double strokeThickness)
{
var bounds = new Rectangle2D(fromPoint.X, fromPoint.Y, toPoint.X, toPoint.Y);
// ** Uncomment the line below to see the difference **
//return strokeThickness <= 0 ? bounds : bounds.Inflate2(strokeThickness);
return strokeThickness <= 0 ? bounds : bounds.Inflate1(strokeThickness);
}
}
public struct Point2D
{
public readonly double X;
public readonly double Y;
public Point2D(double x, double y)
{
X = x;
Y = y;
}
}
public struct Rectangle2D
{
public readonly double MinX;
public readonly double MinY;
public readonly double MaxX;
public readonly double MaxY;
private bool IsEmpty => MinX == 0 && MinY == 0 && MaxX == 0 && MaxY == 0;
public Rectangle2D(double x1, double y1, double x2, double y2)
{
MinX = Math.Min(x1, x2);
MinY = Math.Min(y1, y2);
MaxX = Math.Max(x1, x2);
MaxY = Math.Max(y1, y2);
}
public Rectangle2D Union(Rectangle2D rectangle)
{
if (IsEmpty)
{
return rectangle;
}
var newMinX = Math.Min(MinX, rectangle.MinX);
var newMinY = Math.Min(MinY, rectangle.MinY);
var newMaxX = Math.Max(MaxX, rectangle.MaxX);
var newMaxY = Math.Max(MaxY, rectangle.MaxY);
return new Rectangle2D(newMinX, newMinY, newMaxX, newMaxY);
}
public Rectangle2D Inflate1(double value)
{
var halfValue = value * .5;
return new Rectangle2D(MinX - halfValue, MinY - halfValue, MaxX + halfValue, MaxY + halfValue);
}
public Rectangle2D Inflate2(double value)
{
var halfValue = value * .5;
var x1 = MinX - halfValue;
var y1 = MinY - halfValue;
var x2 = MaxX + halfValue;
var y2 = MaxY + halfValue;
return new Rectangle2D(x1, y1, x2, y2);
}
}
}
</code></pre>
<p><strong>Step 4</strong>: Run the application in <code>Debug</code> <code>x64</code>. You should see this label:</p>
<blockquote>
<p>42.5 , 42.5 => 107.5 , 107.5</p>
</blockquote>
<p><strong>Step 5</strong>: Run the application in <code>Release</code> <code>x64</code>. You should see this label:</p>
<blockquote>
<p>-7.5 , -7.5 => 7.5, 7.5</p>
</blockquote>
<p><strong>Step 6</strong>: Uncomment <code>line 45</code> in <code>MainPage.xaml.cs</code> and repeat step 5. Now you see the original label</p>
<blockquote>
<p>42.5 , 42.5 => 107.5 , 107.5</p>
</blockquote>
<hr>
<p>By commenting out <code>line 45</code>, the code will use <code>Rectangle2D.Inflate2(...)</code> which is exactly the same as <code>Rectangle2D.Inflate1(...)</code> except it creates a local copy of the computations before sending them to the constructor of <code>Rectangle2D</code>. In debug mode, these two function exactly the same. In release however, something is getting optimized out.</p>
<p>This was a nasty bug in our app. The code you see here was stripped from a much larger library and I'm afraid there might be more. Before I report this to Microsoft, I would appreciate it if you could take a look and let me know why <code>Inflate1</code> doesn't work in release mode. Why do we have to create local copies?</p>
| <c#><struct><uwp><compiler-optimization><.net-native> | 2016-06-19 14:15:57 | HQ |
37,909,102 | What is the best javascript "time ago" package where I can control formatting? | <p>I want to use a time ago plugin like timeago or livestamp.js but I want to control the formatting to something like this:</p>
<p>1s ago<br>
5s ago<br>
1m25s ago<br>
1h3m ago<br></p>
<p>Is there a way to do that with either of the above mentioned plugins or is there a better time ago plugin you recommend?</p>
| <javascript><livestamp.js> | 2016-06-19 15:59:16 | LQ_CLOSE |
37,911,051 | Can you still use c++ in Xcode? | I want to learn c++ on my Mac computer. A lot of forums recommend using Xcode, but when I downloaded it I realized that it only has options for Swift or Objective c. Is there still a way to use c++ in Xcode? Or is Objective c or Swift very similar to c++? | <c++><xcode><macos> | 2016-06-19 19:32:01 | LQ_EDIT |
37,911,174 | Via/ViaMat/to/toMat in Akka Stream | <p>Can someone explain clearly what are the difference between those 4 methods ? When is it more appropriate to use each one ? Also generally speaking what is the name of this Group of method? Are there more method that does the same job ? A link to the scaladoc could also help. </p>
<p>-D-</p>
| <akka-stream> | 2016-06-19 19:46:08 | HQ |
37,911,838 | How to use MongoDB with promises in Node.js? | <p>I've been trying to discover how to use MongoDB with Node.js and in the docs it seems the suggested way is to use callbacks. Now, I know that it is just a matter of preference, but I really prefer using promises.</p>
<p>The problem is that I didn't find how to use them with MongoDB. Indeed, I've tried the following:</p>
<pre><code>var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/example';
MongoClient.connect(url).then(function (err, db) {
console.log(db);
});
</code></pre>
<p>And the result is <code>undefined</code>. In that case it seems this is not the way to do so.</p>
<p>Is there any way to use mongo db inside Node with promises instead of callbacks?</p>
| <javascript><node.js><mongodb> | 2016-06-19 21:03:57 | HQ |
37,912,161 | How can I compute element-wise conditionals on batches in TensorFlow? | <p>I basically have a batch of neuron activations of a layer in a tensor <code>A</code> of shape <code>[batch_size, layer_size]</code>. Let <code>B = tf.square(A)</code>. Now I want to compute the following conditional on each element in each vector in this batch: <code>if abs(e) < 1: e β 0 else e β B(e)</code> where <code>e</code> is the element in <code>B</code> that is at the same position as <code>e</code>. Can I somehow vectorize the entire operation with a single <code>tf.cond</code> operation?</p>
| <tensorflow> | 2016-06-19 21:46:07 | HQ |
37,913,103 | what are ( Angular, Node.js, AJAX, JQuery)? | <p>I really have a hard time to distinguish between all those frameworks, libraries or API I don't know, and how they related to each if they do.</p>
| <javascript><jquery><angularjs><ajax><node.js> | 2016-06-20 00:05:02 | LQ_CLOSE |
37,913,482 | What's that mean each code | struct Physics {
static let smallCoin : UInt32 = 0x1 << 1
static let smallCoin2 : UInt32 = 0x1 << 2
static let ground : UInt32 = 0x1 << 3
}
What that mean
UInt32 = 0x1 << 1 ?
and static let ? | <ios><swift><struct><sprite-kit><swift2> | 2016-06-20 01:17:06 | LQ_EDIT |
37,914,907 | How to create horizontal funnel like this? | <p>I wish there was a horizontal funnel plugin available in the market. I'm not a good js developer but I'm a designer with html/css skills in hand. I have designed similar funnel like below in psd but I couldn't find any plugin to plug in into the html. The funnel links should be dynamically adjusted too. Please suggest me how to build similar kind of funnel with steps title, conversion % on the second row in the funnel columns. I've also created this in css but css doesn't work because the funnel columns should be totally dynamic.</p>
<p><a href="https://i.stack.imgur.com/Eo9Qz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Eo9Qz.png" alt="Hotjar funnel image"></a></p>
| <javascript><jquery><css><canvas><svg> | 2016-06-20 05:02:56 | LQ_CLOSE |
37,916,100 | Textsize based on the screen size | <blockquote>
<p>How to set the size of the text in text view based on the screen size and to scale dynamically based on height and width of the screen without creating different folders based on the resolution in android.</p>
</blockquote>
<p>Thanks in advance</p>
| <android> | 2016-06-20 06:44:23 | LQ_CLOSE |
37,917,373 | Java - make class required for other class | <p>i have 2 class, planet and moon, my plan is to make moon class require planet class, so first i create planet and then create moon, how to do it?
my planet class :</p>
<pre><code>public class planet {
//planet name
private String namaPlanet;
//total moon per planet
private int jmlBulan;
//revolution and rotation
private double jmlRotasi, jmlRevolusi;
public planet(String namaPlanet, int jmlBulan, double jmlJamPhari, double jmlHariPtahun) {
this.namaPlanet = namaPlanet;
this.jmlBulan = jmlBulan;
this.jmlRotasi = jmlJamPhari;
this.jmlRevolusi = jmlHariPtahun;
}
public planet(String namaPlanet, double jmlRotasi, double jmlRevolusi) {
this.namaPlanet = namaPlanet;
this.jmlRotasi = jmlRotasi;
this.jmlRevolusi = jmlRevolusi;
}
}
</code></pre>
<p>moon class :</p>
<pre><code>public class bulan extends planet {
private String namaBulan;
public bulan(String namaBulan, String namaPlanet,double jmlJamPhari, double jmlHariPtahun) {
super(namaPlanet, jmlJamPhari, jmlHariPtahun);
this.namaBulan = namaBulan;
}
}
</code></pre>
| <java> | 2016-06-20 08:04:39 | LQ_CLOSE |
37,917,829 | I want to develop 2d web game. What game engine should I choose? | <p>I want to write in compiled language.</p>
<p>Please suggest me some engines those run on web browser.</p>
<p>Please don't suggest Unity and Unreal Engine because they require web player and this web player does not support Linux</p>
| <web><2d><game-engine> | 2016-06-20 08:33:06 | LQ_CLOSE |
37,918,511 | How we can convert Zthes format of Ontology in RDF/XML format? | I have used smartlogic semaphore, which uses ZThes Format for Ontologies. Now, i have Zthes Format of an Ontology. I want to convert this into RDF/XML format. | <rdf><ontology><skos> | 2016-06-20 09:06:24 | LQ_EDIT |
37,919,082 | Android Error [java.lang.NullPointerException: 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference] | <p>I have my main which contain a menu drawer with some fragments. Then a host page before to display the main. I have some errors about that <code>Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference</code></p>
<p>I tried to change it <code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);</code>
but still nothing even with <code>public class MainActivity extends Activity {</code> or <code>public class MainActivity extends AppcompactActivity {</code></p>
<p>There is my main:</p>
<pre><code> package thyroid.com.thyroid;
import thyroid.com.thyroid.adapter.NavDrawerListAdapter;
import thyroid.com.thyroid.model.NavDrawerItem;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private ActionBar getSupportActionBar() {
return null;
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://thyroid.com.thyroid/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://thyroid.com.thyroid/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
/**
* Slide menu item click listener
*/
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new LoginFragment();
break;
case 1:
fragment = new RegisterFragment();
break;
case 2:
fragment = new LoginFragment();
break;
case 3:
fragment = new LoginFragment();
break;
case 4:
fragment = new LoginFragment();
break;
case 5:
fragment = new LoginFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
</code></pre>
<p>Here one of the fragment:</p>
<pre><code> package thyroid.com.thyroid;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import thyroid.com.thyroid.model.ServerRequest;
import thyroid.com.thyroid.model.ServerResponse;
import thyroid.com.thyroid.model.User;
public class LoginFragment extends Fragment implements View.OnClickListener{
private AppCompatButton btn_login;
private EditText et_email,et_password;
private TextView tv_register,tv_reset_password;
private ProgressBar progress;
private SharedPreferences pref;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login,container,false);
initViews(view);
return view;
}
private void initViews(View view){
pref = getActivity().getPreferences(0);
btn_login = (AppCompatButton)view.findViewById(R.id.btn_login);
tv_register = (TextView)view.findViewById(R.id.tv_register);
tv_reset_password = (TextView)view.findViewById(R.id.tv_reset_password);
et_email = (EditText)view.findViewById(R.id.et_email);
et_password = (EditText)view.findViewById(R.id.et_password);
progress = (ProgressBar)view.findViewById(R.id.progress);
btn_login.setOnClickListener(this);
tv_register.setOnClickListener(this);
tv_reset_password.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_register:
goToRegister();
break;
case R.id.btn_login:
String email = et_email.getText().toString();
String password = et_password.getText().toString();
if(!email.isEmpty() && !password.isEmpty()) {
progress.setVisibility(View.VISIBLE);
loginProcess(email,password);
} else {
Snackbar.make(getView(), "Fields are empty !", Snackbar.LENGTH_LONG).show();
}
break;
case R.id.tv_reset_password:
goToResetPassword();
break;
}
}
private void loginProcess(String email,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,true);
editor.putString(Constants.EMAIL,resp.getUser().getEmail());
editor.putString(Constants.NAME,resp.getUser().getName());
editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
editor.apply();
goToProfile();
}
progress.setVisibility(View.INVISIBLE);
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG,"failed");
Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
private void goToResetPassword(){
Fragment reset = new Fragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,reset);
ft.commit();
}
private void goToRegister(){
Fragment register = new RegisterFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,register);
ft.commit();
}
private void goToProfile(){
Fragment profile = new ProfileFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,profile);
ft.commit();
}
}
</code></pre>
<p>And now the .class which is the "host page" before the main:</p>
<pre><code>package thyroid.com.thyroid;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import static thyroid.com.thyroid.R.id.button;
public class SplashScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
Button button = (Button) findViewById(R.id.button);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),MainActivity.class);
startActivityForResult(intent,0);
}
});
Thread timerThread = new Thread() {
public void run() {
try {
sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
}
}
};
timerThread.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
</code></pre>
<p>This is my errors:</p>
<pre><code>06-20 11:23:33.603 29939-29939/thyroid.com.thyroid E/AndroidRuntime: FATAL EXCEPTION: main
Process: thyroid.com.thyroid, PID: 29939
java.lang.RuntimeException: Unable to start activity ComponentInfo{thyroid.com.thyroid/thyroid.com.thyroid.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at thyroid.com.thyroid.MainActivity.onCreate(MainActivity.java:101)
at android.app.Activity.performCreate(Activity.java:5976)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
</code></pre>
| <java><android-fragments><android-actionbar><fragment><drawer> | 2016-06-20 09:34:38 | LQ_CLOSE |
37,919,328 | SearchView hint not showing | <p>I'm trying to display hint text in a search view in my Main Activity. The onqueryTextSubmit launches another activity called SearchResultsActivity which will display the results of the query. My problem is that I cannot display the hint text. My searchable.xml code</p>
<pre><code><searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:label="@string/app_name"
/>
</code></pre>
<p>and the manifest code
</p>
<pre><code><application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data
android:name="android.app.default_searchable1"
android:value=".SearchResultsActivity"
android:resource="@xml/searchable"/>
</activity>
<activity android:name=".SearchResultsActivity">
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable">
</meta-data>
</activity>
</application>
</manifest>
</code></pre>
<p>and finaly my onQueryTextSubmit code</p>
<pre><code>@Override
public boolean onQueryTextSubmit(String query)
{
Anniversaries tempResults;
tempResults = mainAnniversariesManager.searchManager.searchAnniversaries(query);
if (tempResults.entries.size() == 0)
{
snackbar = Snackbar.make(findViewById(R.id.coordinator), getString(R.string.no_results_found) + query, Snackbar.LENGTH_INDEFINITE);
snackbar.show();
return true;
} else
{
snackbar = null;
if (!searchView.isIconified())
{
searchView.setIconified(true);
}
menuItem.collapseActionView();
Intent intent=new Intent(getApplicationContext(),SearchResultsActivity.class);
Bundle args=new Bundle();
args.putSerializable("serialized_Anniversaries",tempResults);
intent.putExtra("args",args);
startActivity(intent);
return false;
}
}
</code></pre>
<p>Thanks in advance</p>
| <android><android-manifest><searchview> | 2016-06-20 09:48:01 | HQ |
37,919,952 | Local Storage not storing/retrieving value | <p>This is my code:</p>
<pre><code> <select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onchange="document.form.submit();">
<script>
var cat = localStorage.getItem('category');
localStorage.setItem('category', cat);
</script>
<option value="" disabled selected>Select Category</option>
<?php
$sth = $conn->prepare('Select name From category');
$sth->execute();
$data = $sth->fetchAll();
foreach ($data as $row ){
if($row['name']!="")
echo ' <option id=\"CategoryName\" nameCategoryNameVendorName\" value="' .$row['name']. '">'.$row['name'].'</option>';
}
?>
</select>
</code></pre>
<p>I want the selected value of the drop down 'category' to be retrieved in the drop down even after the page is submitted by <code>onchange="document.form.submit();"</code>. Why isn't it happening?</p>
| <javascript><php><html> | 2016-06-20 10:18:14 | LQ_CLOSE |
37,920,023 | could not find implicit value for evidence parameter of type org.apache.flink.api.common.typeinfo.TypeInformation[...] | <p>I am trying to write some use cases for Apache Flink. One error I run into pretty often is</p>
<pre><code>could not find implicit value for evidence parameter of type org.apache.flink.api.common.typeinfo.TypeInformation[SomeType]
</code></pre>
<p>My problem is that I cant really nail down when they happen and when they dont.</p>
<p>The most recent example of this would be the following</p>
<pre><code>...
val largeJoinDataGen = new LargeJoinDataGen(dataSetSize, dataGen, hitRatio)
val see = StreamExecutionEnvironment.getExecutionEnvironment
val newStreamInput = see.addSource(largeJoinDataGen)
...
</code></pre>
<p>where <code>LargeJoinDataGen extends GeneratorSource[(Int, String)]</code> and <code>GeneratorSource[T] extends SourceFunction[T]</code>, both defined in separate files.</p>
<p>When trying to build this I get</p>
<pre><code>Error:(22, 39) could not find implicit value for evidence parameter of type org.apache.flink.api.common.typeinfo.TypeInformation[(Int, String)]
val newStreamInput = see.addSource(largeJoinDataGen)
</code></pre>
<p><strong>1. Why is there an error in the given example?</strong></p>
<p><strong>2. What would be a general guideline when these errors happen and how to avoid them in the future?</strong></p>
<p>P.S.: first scala project and first flink project so please be patient</p>
| <scala><apache-flink><flink-streaming> | 2016-06-20 10:21:16 | HQ |
37,920,103 | Multiple value in a dictionary key | <p>Is there any way to add multiple value in a dictionary key one by one. Suppose we have dictionary Dict and we want to insert value 3 and 4 with the associated key "xxx", 9 and 10 with key YYY. I want to add them one by one not by making a list.</p>
<p>Example is like this</p>
<pre><code>Dict[xxx]=3
Dict[YYY]=9
Dict[xxx]=4
Dict[YYY]=10
</code></pre>
<p>In this way the last value is retaining with the key XXX. Any other way to do this. Please let me know.</p>
| <python> | 2016-06-20 10:25:02 | LQ_CLOSE |
37,921,913 | Java and haarcascade face and mouth detection - mouth as the nose | <p>Today I begin to test the project which detects a smile in Java and OpenCv. To recognition face and mouth project used haarcascade_frontalface_alt and haarcascade_mcs_mouth But i don't understand why in some reasons project detect nose as a mouth.
I have two methods:</p>
<pre><code>private ArrayList<Mat> detectMouth(String filename) {
int i = 0;
ArrayList<Mat> mouths = new ArrayList<Mat>();
// reading image in grayscale from the given path
image = Highgui.imread(filename, Highgui.CV_LOAD_IMAGE_GRAYSCALE);
MatOfRect faceDetections = new MatOfRect();
// detecting face(s) on given image and saving them to MatofRect object
faceDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
MatOfRect mouthDetections = new MatOfRect();
// detecting mouth(s) on given image and saving them to MatOfRect object
mouthDetector.detectMultiScale(image, mouthDetections);
System.out.println(String.format("Detected %s mouths", mouthDetections.toArray().length));
for (Rect face : faceDetections.toArray()) {
Mat outFace = image.submat(face);
// saving cropped face to picture
Highgui.imwrite("face" + i + ".png", outFace);
for (Rect mouth : mouthDetections.toArray()) {
// trying to find right mouth
// if the mouth is in the lower 2/5 of the face
// and the lower edge of mouth is above of the face
// and the horizontal center of the mouth is the enter of the face
if (mouth.y > face.y + face.height * 3 / 5 && mouth.y + mouth.height < face.y + face.height
&& Math.abs((mouth.x + mouth.width / 2)) - (face.x + face.width / 2) < face.width / 10) {
Mat outMouth = image.submat(mouth);
// resizing mouth to the unified size of trainSize
Imgproc.resize(outMouth, outMouth, trainSize);
mouths.add(outMouth);
// saving mouth to picture
Highgui.imwrite("mouth" + i + ".png", outMouth);
i++;
}
}
}
return mouths;
}
</code></pre>
<p>and detect smile</p>
<pre><code>private void detectSmile(ArrayList<Mat> mouths) {
trainSVM();
CvSVMParams params = new CvSVMParams();
// set linear kernel (no mapping, regression is done in the original feature space)
params.set_kernel_type(CvSVM.LINEAR);
// train SVM with images in trainingImages, labels in trainingLabels, given params with empty samples
clasificador = new CvSVM(trainingImages, trainingLabels, new Mat(), new Mat(), params);
// save generated SVM to file, so we can see what it generated
clasificador.save("svm.xml");
// loading previously saved file
clasificador.load("svm.xml");
// returnin, if there aren't any samples
if (mouths.isEmpty()) {
System.out.println("No mouth detected");
return;
}
for (Mat mouth : mouths) {
Mat out = new Mat();
// converting to 32 bit floating point in gray scale
mouth.convertTo(out, CvType.CV_32FC1);
if (clasificador.predict(out.reshape(1, 1)) == 1.0) {
System.out.println("Detected happy face");
} else {
System.out.println("Detected not a happy face");
}
}
}
</code></pre>
<p>Examples:</p>
<p>For that picture </p>
<p><a href="https://i.stack.imgur.com/9b83D.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/9b83D.jpg" alt="enter image description here"></a></p>
<p>correctly detects this mounth:</p>
<p><a href="https://i.stack.imgur.com/ikQpM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ikQpM.png" alt="enter image description here"></a></p>
<p>but in other picture </p>
<p><a href="https://i.stack.imgur.com/t7Hg8.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/t7Hg8.jpg" alt="enter image description here"></a></p>
<p>nose is detected
<a href="https://i.stack.imgur.com/uFWLa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uFWLa.png" alt="enter image description here"></a></p>
<p>What's the problem in your opinion ?</p>
| <java><opencv><face-detection><haar-classifier> | 2016-06-20 11:54:07 | HQ |
37,922,829 | intelliJ IDEA "Overrides method" warning with Java 8 lambda expressions | <p>I get a warning "Overrides method in java.util.function.Function" when using lambda expressions like
<code>new Vector<String>().stream().map(String::toString);</code> but as far as I know this is just normal lambda usage. How can I get rid of this warning without removing legitimate override warnings?</p>
<p>I use intelliJ IDEA 2016.1.3 with OpenJDK 8 on Gnome on Arch Linux.</p>
| <intellij-idea><compiler-warnings> | 2016-06-20 12:39:58 | HQ |
37,923,261 | Angular 1.5 component with ng-model | <p>Is it possible to use ng-model with a component? I would like to bind a scope variable to a component with ng-model. I have <a href="http://plnkr.co/edit/72XTUweimR2fzXg35xet?p=preview">plunkered my issue</a>. I would like the component my-input to be binded to the variable from the scope userData.name.</p>
<p>I am using Angular JS 1.5.6 components, and want to avoid using directive.</p>
<pre><code><body ng-controller="MyCtrl">
<div class="container">
<h2>My form with component</h2>
<form role="form">
<div class="form-group">
<label>First name</label>
<my-input placeholder="Enter first name" ng-model="userData.name"></my-input>
</div>
</form>
</div>
</body>
</code></pre>
| <javascript><angularjs> | 2016-06-20 12:59:51 | HQ |
37,923,383 | Andorid You must supply a layout_width attribute | below xml layout is my simple application layout, but after compile application i get this error:
Unable to start activity ComponentInfo{ir.pishguy.signalpresentationproject/ir.pishguy.
signalpresentationproject.Activities.ActivityMain}:
android.view.InflateException:
Binary XML file line #147: Binary XML file line #147:
You must supply a layout_width attribute.
my all widgets have `layout_width` but i dont know why i get this error
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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">
xmlns:android="http://schemas.android.com/apk/res/android"/>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<!--<android.support.v4.widget.SwipeRefreshLayout-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="65dp"
android:background="@color/signal_toolbar_color"
android:titleTextColor="#ffffff">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<com.joanzapata.iconify.widget.IconTextView
android:id="@+id/signal_robot"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:clickable="true"
android:gravity="center|right"
android:shadowColor="#22000000"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="{fa-android}"
android:textColor="@color/quote"
android:textSize="25sp"/>
<com.joanzapata.iconify.widget.IconTextView
android:id="@+id/search_icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center|right"
android:shadowColor="#22000000"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="{fa-search}"
android:textColor="#ffffff"
android:textSize="25sp"/>
<com.gigamole.library.ntb.NavigationTabBar
android:id="@+id/navigationTabBar"
android:layout_width="150dp"
android:layout_height="30dp"
android:layout_gravity="center_vertical|left"
android:background="@drawable/bg_round_circle"
app:ntb_active_color="#4527A0"
app:ntb_animation_duration="150"
app:ntb_corners_radius="50dp"
app:ntb_inactive_color="#dddfec"
app:ntb_preview_colors="@array/red_wine"/>
<TextView
android:id="@+id/activity_market_robot_title"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:gravity="center|right"
android:text="@string/app_name"
android:textColor="#ffffff"
android:textSize="18sp"/>
</LinearLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<!-- android.support.v4.widget.NestedScrollView -->
<android.support.v4.view.ViewPager
android:id="@+id/vp_horizontal_ntb"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/activity_main_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="20dp"
android:clickable="true"
android:src="@drawable/ic_add_circle_outline"
android:tint="@color/white"
android:visibility="gone"
app:backgroundTint="@color/signal_secondary_color"
app:layout_behavior="ir.pishguy.signalpresentationproject.Configurations.ScrollAwareFABBehavior"/>
<ir.pishguy.signalpresentationproject.Widgets.CircularRevealView
android:id="@+id/market_item_reveal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"/>
</android.support.design.widget.CoordinatorLayout>
<com.lapism.searchview.SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout> | <android> | 2016-06-20 13:05:20 | LQ_EDIT |
37,923,431 | AntiXSS in ASP.Net Core | <p><a href="https://wpl.codeplex.com/" rel="noreferrer">Microsoft Web Protection Library (AntiXSS)</a> has reached End of Life. The page states "In .NET 4.0 a version of AntiXSS was included in the framework and could be enabled via configuration. In ASP.NET v5 a white list based encoder will be the only encoder."</p>
<p>I have a classic cross site scripting scenario: An ASP.Net Core solution where users can edit text using a WYSIWYG html-editor. The result is displayed for others to see. This means that if users inject a JavaScript into the data they submit when saving the text this code could execute when others visits the page. </p>
<p>I want to be able to whitelist certain HTML-codes (safe ones), but strip out bad codes.</p>
<p>How do I do this? I can't find any methods in ASP.Net Core RC2 to help me. Where is this white list encoder? How do I invoke it? For example I would need to clean output being returned via JSON WebAPI.</p>
| <xss><asp.net-core-1.0> | 2016-06-20 13:07:46 | HQ |
37,923,481 | Convert date string swift | <p>I have a date string in this format:</p>
<pre><code>2016-06-20T13:01:46.457+02:00
</code></pre>
<p>and I need to change it to something like this:</p>
<pre><code>20/06/2016
</code></pre>
<p>Previously I have always used this library -> <a href="https://github.com/malcommac/SwiftDate/blob/master/Documentation/UserGuide.md" rel="noreferrer">SwiftDate</a> to manipulate the dates, but it doesn't work now.</p>
<p>I tried also something like:</p>
<pre><code>let myDate = self.dateNoteDict[indexPath.row]!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
let date = dateFormatter.dateFromString(myDate)
print("date -> \(date)")
</code></pre>
<p>but it doesn't work. How can I do?</p>
<p>Thanks in advance.</p>
| <ios><swift><date><nsdate><nsdateformatter> | 2016-06-20 13:10:19 | HQ |
37,923,864 | Java - grouping identical exceptions in logs | <p>Is there any logging solution with exception grouping feature? What I want to achieve is when some exception is logged for example 100 times in 10 seconds I don't want to log 100 stack traces. I want to log something like <code>RuntimeException was thrown 100 times: single stack trace here</code>. It'd perfect to have something integrated with <code>log4j</code>.</p>
<p>Ofc there is an option to create some logging facade with exception queue inside but maybe there is something already implemented.</p>
| <java><logging><log4j> | 2016-06-20 13:28:57 | HQ |
37,924,068 | Passing data without ending a function C# (Creating a facebook's wall) | <p>Hey i am supposed to do a user activity log for a forum on each user profile (something similar to facebook's wall), i tried to make some huge database request but the efficiency is disappointing so i have to find another way to do this. So i've thought that maybe on each function (like voteup, votedown, write post, create topic etc) i'll be parsing a json to my logic and then from getting that json i'll be making some actions. But im not sure if its possible in C# and couldn't find any similar soultion on web. Maybe by making each function some kind of async i could get the goal? Or maybe some of you know a good tutorial or example with doing such a thing. </p>
| <c#><asp.net-mvc> | 2016-06-20 13:39:47 | LQ_CLOSE |
37,924,071 | Tensorflow: Writing an Op in Python | <p>I would like to write an Op in Python. This tutorial only explains how to do it in c++ with a Python wrapper.
<a href="https://www.tensorflow.org/versions/master/how_tos/adding_an_op/index.html#adding-a-new-op" rel="noreferrer">https://www.tensorflow.org/versions/master/how_tos/adding_an_op/index.html#adding-a-new-op</a></p>
<p>How can I write it completely in Python?</p>
| <tensorflow> | 2016-06-20 13:39:53 | HQ |
37,924,144 | Using function with return type Task<T>...c# | ASP.NET MVC 5/ C# .NEt 4.6.1
I had a function that did the following:
public class UserClass
{
public static CurrentUserData GetUserInfo()
{
CurrentUserData ui;
ui = GetUserData();
return ui;
}
}
My CurrentUserData object is as follows:
public class CurrentUserData
{
public bool ReadOnly{get;set;}
}
In my controller, I call my method and can see the ReadOnly property fine:
var user = UserClass.GetUserInfo();
if (user.ReadOnly)
{
////code to execute
}
I had to add an async call to my function, and now it looks likes this (I omitted code for brevity):
public static Task<CurrentUserData > GetUserInfo()
{
Task<CurrentUserData > ui;
ui = GetUserData();
HttpResponseMessage response = await httpClient.SendAsync(request);
return ui;
}
Notice the Task<T> I had to add. But when I call the method in my controller like before, I get the error:
Error CS1061 'Task<CurrentUserData >' does not contain a definition for
'ReadOnly' and no extension method 'ReadOnly' accepting a first argument of
type 'Task<CurrentUserData >' could be found (are you missing a using directive or
an assembly reference?)
What do I need to change so when any class calls my new Task<CurrentUserData > method, it will see all the properties of the object wrapped in Task<CurrentUserData >?
Thanks
| <c#><asp.net-mvc> | 2016-06-20 13:43:34 | LQ_EDIT |
37,924,377 | Does Pandas calculate ewm wrong? | <p>When trying to calculate the exponential moving average (EMA) from financial data in a dataframe it seems that Pandas' ewm approach is incorrect.</p>
<p>The basics are well explained in the following link:
<a href="http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages" rel="noreferrer">http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages</a></p>
<p>When going to Pandas explanation, the approach taken is as follows (using the "adjust" parameter as False):</p>
<pre><code> weighted_average[0] = arg[0];
weighted_average[i] = (1-alpha) * weighted_average[i-1] + alpha * arg[i]
</code></pre>
<p>This in my view is incorrect. The "arg" should be (for example) the closing values, however, arg[0] is the first average (i.e. the simple average of the first series of data of the length of the period selected), but NOT the first closing value. arg[0] and arg[i] can therefore never be from the same data. Using the "min_periods" parameter does not seem to resolve this.</p>
<p>Can anyone explain me how (or if) Pandas can be used to properly calculate the EMA of data?</p>
| <pandas><exponential><moving-average> | 2016-06-20 13:55:12 | HQ |
37,924,970 | How to access a remote MySQL database from Android Application | <p>I need some help
I've made a simple login application in android with a MySQL database and the PHP script and I'm using XAMPP. Everything works and the database takes the entries but only when my phone is connected to the same internet connection as my server is. When I try doing the same, suppose while my phone is connected to 3G, IT DOESN'T WORK</p>
| <php><android><mysql> | 2016-06-20 14:22:54 | LQ_CLOSE |
37,925,034 | Mockito asks to add @PrepareForTest for the class even after adding @PrepareForTest | <p>I have the following simple code. I have a class (TestClass) and I want to test "someMethod". There is an external static method which is called by my "someMethod".
I want to Powermock that static method to return me some dummy object.
I have the @PrepareForTest(ExternalClass.class) in the begining, but when I execute it gives the error:</p>
<p><em>The class ExternalClass not prepared for test.
To prepare this class, add class to the <code>'@PrepareForTest'</code> annotation.
In case if you don't use this annotation, add the annotation on class or method level.</em></p>
<p>Please help me to point out what is wrong with the way I have used <code>@PrepareForTest</code></p>
<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest(ExternalClass.class)
public class xyzTest {
@Mock
private RestTemplate restTemplate;
@Mock
private TestClass testClass;
@BeforeClass
private void setUpBeforeClass() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSuccessCase() {
Boolean mockResponse = true;
ResponseEntity<Boolean> response = new ResponseEntity<Boolean>(mockResponse, HttpStatus.OK);
SomeClass someClass = new SomeClass("test", "1.0.0", "someUrl", "someMetaData");
PowerMockito.mockStatic(ExternalClass.class);
Mockito.when(restTemplate.postForEntity(any(String.class), any(String.class), eq(Boolean.class))).thenReturn(response);
Mockito.when(ExternalClass.getSomeClass(any(String.class))).thenReturn(someClass);
Boolean result = testClass.someMethod("test");
Assert.isTrue(result);
Mockito.verify(restTemplate, times(1)).postForObject(any(String.class), any(String.class), any());
}
}
</code></pre>
| <java><mockito><powermock> | 2016-06-20 14:25:28 | HQ |
37,925,035 | Notepad plus plus shortcut for reloading files | <p>Is there any keyboard shortcut for reloading files in n++ ?
How can i configure my own?</p>
<p>Steps to reproduce:</p>
<ul>
<li>right click and reload on header tab.</li>
</ul>
| <notepad++> | 2016-06-20 14:25:33 | HQ |
37,925,946 | how can I convert string to list in python | <p>i am trying to parse a xml file, it works very well. I have string output, which i would like to make as list, but i doesnot work.
I get for tuple or list, that every line is a list...Somebody any idea?</p>
<pre><code>def handleToc(self,elements):
for element in elements:
self.name = element.getElementsByTagName("name")[0]
self.familyname = element.getElementsByTagName("family")[0]
#self.position = element.getElementsByTagName("position")[0].firstChild.nodeValue
position = element.getElementsByTagName("position")[0].firstChild.nodeValue
liste=position.encode('utf-8')
nameslist = [y for y in (x.strip() for x in liste.splitlines()) if y]
#print names_list[1:-1]
#print ''.join(repr(x).lstrip('u')[1:-1] for x in position)
#converted_degrees = {int(value) for value in position}
liste1=tuple(liste)
print liste
print list1
</code></pre>
<p>and the output is:
66.5499972
70.5500028
73.7
76.3
79.4499972
83.4500028
86.6
89.2</p>
| <python> | 2016-06-20 15:10:45 | LQ_CLOSE |
37,926,730 | Problems trying to save data to SQlite | <p>Since this is my second app, and my first app was 99% designing, this could be a duplicate because i might not be using the proper keywords for my searches, but i'm searching for 3 hours now for the solution, which is probably very simple, and i can't seem to find it.</p>
<p>When I try to save information to my database with 2 TextViews, 1 Spinner, and a Button, i get this error message:</p>
<pre><code>FATAL EXCEPTION: main
Process: nl.pluuk.gelduren, PID: 29876
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at nl.pluuk.gelduren.Add_client.saveData(Add_client.java:76)
at nl.pluuk.gelduren.Add_client$3.onClick(Add_client.java:67)
at android.view.View.performClick(View.java:5233)
at android.view.View$PerformClick.run(View.java:21209)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5497)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code></pre>
<p>This is my code which i'm currently using to not save any data</p>
<pre><code>public void save(){
save = (Button)findViewById(R.id.button_save_client);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("Save Button Clicked");
Client_textView = (TextView)findViewById(R.id.inputform_client_name);
Rate_textView = (TextView)findViewById(R.id.inputform_rate);
Pay_Period_textView = (Spinner)findViewById(R.id.spinner_pay_period);
Client = "" + Client_textView.getText();
Rate = Integer.parseInt("" + Rate_textView.getText());
Pay_Period = "" + Pay_Period_textView.getSelectedItem();
saveData();
}
});
}
public void saveData(){
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CLIENT_NAME, Client);
System.out.println("Yes, i'm in your log");
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_RATE, Rate);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_PAY_PERIOD, Pay_Period);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedReaderContract.FeedEntry.TABLE_NAME,
null,
values);
}
</code></pre>
<p>This code is all inside Add_client.
The error Add_client.java:76 is referring to the line: <code>SQLiteDatabase db = mDbHelper.getWritableDatabase();</code>
The error Add_client.java:67 is referring to the line: <code>saveData();</code>
Which is probably caused by line 76.</p>
<p>I made sure that there are columns inside the database, by executing <code>System.out.println("Column count:" + c.getColumnCount());</code></p>
<p>This told me that there where 3 columns, which is what I was expecting.
I also checked if there was any data inside the columns with:</p>
<pre><code>Boolean rowExists;
if (c.moveToFirst())
{
System.out.println(c.getColumnName(0));
rowExists = true;
} else
{
System.out.println("Nothing to see here");
rowExists = false;
}
</code></pre>
<p>This gave me the output: Nothing to see here, which is was also expecting because the database starts empty.</p>
<p>Where is the mistake in my code which keeps smashing me these errors?</p>
<p>Is there is any other information needed, I will be happily include it in an edit.</p>
| <java><android><sqlite> | 2016-06-20 15:50:07 | LQ_CLOSE |
37,926,940 | how to specify new environment location for conda create | <p>the default location for packages is .conda folder in my home directory. however, on the server I am using, there is a very strict limit of how much space I can use, which basically avoids me from putting anything under my home directory. how can I specify the location for the virtual environment that I want to create? Thanks! server is running Ubuntu. </p>
| <virtualenv><anaconda><conda> | 2016-06-20 16:00:04 | HQ |
37,927,065 | Textbox,Database,Gridview,Error or succes messages | <p>if user inserted value in textbox present in database then show to gridview(display in grid view) else error message in c#..
If successfully found then show else show that data not found as you inserted in textbox.....Hlep me<a href="http://i.stack.imgur.com/RRO7w.png" rel="nofollow">enter image description here</a></p>
| <c#><sql><gridview> | 2016-06-20 16:05:27 | LQ_CLOSE |
37,927,553 | Can clang-format break my code? | <p>As <code>clang-format</code> is a tool to only reformat code, is it possible that such formatting can break working code or at least change how it works? Is there some kind of contract that it will/can not change how code works?</p>
<p>We have a lot of code that we want to format with <code>clang-format</code>. This means, many lines of code will change. Not having to review every single line of code that only changed due to a <code>clang-format</code> would be a big simplification of this process.</p>
<p>I would say that <code>clang-format</code> will not change how code works. On the other hand I am not 100% sure, if this can be guaranteed.</p>
| <c><clang-format> | 2016-06-20 16:32:53 | HQ |
37,927,772 | how to silence warnings about ignored files in eslint | <p>After setting up <code>eslint</code> and adding some files in the ignore list, every time that eslint is run it produces warnings about files that are ignored:</p>
<pre><code> /path/to/file/name.min.js
0:0 warning File ignored because of a matching ignore pattern. Use "--no-ignore" to override
</code></pre>
<p>How can this warning be silenced?</p>
| <eslint> | 2016-06-20 16:46:11 | HQ |
37,928,077 | A single column with many values separated by semicolon, R | <p>I have a column with 1000 rows. Each row has 5000 values all separated with semicolon. I like to turn this column into a matrix of 1000 x 5000 dimension.
How can I do this in R?</p>
<p>Thanks,
Aaron</p>
| <r> | 2016-06-20 17:04:10 | LQ_CLOSE |
37,928,998 | How to use a jQuery plugin inside Vue | <p>I'm building a web application inside VueJS but I encounter a problem. I want to use a jQuery extension (cropit to be specific) but I don't know how to instantiate/require/import it the right way without getting errors.</p>
<p>I'm using de official CLI tool and de webpack template for my App.</p>
<p>I included jQuery like this in my main.js file:</p>
<pre><code>import jQuery from 'jQuery'
window.jQuery = jQuery
</code></pre>
<p>Now I'm building an image editor component where I want to instantiate crept like this: </p>
<pre><code>export default {
ready () {
$(document).ready(function ($) {
$('#image-cropper-wrapper-element').cropit({ /* options */ })
})
},
}
</code></pre>
<p>But I keep getting errors...Now my question is how to properly instantiate jQuery and plugins via NPM/Webpack/Vue?</p>
<p>Thanks in advance!</p>
| <jquery><jquery-plugins><webpack><vue.js> | 2016-06-20 18:03:35 | HQ |
37,929,026 | Get local currency in swift | <p>I am setting up an little in app purchase store for muliple countries. How can I figure out that I have to show up the price in Dollar, Euro etc...
I think it have to do with the localeIdentifier but I am not sure how to handle this</p>
| <xcode><swift><locale><currency> | 2016-06-20 18:05:20 | HQ |
37,929,173 | Significance of port 3000 in Express apps | <p>I noticed that almost all examples of Express.js applications use port 3000 as the default listening port for HTTP servers. Is this just because it's a rarely used port, or is there any other reason for this port number?</p>
<p>If I want to run multiple apps side-by-side on my local machine, is it good practice to use ports like 3000, 3001, 3002, etc.?</p>
<p>(I understand that ideally, you'd let the system assign ports. This is just a question as a matter of simplicity, and why 3000 seems to be a conventional assignment.)</p>
| <node.js><http><express><port> | 2016-06-20 18:15:31 | HQ |
37,929,422 | What is the different between Docker bundles and docker-compose? | <p>Docker 1.12 introduced the new concept of bundles. A new file format to describe a set of services.</p>
<p>My application is already deployed with <em>docker-compose</em>. I have a <code>docker-compose.yml</code> for each of my environments and I can quickly deploy my app just with a <code>docker-compose up</code>.</p>
<p>From what I understand of <a href="https://blog.docker.com/2016/06/docker-app-bundle/">this post</a>, <em>Docker bundles</em> is just a new way built-in Docker to do the same thing as docker-compose does as an external software.</p>
<p>Is that it ? What can I expect from <em>Docker bundles</em> that I won't have with <em>docker-compose</em> ?</p>
| <docker><docker-compose> | 2016-06-20 18:31:04 | HQ |
37,929,563 | How to insert objects from a List into a dataTable in sql server using linq to sql | i'm new in programming and i'm trying to insert a list of objects using linq to sql and only the last object from the list gets inserted into the dataBase. Can someone help me find the problem?
This is my code:
//this is the code in the orderDetailRepository class
public List<OrderDetail> CreateOrderDetailRecords(List<OrderDetail> details)
{
FruitStoreDataContext db = new FruitStoreDataContext();
db.OrderDetails.InsertAllOnSubmit(details);
db.SubmitChanges();
return details;
}
//this is the code in the Form.cs file when i press the "finish button"
private void FinishButton_Click(object sender, EventArgs e)
{
OrderDetailRepository orderDetailRepo = new OrderDetailRepository();
orderDetailRepo.CreateOrderDetailRecords(Ord);
//Ord is the name of the list of OrderDetail Objects that i created...
TotalCostLabel.Visible = true;
TotalCostLabel.Text = "$" + totalCost;
}
| <c#><linq-to-sql> | 2016-06-20 18:38:43 | LQ_EDIT |
37,929,743 | ruby check if a jpeg is readable | Ruby newby here<br />
I am downloading pictures with open-Uri and sometimes, the downloaded picture is corrupted and cannot be opened with a picture viewer (or another program capable of displaying pictures)<br />
Is there a simple method to determine if the downloaded picture is corrupted an cannot be read by other programs?<br />
Thanks<br /> | <ruby><jpeg><open-uri> | 2016-06-20 18:50:41 | LQ_EDIT |
37,929,897 | get a line until | in iostream | <p>Currently I'm using the code below to read some variable from a text file like this:</p>
<blockquote>
<p>12345|54321|TAN Ah Kow |M|12 Jalan 3/45 KL |Wilayah P|012-3456789|5000.00</p>
</blockquote>
<p>The code is</p>
<pre><code>getline(infile,id,'|');
getline(infile,pw,'|');
getline(infile,name,'|');
getline(infile,gender,'|');
getline(infile,address,'|');
getline(infile,state,'|');
getline(infile,phone,'|');
getline(infile,balance,'|');
</code></pre>
<p>is there any better way to do this?</p>
| <c++><file><iostream> | 2016-06-20 18:59:10 | LQ_CLOSE |
37,930,091 | Chnage state in JSON file | I have trouble in school to change a state in my json file,
i must do a game with HTML and javascript, i start with a "Guess who?" game, in my json i have players with attributs like name,password and state.
all my request only look the number of state and change it if he must.
how i can write a code that change only player.state like 1 to 3 ?
thanks
this is my json file :
`[
{"pseudo":"player1","password":"player","state":"1"},
{"pseudo":"player2","password":"player","state":"0"}
]
` | <javascript><json> | 2016-06-20 19:11:28 | LQ_EDIT |
37,930,181 | bash won't enter to else | <p>I have this code that expects string from the end user:</p>
<pre><code>#!/bin/bash
echo "You are about to deploy the site from STAGING to PRODUCTION, Are you sure? yes/no ";
read continue
if (( "$continue" == "yes" )) ; then
echo "Yes"
else
echo "No"
fi
</code></pre>
<p>The problem is that the else will never be.</p>
<p>Thanks</p>
| <bash><if-statement> | 2016-06-20 19:17:50 | LQ_CLOSE |
37,930,219 | Is Firebase's latency low enough to be used for realtime MMOG instead of socket? | <p>I wonder if Firebase's performance (latency, throughput) is good enough to be used real-time MMO games online.</p>
<p>Could someone with enough knowledge share their opinions on this?</p>
<p>Can Firebase be used instead of socket for real time games?</p>
| <websocket><socket.io><firebase><real-time><mmo> | 2016-06-20 19:20:02 | HQ |
37,930,610 | My script its udpating all fields when i just edit one | my problem its im trying to develop a backend where i need to update but my problem its , when I update one field my script update all fields and all data of my mysqli database.
My code for now its that :
<html>
<body>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "hotel_vaniet";
$strCustomerID = null;
if(isset($_GET["cod"]))
{
$cod = $_GET["cod"];
}
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "hotel_vaniet";
$conn = mysqli_connect($serverName,$userName,$userPassword,$dbName);
$sql = "SELECT * FROM quartos WHERE cod=$cod";
$query = mysqli_query($conn,$sql);
$result=mysqli_fetch_array($query,MYSQLI_ASSOC);
?>
<div id="main">
<form action="editar_quartos_final.php" name="frmAdd" method="post">
<br><h1>PΓ‘gina de EdiΓ§Γ£o</h1>
<br><hr/>
<div id="login2">
<table width="284" border="1">
<tr>
<th width="120">Tipo</th>
<td width="238"><input type="text" name="tipo" size="50" value="<?php echo $result["tipo"];?>"></td>
</tr>
<tr>
<th width="120">Capacidade</th>
<td><input type="text" name="capacidade" size="50" value="<?php echo $result["capacidade"];?>"></td>
</tr>
<tr>
<th width="120">PreΓ§o p/ Noite</th>
<td><input type="text" name="preco" size="50" value="<?php echo $result["preco"];?>"></td>
</tr>
<tr>
<th width="120">Reservado</th>
<td><input type="text" name="reservado" size="50" value="<?php echo $result["reservado"];?>"></td>
</tr>
</table>
<br><input id="submitbuttoneditar" type="submit" value=" Editar " name="submit"/><br />
</div>
</form>
<?php
mysqli_close($conn);
?>
</body>
</html>
This the first page ,this page send me to another where makes all changes. The second page :
<html>
<head>
<title>PΓ‘gina de EdiΓ§Γ£o do Cliente</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hotel_vaniet";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE quartos SET
tipo = '".$_POST["tipo"]."' ,
capacidade = '".$_POST["capacidade"]."' ,
preco = '".$_POST["preco"]."' ,
reservado = '".$_POST["reservado"]."'
WHERE cod=cod";
if ($conn->query($sql) === TRUE) {
echo "Dados actualizados com sucesso!";
header("Location: quartos.php");
} else {
echo "Erro na ediΓ§Γ£o dos dados! " . $conn->error;
header("Location: quartos.php");
}
$conn->close();
?>
</body>
</html>
Thanks for your help ! | <php><mysqli> | 2016-06-20 19:45:42 | LQ_EDIT |
37,931,527 | Showing an image or text for few seconds using javascript | <p>I am building a web app: front-end in Angular and back-end in Rails.
When users are done with filling out the application, they need to press "save" button to save the data. </p>
<p>Right now, when the user clicks the button, there is currently no feedback. When the button is clicked, I wanna show either text or image which says "Data Saved" for 2 seconds. </p>
<p>I would like to add code, but I have no idea how to even start with this. If anyone knows how to do this with Angular or Javascript, please let me know! </p>
| <javascript><angularjs> | 2016-06-20 20:46:27 | LQ_CLOSE |
37,931,577 | how to change the text of one button by clicking a second button in java | public class myJPanel6 extends JPanel implements ActionListene
{
myJButton b1, b2;
student st1;
String s1;
public myJPanel6()
{
setLayout(new GridLayout(1,1));
student st1 = new student("Michael", "Robinson", 20);
b1 = new myJButton(st1.getName());
b1.addActionListener(this);
add(b1);
b2 = new myJButton(st1.WhatIsUp());
b2.addActionListener(this);
add(b2);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1)
{
s1=st1.WhatIsUp();
b2.setText(s1);
}
}`
hello all!!
i want to change the text of one button when i click on the second button, but it's do nothing, i don't know what is the problem in it.
if anyone will help me as soon as possible then i would be really thankful and will appreciate every effort. | <java><swing><jbutton> | 2016-06-20 20:49:41 | LQ_EDIT |
37,931,827 | Items collection must be empty before using ItemsSource. | <p>I Have "Items collection must be empty before using ItemsSource." Error In My Code</p>
<p>I Test All Answer in StackOverFlow Links But They Did not Work!
My Xaml :</p>
<pre><code><Window x:Class="FirstWpfTestApplication.Main"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FirstWpfTestApplication"
xmlns:valConverter="clr-namespace:FirstWpfTestApplication.Model.ValueConverters"
mc:Ignorable="d"
Title="Main" Height="500" Width="800" WindowStartupLocation="CenterScreen">
<UserControl>
<UserControl.Resources>
<valConverter:GenderConverter x:Key="GenderConverter"/>
<valConverter:EnumList x:Key="EnumConverter"/>
<Style TargetType="TextBox">
<Setter Property="MinWidth" Value="100"/>
<Setter Property="Margin" Value="5"/>
</Style>
<Style TargetType="TextBlock">
<Setter Property="Margin" Value="5"/>
</Style>
<Style TargetType="RadioButton">
<Setter Property="Margin" Value="5"/>
</Style>
<Style TargetType="CheckBox">
<Setter Property="Margin" Value="5"/>
</Style>
<Style TargetType="ComboBox">
<Setter Property="MinWidth" Value="100"/>
</Style>
<Style TargetType="Button">
<Setter Property="Margin" Value="5"/>
<Setter Property="MinWidth" Value="60"/>
</Style>
</UserControl.Resources>
<Grid>
<DockPanel>
<!--<ListBox Name="lstPeople" DockPanel.Dock="Left">
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:" Margin="10 0"/>
<TextBlock Text="{Binding Name}" Margin="10 0"/>
</StackPanel>
</DataTemplate>
</ListBox>-->
<Border BorderThickness="2" BorderBrush="Black" CornerRadius="1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Column="0" Grid.Row="0" Margin="10">
<TextBlock>Name:</TextBlock>
<TextBox Text="{Binding Name}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Column="0" Grid.Row="1" Margin="10">
<TextBlock VerticalAlignment="Center">Gender:</TextBlock>
<WrapPanel Orientation="Vertical">
<RadioButton IsChecked="{Binding Gender,Converter={StaticResource GenderConverter},ConverterParameter=True}"
Name="rdMan">
Man
</RadioButton>
<RadioButton IsChecked="{Binding Gender,Converter={StaticResource GenderConverter},ConverterParameter=False}"
Name="rdWoman">
WoMan
</RadioButton>
</WrapPanel>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Column="0" Grid.Row="2" Margin="10">
<TextBlock>Field Of Work:</TextBlock>
<StackPanel Orientation="Horizontal">
<CheckBox Name="chActor" IsChecked="{Binding FieldOfWorks,Converter={StaticResource EnumConverter},ConverterParameter=Actor}">
Actor
</CheckBox>
<CheckBox Name="chDirector" IsChecked="{Binding FieldOfWorks,Converter={StaticResource EnumConverter},ConverterParameter=Director}">
Director
</CheckBox>
<CheckBox Name="chProducer" IsChecked="{Binding FieldOfWorks,Converter={StaticResource EnumConverter},ConverterParameter=Producer}">
Producer
</CheckBox>
</StackPanel>
</StackPanel>
<StackPanel Grid.Row="3" Orientation="Horizontal">
<TextBlock>Country:</TextBlock>
<ComboBox Name="cbCountries">
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox>
</StackPanel>
<StackPanel Margin="0 10" HorizontalAlignment="Left" Orientation="Horizontal" Grid.Row="4">
<Button>Save</Button>
</StackPanel>
</Grid>
</Border>
</DockPanel>
</Grid>
</UserControl>
</code></pre>
<p></p>
<p>And My C# Code:</p>
<pre><code> public partial class Main : Window
{
public List<People> PeopleContext;
public Main()
{
InitializeComponent();
this.DataContext = People.GetPeople();
cbCountries.ItemsSource = new Country().GetCountries();//In This Line Exception Will Throw
}
}
</code></pre>
<p>Please Help To Fix This Problem In WPF</p>
| <c#><wpf><itemsource> | 2016-06-20 21:06:52 | LQ_CLOSE |
37,932,243 | attr('selected', true); more than two times don't selected, the version of jQuery after 1.8 | attr('selected', true); more than two times don't selected, the version of jQuery after 1.8
[simple here - jsfiddle.net/fWLJ9/236/][1]
[1]: http://jsfiddle.net/fWLJ9/236/
<!-- begin snippet: js hide: false console: true -->
<!-- language: lang-js -->
$(document).on("click",".edit", function(){
$("#editor").find("select").prop('selectedIndex',0);
$("#editor").find("#whour option[value='"+this.id+"']").attr('selected', true);
});
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="editor">
<select id="whour" name="duration[hr]">
<option value="0">ββ</option>
<option value="1">1 h.</option><option value="2">2 h.</option><option value="3">3 h.</option><option value="4">4 h.</option><option value="5">5 h.</option><option value="6">6 h.</option><option value="7">7 h.</option><option value="8">8 h.</option><option value="9">9 h.</option><option value="10">10 h.</option>
</select>
</div>
<button id="2" class="edit">
2h
</button>
<button id="3" class="edit">
3h
</button>
<button id="4" class="edit">
4h
</button>
<button id="5" class="edit">
5h
</button>
<!-- end snippet -->
there is a decision? | <jquery> | 2016-06-20 21:40:33 | LQ_EDIT |
37,932,434 | How to change a property on an object without mutating it? | <pre><code>const a = {x: "Hi", y: "Test"}
const b = ???
// b = {x: "Bye", y: "Test"}
// a = {x: "Hi", y: "Test"}
</code></pre>
<p>How can I set x to "Bye" without mutating a?</p>
| <javascript> | 2016-06-20 21:54:59 | HQ |
37,932,442 | I have a regex for only numbers allowed. But need one for floating o's als | I have a regex for to check if an input field has only numbers in it.
if (paymentAmount.match(/[^0-9\.,]/g)) ... show error
I need to also check for if there are any 0's before the value also.
for example. 0001.23 should throw and error. but 1.23 should be ok.
Is there a way to add this to the current regex check.
| <regex> | 2016-06-20 21:55:33 | LQ_EDIT |
37,932,635 | Getting different results for getStackTrace()[2].getMethodName() | <p>For logging purposes, I created a method logTitle() that prints out the calling method name for our TestNG tests. Sample code is below.</p>
<pre><code>@Test
public void test1() throws Exception {
method1();
}
public static void method1() throws Exception {
Utils.logTitle(2);
}
</code></pre>
<p>...</p>
<pre><code>public static void logTitle(Integer level) throws Exception {
// Gets calling method name
String method = Thread.currentThread().getStackTrace()[2].getMethodName();
// This would get current method name
switch (level) {
case 1:
logger.info("=======================================================");
logger.info(method);
logger.info("=======================================================");
break;
case 2:
logger.info("------------------------------------");
logger.info(method);
logger.info("------------------------------------");
break;
case 3:
logger.info("---------------------");
logger.info(method);
logger.info("---------------------");
break;
case 4:
logger.info("--------- " + method + " ------------");
break;
default:
logger.info(method);
}
}
</code></pre>
<p>The problem is I am getting different results for logTitle() on two different machines.</p>
<p>Everyone's laptop returns correctly:</p>
<pre><code>2016-06-20 14:22:06 INFO - ------------------------------------
2016-06-20 14:22:06 INFO - method1
2016-06-20 14:22:06 INFO - ------------------------------------
</code></pre>
<p>Our dev unix box returns differently:</p>
<pre><code>2016-06-20 14:42:26 INFO - ------------------------------------
2016-06-20 14:42:26 INFO - logTitle
2016-06-20 14:42:26 INFO - ------------------------------------
</code></pre>
<p>This works correctly on everyone else's laptop, just not the dev unix box. I think the dev unix box is using IBM's version of Java, while everyone else is using Oracle's version of Java, but not sure if that is the culprit or not.</p>
<p>Any ideas?</p>
| <java><testng> | 2016-06-20 22:10:19 | HQ |
37,932,686 | I have a JQuery function that sets active based on hover, I want to automate this to avoid duplication of effort | <p>I have a fairly simple piece of JQuery that hides/unhides an element, based on which of the tabs are hovered over:</p>
<p>HTML:</p>
<pre><code> <div class="row col-sm-4">
<ul class="text-center">
<li><p class="chat-provider-tab tab">Chat Provider</p></li>
<li><p class="operations-tab tab">Operations</p></li>
<li><p class="proactive-chat-tab tab">Proactive Chat</p></li>
</ul>
</div>
<div class="row col-sm-8">
<p class="chat-provider helptip" style="display: none">Chat Provider</p>
<p class="operations helptip" style="display: none">Operations</p>
<p class="proactive-chat helptip" style="display: none">Proactive Chat</p>
</div>
</code></pre>
<p>JQuery:</p>
<pre><code>$(".chat-provider-tab").hover( function(){
$(".chat-provider").toggleClass("activetab")
});
$(".operations-tab").hover( function(){
$(".operations").toggleClass("activetab")
});
$(".proactive-chat-tab").hover( function(){
$(".proactive-chat").toggleClass("activetab")
});
</code></pre>
<p>I'd like to automate this where possible, and have tried several methods, however haven't been able to replicate the success I'm having with the above method.</p>
<p>Thank you,
Suxors</p>
| <jquery><html><css><automation> | 2016-06-20 22:14:39 | LQ_CLOSE |
37,932,808 | ORA-00920: invalid relational operator i obtain that please help me | INSERT INTO DIM_TEMPS (ID_DATE, DATE_DU_JOUR, ANNEE_CALENDAIRE, SEMESTRE, LIBELLE_SEMESTRE, TRIMESTRE, LIBELLE_TRIMESTRE, ANNEE_MOIS,MOIS, LIBELLE_MOIS, SEMAINE, JOUR, LIBELLE_JOUR, JOUR_FERIE, JOUR_OUVRE, QUANTIEME_JOUR) SELECT TO_NUMBER(TO_CHAR(DT_CAL, "YYYYMMDD")) AS ID_CALENDRIER, DT_CAL AS DATE_DU_JOUR, TO_NUMBER(TO_CHAR(DT_CAL, "YYYY")) AS ANNEE_CALENDAIRE, ROUND(TO_NUMBER(TO_CHAR(DT_CAL, "Q"))/2) AS SEMESTRE, CASE ROUND(TO_NUMBER(TO_CHAR(DT_CAL, "Q"))/2) WHEN 1 THEN "1er semestre" ELSE "2Γ¨me semestre" END AS LIBELLE_SEMESTRE, TO_NUMBER(TO_CHAR(DT_CAL, "Q")) AS TRIMESTRE, CASE TO_NUMBER(TO_CHAR(DT_CAL, "Q")) WHEN 1 THEN "1er trimestre" ELSE TO_NUMBER(TO_CHAR(DT_CAL, "Q")) || "Γ¨me trimestre" END AS LIBELLE_TRIMESTRE, TO_NUMBER(TO_NUMBER(TO_CHAR(DT_CAL, "YYYY")) || LPAD(TO_CHAR(DT_CAL, "MM"), 2, "0")) AS ANNEE_MOIS, TO_NUMBER(TO_CHAR(DT_CAL, "MM")) AS MOIS, TO_CHAR(DT_CAL, "Month") AS LIBELLE_MOIS, TO_NUMBER(TO_CHAR(DT_CAL, "IW")) AS SEMAINE, TO_NUMBER(TO_CHAR(DT_CAL, "DD")) AS JOUR, TO_CHAR(DT_CAL, "Day") AS LIBELLE_JOUR, CASE WHEN TO_CHAR(DT_CAL, "D") IN ("6", "7") THEN "Oui" ELSE "Non" END AS JOUR_FERIE, CASE WHEN TO_CHAR(DT_CAL, "D") IN ("6", "7") THEN "Non" ELSE "Oui" END AS JOUR_OUVRE, NUM_JOUR AS QUANTIEME_JOUR FROM ( SELECT to_date("19000101","YYYYMMDD") + (rownum - 1) AS DT_CAL, rownum AS NUM_JOUR FROM dual connect BY to_date("19000101","YYYYMMDD") + (rownum - 1) <= to_date('29991231','YYYYMMDD') ); COMMIT; | <sql><oracle> | 2016-06-20 22:26:00 | LQ_EDIT |
37,932,934 | How can I refresh a page when a database is updated(Laravel)? | <p>How can I refresh a page when a database is updated in Laravel?</p>
| <javascript><php><laravel> | 2016-06-20 22:38:14 | LQ_CLOSE |
37,933,922 | How to install older version of Typescript? | <p>I recently installed Typescript 1.8 and found too many breaking issues.
So for the time being I would like to install 1.7.
Where can I get a link to down this?</p>
| <typescript><typescript1.8> | 2016-06-21 00:40:06 | HQ |
37,933,930 | progblem with triggers in pl/sql |
SQL> get f:/sqlprog/trigger_3;
1 create or replace trigger t2 before insert or update on programmer for each
row
2 declare
3 cursor c1 is select prof1, prof2 from programmer;
4 beign
5 for r1 in c1 loop
6 if r1.pname=:new.pname then
7 if :new.prof1=: new.prof2 then
8 raise_application_error(-20091,'prof1 and prof2 should not be same');
9 end if;
10 end if;
11 end loop;
12* end;
SQL> /
Warning: Trigger created with compilation errors.
SQL> show errors
Errors for TRIGGER T2:
LINE/COL ERROR
-------- -----------------------------------------------------------------
4/1 PLS-00103: Encountered the symbol "FOR" when expecting one of the
following:
constant exception <an identifier>
<a double-quoted delimited-identifier> table long double ref
char time timestamp interval date binary national character
nchar
6/15 PLS-00103: Encountered the symbol ":" when expecting one of the
following:
( - + all case mod new null <an identifier>
<a double-quoted delimited-identifier> <a bind variable>
LINE/COL ERROR
-------- -----------------------------------------------------------------
continue any avg count current max min prior some sql stddev
sum variance execute forall merge time timestamp interval
date <a string literal with character set specification>
<a number> <a single-quoted SQL string> pipe
<an alternatively-quoted string literal with character set
specification>
<an alternative
SQL>
these are the errors which i encountered and the table regarding programmer is given below
prof1=proficieny 1
prof2= proficieny 2
SQL> desc programmer;
Name Null? Type
----------------------------------------- -------- ----------------------------
PNAME VARCHAR2(20)
DOB DATE
DOJ DATE
SEX CHAR(1)
PROF1 VARCHAR2(10)
PROF2 VARCHAR2(10)
SALARY NUMBER(5)
i dont have any idea why i am getting them pls help me out
thank youin advance.
| <plsql><oracle11g><triggers> | 2016-06-21 00:41:02 | LQ_EDIT |
37,934,972 | Serviceworker conflict with HTTP basic auth? | <p>I'm trying to protect a site during an early stage of development from casual prying eyes. Basic auth over HTTPS seemed like a reasonable solution but the presence of a serviceworker seems to prevent it from working in Chrome. This happens specifically if a serviceworker is already installed, but the browser does not have an active authorisation for the desired realm.</p>
<p>Chrome shows that the response was a 401 in the network timeline</p>
<p><a href="https://i.stack.imgur.com/WUole.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WUole.png" alt="401 in Network timeline"></a></p>
<p>And also shows that the browser tab is receiving the right response headers:</p>
<pre><code>HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="My realm"
Date: Tue, 21 Jun 2016 03:09:35 GMT
Connection: close
Cache-Control: no-cache
</code></pre>
<p>But it does not prompt for a login, it just shows the content body of the 401 response.</p>
<p>Is this a Chrome bug, or is it likely to be a problem with my ServiceWorker?</p>
| <javascript><google-chrome><basic-authentication><service-worker> | 2016-06-21 03:14:22 | HQ |
37,935,548 | iOS: Get displayed image size in pixels | <p>In my app, I'm displaying an image of a rectangle from the assets library. The image is 100x100 pixels. I'm only using the 1x slot for this asset.</p>
<p>I want to display this image at 300x300 pixels. Doing this using points is quite simple but I can't figure out how to get UIImageView to set the size in pixels.</p>
<p>Alternatively, if I can't set the size in pixels to display, I'd like to get the size in pixels that the image is being displayed.</p>
<p>I have tried using <code>.scale</code> on the UIImageView and UIImage instances, but it's always 1. Even though I have set constraints to 150 and 300.</p>
| <ios><swift><cocoa> | 2016-06-21 04:22:00 | HQ |
37,935,695 | How do I code so a picture can be cropped on android app? | <p>here is my java:</p>
<pre><code>public class MainPage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
TabLayout tabLayout;
ViewPageAdapter viewPageAdapter;
ViewPager viewPager;
ImageView pfp;
Bitmap bitmap_one;
private String UPLOAD_URL = "http://.php";
private int PICK_IMAGE_REQUEST = 1;
private String KEY_IMAGE = "image";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
initTypeface();
String username = getIntent().getStringExtra("Username");
TextView tv = (TextView)findViewById(R.id.usernameND);
tv.setText(username);
//id's
pfp = (ImageView) findViewById(R.id.imageView_one);
pfp.setOnClickListener(this);
//SearchIntent
Intent searchI = getIntent();
if (Intent.ACTION_SEARCH.equals(searchI.getAction())) {
String query = searchI.getStringExtra(SearchManager.QUERY);
Toast.makeText(MainPage.this, query, Toast.LENGTH_SHORT).show();
}
//Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
//Tabs
tabLayout = (TabLayout) findViewById(R.id.tablayout_two);
viewPager = (ViewPager) findViewById(R.id.viewPager_two);
viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPageAdapter.addFragments(new FeedFragment(), "Feed");
viewPageAdapter.addFragments(new MessagesFragment(), "Messages");
viewPageAdapter.addFragments(new NotificationsFragment(), "Notifications");
viewPager.setAdapter(viewPageAdapter);
tabLayout.setupWithViewPager(viewPager);
//FloatingActionButton
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
//NavigationDrawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.profile) {
Intent i = new Intent(this, Profile.class);
startActivity(i);
} else if (id == R.id.whatshot) {
Intent i = new Intent(this, WhatsHot.class);
startActivity(i);
} else if (id == R.id.trending) {
Intent i = new Intent(this, Trending.class);
startActivity(i);
} else if (id == R.id.radioplayer) {
Intent i = new Intent(this, Radio.class);
startActivity(i);
} else if (id == R.id.musicplayer) {
Intent i = new Intent(this, MusicPlayer.class);
startActivity(i);
} else if (id == R.id.settings) {
Intent i = new Intent(this, Settings.class);
startActivity(i);
} else if (id == R.id.info) {
Intent i = new Intent(this, Info.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.search_view).getActionView();
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
//ImageInfo
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap_one = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
pfp.setImageBitmap(bitmap_one);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Typeface
private void initTypeface() {
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Amble-Regular.ttf");
TextView text = (TextView) findViewById(R.id.toolbarTitle);
text.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Amble-Regular.ttf");
text = (TextView) findViewById(R.id.usernameND);
text.setTypeface(myTypeface);
}
@Override
public void onClick(View v) {
if (v == pfp) {
showFileChooser();
}
}
</code></pre>
<p>}</p>
<p>Here is my xml:</p>
<pre><code> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main_page"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#e9eaea"
app:itemIconTint="#2A363B"
app:itemTextColor="#2A363B"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main_page"
app:menu="@menu/main_page_drawer">
<ImageView
android:id="@+id/imageView_one"
android:layout_width="90dp"
android:scaleType="fitCenter"
android:padding="5dp"
android:background="#2A363B"
android:adjustViewBounds="true"
android:onClick="pfpClick"
android:layout_marginLeft="8dp"
android:layout_marginTop="20dp"
android:layout_height="90dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="108dp"
android:text=""
android:textColor="#FFf"
android:textSize="18sp"
android:id="@+id/usernameND"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_marginTop="126dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>What I want to know is, how can I code my app so onclick of my imageview (imageView_one) it opens up a window or an editor so I can crop a pic into a square so it fits and places it on the Imageview. that is what i am trying to figure out. I am new to android so thank you.</p>
| <java><android><onclick><crop> | 2016-06-21 04:37:59 | LQ_CLOSE |
37,935,959 | Android M FingerprintManager.isHardwareDetected() returns false on a Samsung Galaxy S5 | <p>I have just updated a Verizion Samsung Galaxy S5 (SM-G900V) to the G900VVRU2DPD1 version via the manual instructions listed at <a href="http://www.androidofficer.com/2016/06/g900vvru2dpd1-android-601-marshmallow.html">http://www.androidofficer.com/2016/06/g900vvru2dpd1-android-601-marshmallow.html</a> </p>
<p>When I run the code below, isHardwareDetected() returns 'false'. I would expect it to return 'true'.</p>
<p>The Googling I have done does not resulted in any information one way or the other as to the S5 fingerprint reader being supported under Marshmallow.</p>
<p>Does anyone have any information about the S5's fingerprint reader being supported?</p>
<pre><code> FingerprintManager manager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
if (manager != null) {
if (ActivityCompat.checkSelfPermission(this, permission.USE_FINGERPRINT) !=
PackageManager.PERMISSION_GRANTED) {
retVal.append(INDENT).append("Fingerprint permission was not granted")
.append(EOL);
} else {
retVal.append(INDENT).append("Fingerprint hardware detected: ")
.append(manager.isHardwareDetected()).append(EOL);
retVal.append(INDENT).append("Has Enrolled Fingerprint(s): ")
.append(manager.hasEnrolledFingerprints()).append(EOL);
}
} else {
retVal.append(INDENT).append("no FingerprintManager available").append(EOL);
}
</code></pre>
| <android> | 2016-06-21 05:04:08 | HQ |
37,936,138 | HTML Validation for phone numbers | <p>I am new to HTML,can any one please help me to validate a phone number only with '+' and numeric values and phone number shud not exceed 13 numbers,and to validate email with a '@' and a '.',I dont want to use javascript </p>
| <html> | 2016-06-21 05:19:04 | HQ |
37,936,197 | Jade include with parameter | <p>In an older version of Jade I was able to include partials and pass variables into them like this:
!=partial('partials/video', {title:video.title, artist:video.artist})
now the partial connotation does not exist any more. How do I achieve the same thing using the include connotations?</p>
| <pug><partial> | 2016-06-21 05:24:17 | HQ |
37,936,560 | How to Sign Out of Google After Being Authenticated | <p>So my app has the option to sign in with Google. Upon clicking the button that Google provides, a web view opens and has the user input their credentials. After allowing the app to access their information the app then signs the user in and changes the SignInViewController to the TabBarController (where they can now interact accordingly).</p>
<p>When the user presses a Signout button they are directed to the login screen as one would expect. But the odd thing is, if the user presses the google button again they are automatically signed in with no further authentication at all and no option to remove their account. Is their a way to clear the google account credentials as to protect the users from accidental theft?</p>
<p><strong>Sign in function:</strong></p>
<pre><code>func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if let error = error {
print(error.localizedDescription)
return
}
let authentication = user.authentication
let credential = FIRGoogleAuthProvider.credentialWithIDToken(authentication.idToken, accessToken: authentication.accessToken)
FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in
// ...
SignInViewController().signedIn(user)
}
// ...
}
</code></pre>
<p><strong>Sign out function:</strong></p>
<pre><code>func signOutOverride() {
do {
try! FIRAuth.auth()!.signOut()
CredentialState.sharedInstance.signedIn = false
// Set the view to the login screen after signing out
let storyboard = UIStoryboard(name: "SignIn", bundle: nil)
let loginVC = storyboard.instantiateViewControllerWithIdentifier("SignInVC") as! SignInViewController
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window?.rootViewController = loginVC
} catch let signOutError as NSError {
print ("Error signing out: \(signOutError)")
}
}
</code></pre>
| <ios><swift><authentication><firebase><viewcontroller> | 2016-06-21 05:55:39 | HQ |
37,936,751 | Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3 | <p><strong>Introduction</strong></p>
<p>I am working with the bootstrap framework.I am currently working on "Bootstrap Tabs"(hide/show).I am using bootstrap version 3 and jquery version 3.0.2 something.</p>
<p><strong>Problem</strong></p>
<p>My tabs are not working, unless i load jquery of version less than 1.6.But then ajax making problem with jquery less than 1.6. Chrome console give me this error.</p>
<blockquote>
<p>bootstrap.min.js:6 Uncaught Error: Bootstrap's JavaScript requires
jQuery version 1.9.1 or higher, but lower than version 3</p>
</blockquote>
<p>I tried different fallback techniques but couldn't implement correctly.</p>
<p>I am stuck here for 2 days, if someone have any idea or any reference, please do help.Thanks for your time.</p>
| <javascript><jquery><twitter-bootstrap-3> | 2016-06-21 06:10:53 | HQ |
37,937,262 | Passing props to Vue.js components instantiated by Vue-router | <p>Suppose I have a Vue.js component like this:</p>
<pre><code>var Bar = Vue.extend({
props: ['my-props'],
template: '<p>This is bar!</p>'
});
</code></pre>
<p>And I want to use it when some route in vue-router is matched like this:</p>
<pre><code>router.map({
'/bar': {
component: Bar
}
});
</code></pre>
<p>Normally in order to pass 'myProps' to the component I would do something like this:</p>
<pre><code>Vue.component('my-bar', Bar);
</code></pre>
<p>and in the html:</p>
<pre><code><my-bar my-props="hello!"></my-bar>
</code></pre>
<p>In this case, the router is drawing automatically the component in the router-view element when the route is matched.</p>
<p>My question is, in this case, how can I pass the the props to the component?</p>
| <vue.js><vue-router> | 2016-06-21 06:44:37 | HQ |
37,937,364 | How to encrypt the value in base64 encoded value in PHP | Here i am using file upload,here i did base64 encode image upto **$encodeimage = base64_encode(file_get_contents($filename));//here we got encodede image value** now i got answer,after that i want to encrypt the base64 encoded value,i am writing below code but i can't get encrypt value?
<!-- begin snippet: js hide: false console: true -->
<!-- language: lang-js -->
<?php
require_once 'Security.php';
define ("MAX_SIZE","1000");
$errors=0;
$image =$_FILES["file"]["name"];//i got filename here
$uploadedfile = $_FILES['file']['tmp_name'];
$filetype = $_FILES['file']['type'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$error_msg = ' Unknown Image extension ';
$errors=1;
}
else{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$error_msg = "You have exceeded the size limit";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=600;
/*$newheight=($height/$width)*$newwidth;*/
$newheight=600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $_FILES['file']['name'];
imagejpeg($tmp,$filename,100);
$encodeimage = base64_encode(file_get_contents($filename));//here we got encodede image value
$encrypt_image = "data:".$filetype."base64,".$encodeimage;
$security = new Security();
/*$string = $_POST['user_string'];*/
$publicKey = $security->genRandString(32);
$encryptedData = $security->encrypt($encrypt_image, $publicKey);
imagedestroy($src);
imagedestroy($tmp);
}
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$id_proof = array("filename" =>$filename,
"base64_encodeimage" =>$encrypt_image,
"encryptedData" => $encryptedData,//getting null value here
"error_msg" =>$error_msg
);
echo json_encode($id_proof);
?>
----------
**Security.php**
<?php
class Security {
// Private key
public static $salt = 'Lu70K$i3pu5xf7*I8tNmd@x2oODwwDRr4&xjuyTh';
// Encrypt a value using AES-256.
public static function encrypt($plain, $key, $hmacSalt = null) {
self::_checkKey($key, 'encrypt()');
if ($hmacSalt === null) {
$hmacSalt = self::$salt;
}
$key = substr(hash('sha256', $key . $hmacSalt), 0, 32); # Generate the encryption and hmac key
$algorithm = MCRYPT_RIJNDAEL_128; # encryption algorithm
$mode = MCRYPT_MODE_CBC; # encryption mode
$ivSize = mcrypt_get_iv_size($algorithm, $mode); # Returns the size of the IV belonging to a specific cipher/mode combination
$iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM); # Creates an initialization vector (IV) from a random source
$ciphertext = $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv); # Encrypts plaintext with given parameters
$hmac = hash_hmac('sha256', $ciphertext, $key); # Generate a keyed hash value using the HMAC method
return $hmac . $ciphertext;
}
// Check key
protected static function _checkKey($key, $method) {
if (strlen($key) < 32) {
echo "Invalid public key $key, key must be at least 256 bits (32 bytes) long."; die();
}
}
// Decrypt a value using AES-256.
public static function decrypt($cipher, $key, $hmacSalt = null) {
self::_checkKey($key, 'decrypt()');
if (empty($cipher)) {
echo 'The data to decrypt cannot be empty.'; die();
}
if ($hmacSalt === null) {
$hmacSalt = self::$salt;
}
$key = substr(hash('sha256', $key . $hmacSalt), 0, 32); # Generate the encryption and hmac key.
// Split out hmac for comparison
$macSize = 64;
$hmac = substr($cipher, 0, $macSize);
$cipher = substr($cipher, $macSize);
$compareHmac = hash_hmac('sha256', $cipher, $key);
if ($hmac !== $compareHmac) {
return false;
}
$algorithm = MCRYPT_RIJNDAEL_128; # encryption algorithm
$mode = MCRYPT_MODE_CBC; # encryption mode
$ivSize = mcrypt_get_iv_size($algorithm, $mode); # Returns the size of the IV belonging to a specific cipher/mode combination
$iv = substr($cipher, 0, $ivSize);
$cipher = substr($cipher, $ivSize);
$plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
return rtrim($plain, "\0");
}
//Get Random String - Usefull for public key
public function genRandString($length = 0) {
$charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$str = '';
$count = strlen($charset);
while ($length-- > 0) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
}
<!-- end snippet -->
| <php><encryption><base64> | 2016-06-21 06:51:16 | LQ_EDIT |
37,937,782 | Where a thread object is created in stack or in heap memory? | <p>Actually I was asked this question recently in an interview , I answered stack , am I right as I thought that threads would be executing methods, but could you please explain as why threads get created in stack or if not then why is it created in heap.</p>
<p>Thanks in advance</p>
| <java><java-threads> | 2016-06-21 07:13:40 | LQ_CLOSE |
37,938,757 | MSBuild plugin configuration in not available in Jenkins Configuration page | <p>I have installed MSBuild plugin for jenkins using plugin management. It was installed successfully and I am able to see the options for MSBuild in Job configuration page. </p>
<p>But, unfortunately I am not able to see MSBuild section in Jenkins configuration page. I need to provide the path for MSBuild.exe in that section.</p>
<p>Any idea why?</p>
<p>Thanks in advance!</p>
| <jenkins><msbuild> | 2016-06-21 08:02:49 | HQ |
37,939,131 | How to validate Jinja syntax without variable interpolation | <p>I have had no success in locating a good precommit hook I can use to validate that a Jinja2 formatted file is well-formed without attempting to substitute variables. The goal is something that will return a shell code of zero if the file is well-formed without regard to whether variable are available, 1 otherwise.</p>
| <validation><syntax><jinja2><pre-commit-hook> | 2016-06-21 08:22:35 | HQ |
37,941,284 | Database operations in IntentService results into application halt,become unresponsive and giving ANR | <p>I am using an IntentService in a alarm manager to trigger it after every 15 seconds.
I have to continuously send large amount data to server and receiving large amount of data in response in background.
I have to follow beneath process : </p>
<ol>
<li><p>I am reading data from Database through queries.</p></li>
<li><p>Then converting it in Json through POJO architecture.</p></li>
<li><p>Sending this JSON in request to server using Retrofit Library.</p></li>
<li><p>Receiving data in response.</p></li>
<li><p>Inserting this data to my database through certain queries if any updation in the database.</p></li>
</ol>
<p>Is there any alternate approach? As i am facing ANR.
If data is less, its working fine. But as data size is becoming large, UI halts and Application becomes unresponsive.</p>
| <android><retrofit><android-intentservice><jsonschema2pojo> | 2016-06-21 10:00:14 | HQ |
37,941,472 | How to know the text files developed in particular OS like UNIX or Windows using Java | I want to know the which Operating System(EX:UNIX or Windows or MAC) is used to Develop Text File and it's File Format(EX:UTF-8 or ANSI or DOS) by using Java.If I read one text file using Java Application, I want to know which Operating System is used to develop that File and it's File Format.How to do this using Java Application.Please give me some suggestions. | <java><file> | 2016-06-21 10:07:17 | LQ_EDIT |
37,941,503 | one column is Date and another column is Status but i need only after changed to status dates how to find? | I/P Date : Status: 6/20/2016 ABC, 6/21/2016 ABC, 6/22/2016 ABC, 6/23/2016 DEF 6/24/2016 ABC 6/25/2016 ABC, 6/26/2016 ABC, 6/27/2016 ABC, ; O/P Date :Status : 6/24/2016 ABC, 6/25/2016 ABC, 6/26/2016 ABC, 6/27/2016 ABC, above is my input and expected out put. what ever dates after changed status ABC continuously then showcase remaining changed before ABC is no need. | <sql-server> | 2016-06-21 10:08:21 | LQ_EDIT |
37,941,884 | How to Create Store Procedure? | I have following fields i need TO create table in stored procedure i want set table name dbo.UploadFilesProject and Following Fields
@ProjectId (int, Input, No default)
@FileName (varchar(75), Input, No default)
@FilePath (varchar(500), Input, No default)
@UploadedDate (date, Input, No default)
@IsActive (bit, Input, No default)
@UpdatedBy (varchar(75), Input, No default)
@ClientId (int, Input, No default)
I am New Stored Procedure please anyone Tell me how to create stored Procedure ? thanks in advance | <sql-server><database><stored-procedures> | 2016-06-21 10:26:11 | LQ_EDIT |
37,942,063 | Slow insert on PostgreSQL using JDBC | <p>I work on a system which downloads data from a cloud system to a local database (PostgreSQL, MySQL, ...). Now I'm having an issue with PostgreSQL performance because it takes a lot of time to insert the data.</p>
<p>A number of columns and the size of the data may vary. In a sample project, I have a table with approx. 170 columns. There is one unique index - but even after dropping the index the speed of the insert did not change.</p>
<p>I'm using JDBC driver to connect to the database and I'm inserting data in batches of 250 rows (using <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.html">NamedParameterJdbcTemplate</a>).</p>
<p>It took me approx. <strong>18 seconds to insert the data on Postgres</strong>. The same data set <strong>on MySQL took me just a second</strong>. That's a huge difference - where does it come from? Is Postgres JDBC driver that slow? Can it be configured somehow to make it faster? Am I missing something else? The difference between Postgres and MySQL is so huge. Any other ideas how to make it faster?</p>
<p>I made a sample project which is available on Github - <a href="https://github.com/varad/postgresql-vs-mysql">https://github.com/varad/postgresql-vs-mysql</a>. Everything happens in <a href="https://github.com/varad/postgresql-vs-mysql/blob/master/src/main/java/LetsGo.java">LetsGo class</a> in the "run" method.</p>
| <java><postgresql><jdbc> | 2016-06-21 10:34:23 | HQ |
37,942,283 | I dont want the users to log in two times from Wordpress and cakephp | <p>im developing a webapp using cakephp and i want to merge it with WordPress ,is there any solution that user will only login once (i dont want the users to log in two times.)</p>
| <php><jquery><ajax><wordpress> | 2016-06-21 10:44:45 | LQ_CLOSE |
37,942,296 | Not able to create a Firebase (Google)project after deleting the existing ones | <p><a href="https://i.stack.imgur.com/HE8w7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HE8w7.png" alt="Check below error, when trying to create a new project"></a>
I want to use Firebase Analytics. I had a existing project. But after deleting it I am not able to create a new project. Getting error saying maximum limit reached, when i dont even have single running project.</p>
| <firebase><firebase-analytics><google-analytics-firebase> | 2016-06-21 10:45:24 | HQ |
37,943,054 | Custom render blocks inside content area | I created content area for jquery tabs. The sturcture is like on image
[![enter image description here][1]][1]
[1]: http://i.stack.imgur.com/f4fHK.jpg
----------
If I try to render this structure through view of a block. I can't emulate it.
Since I have to put all li's inside one ul and all divs inside "tab-content" | <javascript><jquery><html><asp.net-mvc><episerver> | 2016-06-21 11:22:04 | LQ_EDIT |
37,943,092 | PHP to convert longitude and latitude | I have loop that gives me a longitude and latitude for each client , I am looking for a function where I can pass these variables into and it will out northing and easting value.
I have tried gPoint class but no joy.
Foreach ($clients as $client)
{
$client[lat]
$client[long]
Function convert($lat,$long)
}
| <php> | 2016-06-21 11:23:41 | LQ_EDIT |
37,943,233 | How to split string and map each character into dictionary | <p>Suppose i have a string like <code>'value=sahi'</code> and i want it like <code>{1:s,2:a,3:h,4:i}</code>
is there any function to do like this.</p>
| <python><dictionary> | 2016-06-21 11:30:02 | LQ_CLOSE |
37,943,616 | Firebase sign out not working in Swift | <p>I am using newest Firebase API (3.2.1) and I am using this code to check if user is signed in:</p>
<pre><code>override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if(self.navigationController != nil){
self.navigationController!.setNavigationBarHidden(true, animated: true)
}
if(FIRAuth.auth() != nil){
self.performSegueWithIdentifier("loginSuccessSegue", sender: self)
}
}
</code></pre>
<p>In other words if auth object is present I am switching to other controller. On that controller I have sign out button which is doing sign out like this:</p>
<pre><code>do{
try FIRAuth.auth()?.signOut()
self.performSegueWithIdentifier("logoutSegue", sender: self)
}catch{
print("Error while signing out!")
}
</code></pre>
<p>I do not get error on this operation but when I am switched to login controller, this auth object is present and I get switched back again to controller with data. I also tried checking the current user object in auth and it is present and valid.</p>
<p>Anyone knows how an I properly do sign out?</p>
| <swift><firebase><firebase-authentication> | 2016-06-21 11:49:47 | HQ |
37,943,730 | How can I dynamically resize a select2 input to be the same width as the selected option? | <p>I'm building a 'natural language' search form using a series of inline select inputs, using jQuery Select2 for styling. The widths of the Select2 inputs appear to be set to the width of the selected option on initialisation, which is great. I just can't work out how to get the width to update when the selected option is changed. Any ideas?</p>
<p>Many thanks!</p>
| <jquery-select2><select2> | 2016-06-21 11:54:32 | HQ |
37,943,804 | How to convert Number into Words in yii2 | <p>I need to convert amount into words for example total = 5600 into five thousand six hundred only in yii2</p>
| <php><yii2><yii2-advanced-app><yii2-basic-app> | 2016-06-21 11:57:56 | LQ_CLOSE |
37,943,833 | How to sync to specific folder using command line in Perforce | <p>Suppose I have mapped my depot to client workspace as <code>c:/perforce/project</code> but now </p>
<p>I want to sync all the files present in <code>c:/perforce/project/fold1/fold2</code> folder. </p>
<p>How can we do it, as the command p4 sync takes only file names and not folder.</p>
| <perforce><p4v> | 2016-06-21 11:59:27 | HQ |
37,944,111 | Python rolling log to a variable | <p>I have an application that makes use of multi-threading and is run in the background on a server. In order to monitor the application without having to log on to the server, I decided to include <a href="http://bottlepy.org" rel="noreferrer">Bottle</a> in order to respond to a few HTTP endpoints and report status, perform remote shutdown, etc.</p>
<p>I also wanted to add a way to consult the logfile. I could log using the <code>FileHandler</code> and send the destination file when the URL is requested (e.g. <code>/log</code>).</p>
<p>However, I was wondering if it'd be possible to implement something like a <code>RotatingFileHandler</code>, but instead of logging to a file, logging to a variable (e.g. <code>BytesIO</code>). This way, I could limit the log to the most recent information, while at the same time being able to return it to the browser as text instead of as a separate file download.</p>
<p>The <code>RotatingFileHandler</code> requires a filename, so it's not an option to pass it a <code>BytesIO</code> stream. Logging to a variable itself is perfectly doable (e.g. <a href="http://alanwsmith.com/capturing-python-log-output-in-a-variable" rel="noreferrer">Capturing Python Log Output In A Variable</a>), but I'm a bit stumped on how to do the <em>rolling</em> part.</p>
<p>Any thoughts, hints, suggestions would be greatly appreciated.</p>
| <python><python-3.x><logging> | 2016-06-21 12:13:36 | HQ |
37,944,296 | How to debug a Python package in PyCharm | <h1>Setup</h1>
<p>I have the following tree structure in my project:</p>
<pre><code>Cineaste/
βββ cineaste/
βΒ Β βββ __init__.py
βΒ Β βββ metadata_errors.py
βΒ Β βββ metadata.py
βΒ Β βββ tests/
βΒ Β βββ __init__.py
βββ docs/
βββ LICENSE
βββ README.md
βββ setup.py
</code></pre>
<p><code>metadata.py</code> imports <code>metadata_errors.py</code> with the expression:</p>
<pre><code>from .metadata_errors.py import *
</code></pre>
<p>Thus setting a relative path to the module in the same directory (notice the dot prefix).</p>
<p>I can run <code>metadata.py</code> in the PyCharm 2016 editor just fine with the following configuration:</p>
<p><a href="https://i.stack.imgur.com/xu6kS.png"><img src="https://i.stack.imgur.com/xu6kS.png" alt="enter image description here"></a></p>
<h1>Problem</h1>
<p>However, <strong>with this configuration I cannot debug <code>metadata.py</code></strong>. PyCharm returns the following error message (partial stack trace):</p>
<pre><code> from .metadata_errors import *
SystemError: Parent module '' not loaded, cannot perform relative import
</code></pre>
<p>PyCharm debugger is being called like so:</p>
<pre><code>/home/myself/.pyenv/versions/cineaste/bin/python /home/myself/bin/pycharm-2016.1.3/helpers/pydev/pydevd.py --multiproc --module --qt-support --client 127.0.0.1 --port 52790 --file cineaste.metadata
</code></pre>
<h1>Question</h1>
<p>How can I setup this project so that PyCharm is able to run and debug a file that makes relative imports? </p>
| <python-3.x><debugging><pycharm> | 2016-06-21 12:21:19 | HQ |
37,944,879 | Android Glide: Show a blurred image before loading actual image | <p>I am developing an Android app which displays full screen images to the user. Images are fetched from the server. I am using Glide to show the image. But I want to display a very small size blurred image before displaying the actual image. Once the image is cached, directly full sized image should be shown.</p>
<p>Image Displaying flows goes like this:
- If image is downloaded for the first time, first download a small scaled image, and then download full resolution image.
- If image has been downloaded before, directly show full scale image.</p>
<p>I cannot find any method in Glide library, which tell me if a file exist in cache or not.</p>
<p>Any idea, how this can be done. </p>
| <android><android-glide> | 2016-06-21 12:47:17 | HQ |
37,945,464 | Can't install Android Studio on Windows7 with an error | <p>I tried to install <code>Android Studio 2.1</code> on my netbook, 32 bit.
But, after I execute <code>android-studio-bundle-143.2915827-windows.exe</code>, an error occurred and I cannot install it.</p>
<pre><code>the following SDK components were not installed android support repository and android sdk tools
</code></pre>
<p>I searched it but I have no idea what to do, would you please help me?</p>
<p><a href="https://i.stack.imgur.com/LdA3w.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LdA3w.jpg" alt="enter image description here"></a></p>
<p>I click "retry", but this error occurs again, then I click "cancel" and uninstall and reinstalled it, this error happens again. </p>
| <android-studio> | 2016-06-21 13:12:40 | LQ_CLOSE |
37,945,767 | How to change application icon in Xamarin.Forms? | <p>I replaced all the images everywhere (by this I mean in drawable folders and all Windows Assets folders and iOS Resources folder), but it still shows me the default Xamarin icon for the app. I tried this code, too, but it doesn't seem to work either. Can someone tell me the solution?</p>
<pre><code>[assembly: Application(Icon = "@drawable/icon")]
</code></pre>
| <c#><cross-platform><xamarin.forms> | 2016-06-21 13:26:00 | HQ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.