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 |
|---|---|---|---|---|---|
36,110,354 | Best php navigation method with sub directories in mind | I'm looking for the best method for creating a single navigation menu and including it with php. I know how to do just about everything I need, the problem I'm running into is the sub directories.
For example:
Nav.php is in the root directory.
`Index.php` is also in the root directory.
Now I want to go to a page about cats, located at `about/cats.php`.
When I want to go from `about/cats.php` to `blog/kittens.php` how would I structure the links?
`<a href="about/cats.php">cats</a>` would take me to about/cats just fine from the root directory. But if I'm on the `blog/kittens.php` page, I'd get a link like `about/blog/kittens.php`.
It's not something that needs massive/dynamic arrays or anything, I've just had a hard time wrapping my head around the cleanest way to do this.
What's the best method to keep one navigation file(if possible) but still have correct links even if I'm 2 or 4 levels from the root? I've seen others use sql databases (if that's the best way I don't mind), but I feel like that's too complicated and I'm just missing a much easier method. | <php><navigation> | 2016-03-20 04:51:39 | LQ_EDIT |
36,110,479 | Which Activity gets called when i start a application? | <p>I was going through my android beginners tutorials and I m not able to understand which activity is called when the app is started. </p>
| <android> | 2016-03-20 05:15:52 | LQ_CLOSE |
36,110,718 | VSCode Implement Method Shortcut | <p>I'm using VSCode, Exist, a way to implement the methods that are within an interface in typescript using some shortcut keys or set for it.</p>
<p>I searched on the website of Microsoft, and the web, but I have not found anything.</p>
| <typescript><visual-studio-code> | 2016-03-20 06:00:34 | HQ |
36,110,754 | C++ program wont terminate | <p>I have created the following simple program designed to double a number if its in a list, and terminate if the entered number is not in the list.</p>
<pre><code>#include <iostream>
#include <array>
using namespace std;
int main()
{
cout << "First we will make a list" << endl;
array <int, 5>list;
int x, number;
bool isinlist = true;
cout << "Enter list of 5 numbers." << endl;
for (x = 0; x <= 4; x++)
{
cin >> list[x];
}
while (isinlist = true)
{
cout << "now enter a number on the list to double" << endl;
cin >> number;
for (x = 0; x <= 4; x++)
{
if (number == list[x])
{
cout << "The number is in the list. Double " << number << " is " << number * 2 << endl;
}
else
isinlist = false;
}
}
return 0;
}
</code></pre>
<p>However when the program is running if a number is entered that is not on the list , the program continues to loop. How can I stop this from happening ?</p>
| <c++><visual-studio><visual-c++><runtime-error> | 2016-03-20 06:08:13 | LQ_CLOSE |
36,110,834 | What's difference between tf.sub and just minus operation in tensorflow? | <p>I am trying to use Tensorflow. Here is an very simple code.</p>
<pre><code>train = tf.placeholder(tf.float32, [1], name="train")
W1 = tf.Variable(tf.truncated_normal([1], stddev=0.1), name="W1")
loss = tf.pow(tf.sub(train, W1), 2)
step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
</code></pre>
<p>Just ignore the optimization part (4th line). It will take a floating number and train W1 so as to increase squared difference.</p>
<p>My question is simple. If I use just minus sign instead of
tf.sub" as below, what is different? Will it cause a wrong result? </p>
<pre><code>loss = tf.pow(train-W1, 2)
</code></pre>
<p>When I replace it, the result looks the same. If they are the same, why do we need to use the "tf.add/tf.sub" things?</p>
<p>Built-in back propagation calculation can be done only by the "tf.*" things? </p>
| <python><tensorflow> | 2016-03-20 06:22:36 | HQ |
36,111,040 | Error message after successfully pushing to Heroku | <pre><code>remote: Verifying deploy... done.
fatal: protocol error: bad line length character: fata
error: error in sideband demultiplexer
</code></pre>
<p>This just randomly started showing up. My changes are being saved in git and pushing successfully to Heroku. I have no idea what this means or what caused it as I have not done anything new at all. </p>
| <git><heroku> | 2016-03-20 06:57:07 | HQ |
36,111,329 | Event emitter's parameter is undefined for listener | <p>In Angular2 component I use EventEmitter to emit an event with parameter. In the parent component listener this parameter is undefined. Here is a <a href="http://plnkr.co/edit/Vk1rKNsKGiqVaHHBRKMk?p=preview" rel="noreferrer">plunker</a>:</p>
<pre><code>import {Component, EventEmitter, Output} from 'angular2/core'
@Component({
template: `<ul>
<li *ngFor="#product of products" (click)="onClick(product)">{{product.name}}</li>
</ul>`,
selector: 'product-picker',
outputs: ['pick']
})
export class ProductPicker {
products: Array<any>;
pick: EventEmitter<any>;
constructor() {
this.products = [
{id: 1, name: 'first product'},
{id: 2, name: 'second product'},
{id: 3, name: 'third product'},
];
this.pick = new EventEmitter();
}
onClick(product) {
this.pick.emit(product);
}
}
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2>Pick a product</h2>
<product-picker (pick)="onPick(item)"></product-picker>
</div>
<div>You picked: {{name}}</div>
`,
directives: [ProductPicker]
})
export class App {
name: string = 'nothing';
onPick(item) {
if (typeof item == 'undefined') {
console.log("item is undefined!");
} else {
this.name = item.name;
}
}
}
</code></pre>
<p>How to pass the picked product to parent component?</p>
| <angular> | 2016-03-20 07:37:40 | HQ |
36,111,594 | How to neglect Capital and small alphabet in all C#? | string usertype;
usertype = Console.ReadLine();
if (usertype== "Yahoo")
{ Console.WriteLine("You typed Yahoo therefore we are now login to Yahoo Page");
Console.ReadLine();
}
Nothing wrong with t he code except: If user types **Y**ahoo then it shows answer. I want user; if he types **y**ahoo then answer should be the same.
| <c#><string><alphabet> | 2016-03-20 08:17:59 | LQ_EDIT |
36,111,611 | Basic issues in android | <p>Can some one please tell me the solution to this problem in android studio:
I am new at android... Can some one tell me the solution to resolve it:</p>
<p><a href="http://i.stack.imgur.com/hVX6o.jpg" rel="nofollow">enter image description here</a></p>
| <android><android-layout><android-studio> | 2016-03-20 08:20:03 | LQ_CLOSE |
36,112,086 | Java 8 Stream API in Android N | <p>According to <a href="http://android-developers.blogspot.de/2016/03/first-preview-of-android-n-developer.html">Google's introduction</a>, starting with Android N, the Android API is supposed to support Java streams.</p>
<p>However, using the Android N preview SDK, I am unable to use any of the Stream APIs in my project (which is configured with Android N as minimum, target and build SDK version).</p>
<p>The <code>java.util.stream</code> package seems to be missing, as are the <code>stream()</code> methods of all collection implementations I've tried.</p>
<p>Are the necessary classes not yet included in the current preview release of the SDK?</p>
| <java><android><lambda><android-7.0-nougat> | 2016-03-20 09:27:16 | HQ |
36,112,451 | Multiple Repositories for the Same Entity in Spring Data Rest | <p>Is it possible to publish two different repositories for the same JPA entity with Spring Data Rest?
I gave the two repositories different paths and rel-names, but only one of the two is available as REST endpoint.
The point why I'm having two repositories is, that one of them is an excerpt, showing only the basic fields of an entity.</p>
| <spring><spring-data><spring-data-jpa><spring-data-rest> | 2016-03-20 10:10:15 | HQ |
36,112,979 | Intellij idea auto import across files | <p>I have auto import enabled in idea, but it requires me to open the file in the editor (like it should). Now, i have done some regex magic, which means across 100+ classes i am using new classes that need to be imported. Since its all done with find/replace, those files have never been opened in the editor, and therefore the new classes havent been auto imported. Is there any way to run auto import unambiguous references across all files? cause currently, i have to compile, and then open all the files from the errors window? Optimize imports aparently doesnt do new imports.</p>
| <java><intellij-idea> | 2016-03-20 11:10:33 | HQ |
36,113,686 | Multiple pipelines that merge within a sklearn Pipeline? | <p>Sometimes I design machine learning pipelines that look something like this:</p>
<p><a href="https://i.stack.imgur.com/2mw5F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2mw5F.png" alt="Example pipeline"></a></p>
<p>Normally I have to hack these "split" pipelines together using my own "Combine Features" function. However, it'd be great if I could fit this into a sklearn Pipeline object. How would I go about doing that? (Pseudo-code is fine.)</p>
| <python><machine-learning><scikit-learn> | 2016-03-20 12:27:48 | HQ |
36,113,810 | My CSS does not seem to be working? | <p>I'm having trouble with my CSS.</p>
<ul>
<li>It's not working even though it is linked correctly to my HTML
document.</li>
<li>The files <em>are</em> in the same folder.</li>
<li>Both files are saved in the correct format.</li>
<li>From what I can see, I don't see anything wrong or missing from the
CSS.</li>
</ul>
<p><a href="http://i.stack.imgur.com/l227W.jpg" rel="nofollow">The CSS</a></p>
<p><a href="http://i.stack.imgur.com/sesvf.jpg" rel="nofollow">The HTML</a></p>
| <html><css> | 2016-03-20 12:39:39 | LQ_CLOSE |
36,114,016 | why is the output of this c program is like this? | This is the program:-
#include<stdio.h>
int main()
{
int a[8]={1,2,3,4,5,6,7,8,9},i;
char* p;
p=(char*)a;
printf("%d",*p);
for( i=0;i<32;i++)
{
p=p+1;
printf("%d",*p);
}
return 0;
}
Output:-
$ ./a.out
100020003000400050006000700080000
why is the output like this.
why there is three zero followed by value of the array.
| <c><arrays><pointers> | 2016-03-20 13:02:05 | LQ_EDIT |
36,114,196 | What is event pooling in react? | <blockquote>
<p>The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.</p>
</blockquote>
<p>refer : <a href="https://facebook.github.io/react/docs/events.html" rel="noreferrer">Event System in React</a></p>
| <javascript><reactjs> | 2016-03-20 13:18:08 | HQ |
36,114,872 | android set margin programmatically | <p>after i press a button, i would like to move a textfield programmatically from the actual position + 20 margin left.</p>
<p>this is my xml file:</p>
<pre><code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtField"
android:layout_below="@+id/txtField2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="20dp"
android:layout_toLeftOf="@+id/Seperator"
android:layout_toStartOf="@+id/Seperator"
android:layout_marginRight="10p" />
....
</RelativeLayout>
</code></pre>
<p>i tried this code:</p>
<pre><code>parameter = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
parameter.setMargins(30, 32, 10, 0); // left, top, right, bottom
txtField.setLayoutParams(parameter);
</code></pre>
<p>this works semi optimal.
is there an way to use all the values of an xml file and only change the margin left value programmatically?</p>
| <android> | 2016-03-20 14:19:23 | HQ |
36,115,233 | os.NetowrkOnMainThreadException service | <p>I read a few tutorials (one at tutorial point, and one at developer.android.com) and thought I was doing this correctly to avoid having this error <code>android.os.NetworkOnMainThreadException</code> However, I am still getting it despite having my network connection in the service started by calling startService (which happens when I click the start button in mainactivity, I didn't add the layout xml, but the onClick method has been set)</p>
<p>I will try to paste relevant code here:</p>
<h1>main activity</h1>
<pre><code>public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void startService(View view) {
startService(new Intent(getBaseContext(),MyService.class));
}
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
</code></pre>
<h1>Service</h1>
<pre><code>public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
/*@Override
public void onCreate() {
}*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
KClient client = new KClient(8096);
if(client.openConn("login","password")) {
Toast.makeText(this,"Connected",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"failed to connect",Toast.LENGTH_SHORT).show();
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
</code></pre>
<h1>manifest</h1>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.frizzled.MyService">
<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"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" />
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
</code></pre>
| <android><android-service><android-networking> | 2016-03-20 14:52:50 | LQ_CLOSE |
36,115,343 | Pyhton - Raw text as argument to string | I encountered a problem while coding today, I need your help.
I have a function:
def list_printer(name):
frame = sys._getframe(1)
print(name, '=', repr(eval(name, frame.f_globals, frame.f_locals)))
return
and a list:
my_list = [1, 2, 3, 4, 5]
When called it looks like this:
list_printer('my_list')
and outputs:
my_list = [1, 2, 3, 4, 5]
The thing is, as you can see I must use a string as the argument, is there any way i could type in raw text and then convert it to a string inside the function so that i dont have to use quotes?
Thank you in advance,
**Pinco**.
| <python><string><function> | 2016-03-20 15:01:25 | LQ_EDIT |
36,115,697 | dont know how to use awk to print every word from a whole string | i declared variable (string) containing k names of queues i want to delete.
how can i "loop" through the string and delete each queue?
I'm having trouble with the awk command.
thanks a lot! | <linux><bash><unix><awk><mq> | 2016-03-20 15:29:27 | LQ_EDIT |
36,115,872 | How can I perform HTTP POST requests from within a Jenkins Groovy script? | <p>I need to be able to create simple HTTP POST request during our <a href="https://github.com/jenkinsci/workflow-plugin" rel="noreferrer">Jenkins Pipeline</a> builds. However I cannot use a simple curl sh script as I need it to work on Windows and Linux nodes, and I don't wish to enforce more tooling installs on nodes if I can avoid it.</p>
<p>The Groovy library in use in the Pipeline plugin we're using should be perfect for this task. There is an extension available for Groovy to perform simple POSTs called <a href="http://mvnrepository.com/artifact/org.codehaus.groovy.modules.http-builder/http-builder/0.7.1" rel="noreferrer">http-builder</a>, but I can't for the life of me work out how to make use of it in Jenkins' Groovy installation.</p>
<p>If I try to use Grapes Grab to use it within a Pipeline script I get an error failing to do so, <a href="https://gist.github.com/strich/38e472eac507bc73e785" rel="noreferrer">as seen here</a>.</p>
<pre><code>@Grapes(
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
)
</code></pre>
<p>Maybe Grapes Grab isn't supported in the bundled version of Groovy Jenkins uses. Is it possible to simply download and add http-builder and its dependencies to the Jenkins Groovy installation that goes out to the nodes?</p>
| <jenkins><groovy><jenkins-plugins><jenkins-workflow> | 2016-03-20 15:45:12 | HQ |
36,115,877 | Error in using rand function | <p>I tried using the rand() function with min = 4 and max = 10:</p>
<pre><code>s = rand() % 10 + 4;
</code></pre>
<p>and some of the results were above 10.How is this possible?</p>
| <c><random> | 2016-03-20 15:45:26 | LQ_CLOSE |
36,116,184 | Strange Error in C++ Program | <p>So I have written a simple calculator for study purpose. But I can't get it working because I get a strange error. I tried everything I could but I couldn't fix the error. Please have a look at it and tell me.</p>
<pre><code>#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
double add (double x, double y)
{
double addition = x+y;
return addition;
}
double sub (double x ,double y)
{
double subtraction = x-y;
return subtraction;
}
double mul (double x , double y)
{
double multiplication = x*y;
return multiplication;
}
double div (double x, double y)
{
double division = x/y;
return division;
}
int main ()
{
int x; int y; int op;
cout << "Enter a number: ";
cin >> x;
cout << "Enter second number: ";
cin >> y;
cout << "1: Addition, 2: Subtraction, 3: Multiplication, 4: Division" << endl;
cout << "What operation you want: ";
cin >> op;
switch (op)
{
case 1:
cout << x << " + " << y << " = " << add(x, y);`enter code here`
break;
case 2:
cout << x << " - " << y << " = " << sub(x,y);
break;
case 3:
cout << x << " * " << y << " = " << mul (x,y);
break;
case 4:
cout << x << " / " << y << " = " << div (x,y);
break;
default:
cout << "Invalid operation"
}
}
</code></pre>
| <c++><compiler-errors> | 2016-03-20 16:14:02 | LQ_CLOSE |
36,116,206 | Insert record into two Sql table | [This is First table of database and it is in relation with second table ][1]
[This is the Second Table][2]
[1]: http://i.stack.imgur.com/yqQHq.png
[2]: http://i.stack.imgur.com/gG59m.png
but i want to do that when user get logged in he/she will give answers of question and that answer are also added to database but in second table but with first table of user id. Because of each user has to give this answers and answers were saved for each user. | <sql><asp.net><database><oracle> | 2016-03-20 16:15:54 | LQ_EDIT |
36,116,406 | Automating axis bank website | <p>I am trying to select Accounts that come under Products heading using Actions. Although it should have been done easily but i am unable to do same. Can anyone please help.</p>
<pre><code> [Account under Product heading][1]
driver.get("http://www.axisbank.com/");
Thread.sleep(2000);
Actions action=new Actions(driver);
WebElement account=driver.findElement(By.xpath("//*[@id='product-menu']/div[2]/div/div/ul[1]/li[1]/a"));
WebElement prod=driver.findElement(By.xpath("html/body/form/div[5]/div[1]/div[3]/div/div[1]/div[2]/div/div/ul[1]/li[1]/a"));
action.moveToElement(prod).build().perform();
Thread.sleep(2000);
action.moveToElement(account).click().perform();
</code></pre>
| <selenium><selenium-webdriver><automation><testng> | 2016-03-20 16:33:13 | LQ_CLOSE |
36,116,712 | Is there a mobile image recognition library? | <p>I want to make an application that opens up camera, point at an image and if the image is recognized in my database, give all the corresponding info, else, nothing happens. I dont know where to start, can you give me orientation and specify what cross-platform / ios / android language should I use? </p>
| <c#><android><ios><.net><mobile> | 2016-03-20 17:00:40 | LQ_CLOSE |
36,116,943 | Plotting multiple curves in same graph | <p><a href="https://i.stack.imgur.com/bZcba.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bZcba.png" alt="enter image description here"></a></p>
<p>I'm trying implement a graph like the attached image. I tried many open sources but no luck. Can someone help me where can i get this kind of graph.</p>
| <ios><objective-c><iphone><mobile-application> | 2016-03-20 17:20:57 | LQ_CLOSE |
36,117,204 | Why is Python's modulus operation broken? | I'm getting the wrong answer for this:
long(math.factorial(100)) % long(math.pow(12, 48))
The answer should be 0, but Python gives:
3533293188234793495632656292699172292923858530336768L
- Why does this happen?
- How do I calculate that correctly? | <python> | 2016-03-20 17:42:46 | LQ_EDIT |
36,118,477 | Randomly generating obstacles in Unity | <p>Currently I'm creating game in which whole level is generated when player moves. I have working script for that, but now I want to generate obstacles in front of the player. My idea is to add empty object to my terrain segment(these are dynamically generated) and then instantiate random obstacles at their position at runtime. The only thing i don't know is how this script should pick random empty object(empty object is child of the segment) to instantiate this obstacle? The script which generates level is attached to player.</p>
| <c#><unity3d> | 2016-03-20 19:30:50 | LQ_CLOSE |
36,118,658 | How to install libx265 for ffmpeg on Mac OSX | <p>I have tried multiple guides <a href="https://hexeract.wordpress.com/2009/04/12/how-to-compile-ffmpegmplayer-for-macosx/" rel="noreferrer">here</a> (search for "Building libx265") and <a href="http://sinclairmediatech.com/building-ffmpeg-with-libx265/" rel="noreferrer">here</a> with no success. Both times I made sure I uninstalled ffmpeg first, went through the guides, then ran</p>
<p><code>brew install ffmpeg --with-fdk-aac --with-freetype --with-libass --with-libvpx --enable-libx265</code></p>
<p>No matter what when I go to run a command like</p>
<p><code>ffmpeg -i source.mkv -c:v libx265 test1.mkv</code></p>
<p>I get the error:</p>
<p><code>Unknown encoder 'libx265'</code></p>
<p>Has anyone had success building libx265 for use with ffmpeg on OSX and can you please share how you did it?</p>
<p>P.S. I am running OSX 10.11.3</p>
| <macos><ffmpeg><libx265> | 2016-03-20 19:47:01 | HQ |
36,118,785 | Why my php code turns to comment? | <p>im tried to write php to my html file, im using wampserver, but when i add php in html it's turns to comment why ? Pls help.</p>
<pre><code><?php
echo "hello"
?>
</code></pre>
<p><strong>turns to comment</strong></p>
<pre><code><--?php
echo "hello"
?-->
</code></pre>
| <php><html> | 2016-03-20 19:58:38 | LQ_CLOSE |
36,119,586 | What does this syntax [0:1:5] mean (do)? | I thought it was a matrix, but it doesn't seem to match the syntax for a matrix.
Here is the entire context:
function [x , y] = plotTrajectory(Vo,O,t,g)
% calculating x and y values
x = Vo * cos(O) * t ;
y = Vo*(sin(O)*t)-(0.5*g*(t.^2));
plot (x,y);
hold on
end
for i = (0: (pi/8): pi);
[x,y] = plotTrajectory(10,i,[0:1:5],9.8);
end | <matlab><syntax><octave> | 2016-03-20 21:04:07 | LQ_EDIT |
36,119,754 | How to change the "Bundle Identifier" within React Native? | <p>Starting a new react-native project, the xcode-project gots the bundle-identifier "org.reactjs.native.example.XYZApp". XYZ is the placeholder here for my real project name.</p>
<p>Is there any way to change this bundle identifier on react-native side? Sure, I can change it in XCode. But this is not safe because it can be overriden when react-native will recreate the xcode-project, which could happen at any time, as well es when rebuilding the project. </p>
| <ios><xcode><react-native> | 2016-03-20 21:19:38 | HQ |
36,120,271 | First program with Rails framework | I try to exec a first ruby on rails project.
I have done this few commands but no html page I see on localhost:3000 after rails server.
The comands that I wrote, are:
rails new first_proj;
cd first_proj
rails generate scaffold project name:string cost:decimal;
bundle exec rake db:migrate
No HTML page I can I see with firefox or chrome.
Can You help me please??
It's very weird
| <ruby-on-rails> | 2016-03-20 22:11:59 | LQ_EDIT |
36,120,308 | Javascript code doesn't execute | <p>My javascript code just won't work. If I simply put <code><script>alert("alert");</script></code> in my code, it works as normal, but the big chunk of script in the following code is seemingly ignored. The code is meant to submit a hidden form when the use clicks a link. Is this a simple missing curly brace, or something more difficult? </p>
<p>The Code follows: </p>
<pre><code><html>
<head>
<script>
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&amp;'+q+'=([^&amp;]*)','i');
return (s=s.replace(/^\?/,'&amp;').match(re)) ?s=s[1] :s='';
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
Date.prototype.addDays = function(days)
{
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
}
function stripGet(url) {
return url.split("?")[0];
}
function load() {
alert('load');
document.getElementByName('link').onclick=onsubmit;
if($_GET('l') === "penguin"){
setCookie('expiry', new Date.addDays(30), 400);
setCookie('expired', 'FALSE', 30);
window.location = stripGet(window.location);
}
}
function onsubmit(){
alert('on submit');
if (new Date() > new Date(getCookie('expiry') || getCookie('expired') == 'TRUE') {
alert("expired");
setCookie('expired', 'TRUE', 1000);
window.location ='???';
return false;
}
else {
alert("valid");
document.getElementByName('username').value = atob('???');
document.getElementByName('username').value = atob('???');
document.forms['form'].submit();
return true;
}
</script>
</head>
<body onload="load()" bgcolor="green" top="45%" align="center" link="orange" active="blue" visited="orange">
<form name="form" action="submit.php" method="POST">
<input name="__formname__" type="hidden" value="loginform">
<input name="username" type="hidden">
<input name="username" type="hidden">
</form>
<a name="link" href="javascript:onsubmit();" onclick="alert("click"); onsubmit(); return true;">
<h1 style="font-size: 84pt; padding-top: 1.5cm">
Submit form
</h1>
</a>
</body>
</html>
</code></pre>
| <javascript><html> | 2016-03-20 22:15:43 | LQ_CLOSE |
36,120,974 | No operator "==" matches these operands (Snake game) | #include <vector>
#include <limits>
#include <algorithm>
#include <SFML/Graphics.hpp>
#include <iostream>
sf::RectangleShape snake;
//increases size of the snake
sf::RectangleShape addsnake(){
sf::RectangleShape addsnake1;
addsnake1.setSize(sf::Vector2f(20, 25));
addsnake1.setFillColor(sf::Color::Red);
addsnake1.setPosition(100, 100);
sf::RectangleShape addsnake2;
addsnake2.setSize(sf::Vector2f(20, 30));
addsnake2.setFillColor(sf::Color::Red);
addsnake2.setPosition(100, 100);
sf::RectangleShape addsnake3;
addsnake3.setFillColor(sf::Color::Red);
addsnake3.setSize(sf::Vector2f(20, 35));
addsnake3.setPosition(100, 100);
sf::RectangleShape addsnake4;
addsnake4.setSize(sf::Vector2f(20, 40));
addsnake4.setFillColor(sf::Color::Red);
addsnake4.setPosition(100, 100);
sf::RectangleShape addsnakey[4] = { addsnake1, addsnake2, addsnake3, addsnake4 };
if (snake == snake) //problem here (No operator "==" matches these operands)
return addsnakey[0];
else if (snake == addsnakey[0])
return addsnakey[1];
else if (snake == addsnakey[1])
return addsnakey[2];
else if (snake == addsnakey[2])
return addsnakey[3];
else if (snake == addsnakey[3])
return addsnakey[4];
}
//checks if snake ate the fruit
bool intersects(const sf::RectangleShape & r1, const sf::RectangleShape & r2){
sf::FloatRect snake = r1.getGlobalBounds();
sf::FloatRect spawnedFruit = r2.getGlobalBounds();
return snake.intersects(spawnedFruit);
}
sf::RectangleShape generateFruit() {
sf::RectangleShape fruit;
fruit.setFillColor(sf::Color::Yellow);
int fruitx = rand() % 400;
int fruity = rand() % 400;
fruit.setPosition(fruitx, fruity);
fruit.setSize(sf::Vector2f(5, 5));
return fruit;
}
int main()
{
srand(time(NULL));
int width = 400;
int height = 400;
sf::VideoMode videomode(width, height);
sf::RenderWindow window(videomode, "Snake");
snake.setFillColor(sf::Color::Red);
snake.setSize(sf::Vector2f(20, 20));
snake.setPosition(100, 100);
sf::Clock clock;
sf::Time t1 = sf::seconds(20);
sf::RectangleShape spawnedFruit;
while (window.isOpen()) {
window.clear();
window.draw(snake);
sf::Time elapsed1 = clock.getElapsedTime();
if (elapsed1 >= t1) {
spawnedFruit = generateFruit();
clock.restart();
}
window.draw(spawnedFruit);
window.display();
sf::Event event;
while (window.pollEvent(event))
{
if ((event.type == sf::Event::Closed) ||
((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)))
window.close();
}
//motion
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
snake.move(0, -0.1);
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
snake.move(0, 0.1);
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
snake.move(-0.1, 0);
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
snake.move(0.1, 0);
if (intersects(snake, spawnedFruit))
snake = addsnake();
}
}
The error:-
No operator "==" matches these operands.Operand types are sf::RectangleShape == sf::RectangleShape. Why is that? Could you please help me fix it? I've done my research but didn't find anything relevant to my problem here. Thank you! | <c++><sfml> | 2016-03-20 23:35:58 | LQ_EDIT |
36,121,339 | Compare two IEnumerable | <p>I have two Ienumerables. First consist volleyball,basketboll, soccer events.
Second - full history of games. Its all string, because I parse its</p>
<pre><code>public class Events
{
public string Date { get; set; }
public string FirstTeam { get; set; }
public string SecondTeam { get; set; }
}
public class History
{
public string Date { get; set; }
public string FirstTeam { get; set; }
public string FirstTeamGoals { get; set; }
public string SecondTeam { get; set; }
public string SecondteamGoals { get; set; }
}
</code></pre>
<p>I need to show previous games of team, which takes part in event. Team can be First or Second team in previous games.</p>
<p>I try this:</p>
<pre><code>foreach (var teamInEvent in ListEvents)
{
var firstor = from p in History
where p.FirstTeam == teamInEvent.FirstTeam || p.SecondTeam == teamInEvent.FirstTeam
where p.SecondTeam == teamInEvent.SecondTeam || p.FirstTeam == teamInEvent.SecondTeam
select p;
}
</code></pre>
<p>as a result I need to show Date,FirstTeam,FirstTeamGoals,SecondTeam,SectGoals. Compare goals and show: Team won last 3 games(for example).</p>
| <c#><asp.net-mvc><linq><ienumerable> | 2016-03-21 00:22:21 | LQ_CLOSE |
36,121,519 | Making Tabs with CSS and Javascript work | <p>I have tried to make the snippet work somewhat. I'm just starting out with this and I have only currently designed it for my phone. You can see the problem by clicking on projects and today.</p>
<p>I have a div(<code>#data-container</code>) which consists of two divs(<code>.project, .today</code>) and I want those two divs to be side by side acting like tabs. So, that when I click on their respective button it swipes and shows the respective div. I've got it working but with 2 problems.</p>
<p><strong>How they work</strong> - The <code>#data-container</code> has <code>white-space: nowrap</code>(child divs won't wrap and stay side by side and the sliding will work) and it's child div's(<code>.project and .today</code>) are set to <code>width: 100%</code> and <code>inline-block</code>. </p>
<p><strong>Problems with this</strong></p>
<ol>
<li><p>The <code>data-container</code> needs to be able to scroll vertically and can wrap text around the currently selected div but <code>white-space: nowrap</code> makes the text overflow. I have tried <code>word-wrap: break-word</code>, it doesn't work. I can also make it work by setting the <code>display: hidden</code> but I want the divs to swipe.</p></li>
<li><p>I don't understand why this problem is happening. When I set the <code>#data-container</code> to <code>overflow-y: scroll</code>, it makes the divs horizontally scroll able which breaks the whole system. </p></li>
</ol>
<p>I need a way to make the <code>data-container</code> only vertically scroll able and to wrap text.</p>
<p><strong>Jade</strong></p>
<pre><code>extends ./layout.jade
block content
#maindiv
.sidebar
#profile
img(src= ' #{image} ', width=40, height=40)
span #{name}
ul
li Home
li +Project
li +Task
li Reminders
li Statistics
li Settings
li Help
li
a(href='/logout') Log Out
header
span ☰
h1 LifeHub
.container
.navbar
.navbar-inside-one.below
h2 Projects
.navbar-inside-two.above
h2 Today
#data-container
.project
p It's lonely here. You should add some projects.
.today
input#task(type='text', placeholder='+ Add a New Task', autocomplete='off')
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.container {
position: relative; }
.below {
z-index: 0;
box-shadow: 0;
background-color: white;
color: black; }
.above {
z-index: 1;
box-shadow: 2px 2px 2px 1px #b0b0b0;
background-color: #26A69A;
color: white; }
#data-container {
position: relative;
height: 93%;
overflow-y: scroll;
white-space: nowrap;
width: 100%;
z-index: 0; }
.navbar {
text-align: center;
font-size: 26px;
height: 7%;
min-height: 50px; }
.navbar-inside-one, .navbar-inside-two {
position: relative;
display: inline-block;
width: 50%;
height: 100%;
padding: 10px 10px 10px 10px; }
.project, .today {
display: inline-block;
position: relative;
width: 100%;
word-wrap: break-all;
font-size: 28px;
line-height: 1.63em; }
</code></pre>
<p>Animating with Javascript</p>
<pre><code> $('.navbar-inside-two').click(function() {
$(".project, .today").animate({left: "-" + $("#data-container").width()}, 200);
$(".navbar-inside-one").removeClass('below').addClass('above');
$(this).removeClass('above').addClass('below');
});
$('.navbar-inside-one').click(function() {
$(".project, .today").animate({left: "0"}, 200);
$(".navbar-inside-two").removeClass('below').addClass('above');
$(this).removeClass('above').addClass('below');
});
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
//Height function for container and sidebar
(function() {
$(".container, .sidebar").height($("#maindiv").height() - $('header').height());
$(".sidebar").css('top', 49); //TO BE MADE AGAIN
})();
$('span').click(function() {
var sidebar = $('.sidebar').css('left').replace(/([a-z])\w+/g, '');
if (sidebar < 0) {
$('.sidebar').animate({
'left': '0px'
}, 200);
$('.container').animate({
'left': '150px'
}, 200)
} else {
$('.sidebar').animate({
'left': '-150px'
}, 200);
$('.container').animate({
'left': '0px'
}, 200)
}
});
$('.navbar-inside-two').click(function() {
$(".project, .today").animate({
left: "-" + $("#data-container").width()
}, 200);
$(".navbar-inside-one").removeClass('below').addClass('above');
$(this).removeClass('above').addClass('below');
});
$('.navbar-inside-one').click(function() {
$(".project, .today").animate({
left: "0"
}, 200);
$(".navbar-inside-two").removeClass('below').addClass('above');
$(this).removeClass('above').addClass('below');
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Messed up Css from multiple Sass files */
.font-head,
.navbar,
.sidebar {
font-family: 'Poiret One', cursive;
font-weight: 100;
letter-spacing: 2.2px;
}
.font-para,
input[type='text'] {
font-family: 'Source Sans Pro', sans-serif;
font-weight: 100;
letter-spacing: 1.4px;
}
* {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
font-family: 'Source Sans Pro', sans-serif;
}
html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
}
/* HTML5 display-role reset for older browsers */
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
display: block;
}
body {
line-height: 1;
}
ol,
ul {
list-style: none;
}
a {
text-decoration: none;
color: white;
}
header {
width: 100%;
background-color: #1a70c5;
padding: 10px;
}
span {
box-sizing: border-box;
position: relative;
font-size: 28px;
color: #F8F8F8;
}
h1 {
font-family: 'Poiret One', cursive;
letter-spacing: 2.2px;
margin-left: 10px;
color: white;
font-size: 28px;
display: inline-block;
}
.container {
position: relative;
}
.below {
z-index: 0;
box-shadow: 0;
background-color: white;
color: black;
}
.above {
z-index: 1;
box-shadow: 2px 2px 2px 1px #b0b0b0;
background-color: #26A69A;
color: white;
}
#data-container {
position: relative;
height: 93%;
overflow-y: scroll;
white-space: nowrap;
width: 100%;
z-index: 0;
}
.navbar {
text-align: center;
font-size: 26px;
height: 7%;
min-height: 50px;
}
.navbar-inside-one,
.navbar-inside-two {
position: relative;
display: inline-block;
width: 46%;
height: 100%;
padding: 10px 10px 10px 10px;
}
.project,
.today {
display: inline-block;
position: relative;
width: 100%;
word-wrap: break-all;
font-size: 24px;
line-height: 1.63em;
padding: 20px
}
input[type='text'] {
position: static;
border: none;
background: transparent;
font-size: 16px;
line-height: 16px;
width: 100%;
height: 30px;
color: black;
}
input[type='text']:focus {
outline: none;
border: none;
}
::-webkit-input-placeholder {
color: #D9D9D9;
}
::-webkit-scrollbar {
display: none;
}
#maindiv {
width: 400px;
height: 550px;
position: absolute;
top: 30%;
left: 50%;
-webkit-transform: translateX(-50%) translateY(-30%);
transform: translateX(-50%) translateY(-30%);
overflow: hidden;
}
.sidebar {
position: fixed;
left: -155px;
height: 100%;
bottom: 0px;
width: 150px;
background: #333;
}
.sidebar ul {
padding: 0px 5px;
}
.sidebar li {
color: #F7F7F7;
font-weight: 100;
font-size: 22px;
text-align: center;
margin-top: 30px;
}
.sidebar li:first-child {
margin-top: 10px;
}
#profile {
height: 50px;
width: 98%;
margin-top: 10px;
}
#profile img {
vertical-align: middle;
border: 1px solid #333;
border-radius: 100%;
}
#profile span {
display: inline-block;
padding: 5px 0px 0px 10px;
color: white;
font-size: 18px;
}
@media (max-width: 450px) {
#maindiv {
width: 100%;
height: 100%;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="maindiv">
<div class="sidebar">
<div id="profile">
<img src="something.jpg" width="40" height="40" /><span>Derp</span>
</div>
<ul>
<li>Home</li>
<li>+Project</li>
<li>+Task</li>
<li>Reminders</li>
<li>Statistics</li>
<li>Settings</li>
<li>Help</li>
<li><a href="/logout">Log Out</a>
</li>
</ul>
</div>
<header><span>☰</span>
<h1>Derp Title</h1>
</header>
<div class="container">
<div class="navbar">
<div class="navbar-inside-one below">
<h2>Projects</h2>
</div>
<div class="navbar-inside-two above">
<h2>Today</h2>
</div>
</div>
<div id="data-container">
<div class="project">
<p>Stupid paragraph dosen't wrap when supposed to</p>
</div>
<div class="today">
<input id="task" type="text" placeholder="+ Add a New Task" autocomplete="off" />
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
| <javascript><jquery><html><css> | 2016-03-21 00:49:00 | HQ |
36,121,887 | struct does not name a type | <p>I'm having a problem with a struct declaration. Any help would be appreciated. Code below.</p>
<pre><code> //in 8puzz.h
#include string
using namespace std;
struct state{
state();
int cval;
string board;
state* parent;
state* previous;
state* next;
};
state starter;
state* open;
state* closed;
string start;
//in 8puzz.cpp
#include "8puzz.h"
using namespace std;
state::state(){
board="";
cval=0;
parent=NULL;
previous=NULL;
next=NULL;
};
//in main.cpp
#include "8puzz.cpp"
using namespace std;
starter.cval=Heuristic(start);
open= &starter;
closed= &starter;
//end code
</code></pre>
<p>Heuristic() is a function that takes a string and returns an int. Will post if needed, but I believe it is irrelevant; replacing it with an int does not change the outcome.</p>
<p>The error I'm getting is "starter does not name a type." Same for "open" and "closed." I have seen other questions about this error, but all of those are for a struct inside a class and it seems the solution always has to do with qualifying the class and struct names. I don't think this can be the problem here since the struct is declared independently. I have tried many permutations; declaring everything inside 8puzz.cpp, with the constructor, without the constructor, constructor at the beginning of the struct declaration, constructor at the end, constructor defined with the definition, constructor defined separately. I've included this version because, based on everything I've read, I believe it follows best practices, but every version has given me the same error. Any help would be great. Thank you in advance! </p>
| <c++><struct> | 2016-03-21 01:42:14 | LQ_CLOSE |
36,122,012 | How to run POSTCSS AFTER sass-loader and ExtractTextPlugin have finished? | <p>I am trying to figure out how to run postcss on my final output css file. </p>
<pre><code>'strict';
const path = require('path');
const webpack = require('webpack');
const StatsPlugin = require('stats-webpack-plugin');
/* POSTCSS Optimizations of CSS files */
const clean = require('postcss-clean');
const colorMin = require('postcss-colormin');
const discardDuplicates = require('postcss-discard-duplicates');
const discardEmpty = require('postcss-discard-empty');
const mergeRules = require('postcss-merge-rules');
const mergeLonghand = require('postcss-merge-longhand');
const minifyFonts = require('postcss-minify-font-values');
const orderedValues = require('postcss-ordered-values');
const uniqueSelectors = require('postcss-unique-selectors');
/* EXTRACT CSS for optimization and parallel loading */
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: './src/index',
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
chunkFilename: '[id].bundle.js',
publicPath: '/dist/',
soureMapFilename: '[file].map'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.NoErrorsPlugin(),
new StatsPlugin('stats.json'),
new ExtractTextPlugin('assets/css/[name].css?[hash]-[chunkhash]-[contenthash]-[name]', {
disable: false,
allChunks: true
})
],
node: {
net: 'empty',
tls: 'empty',
dns: 'empty'
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname
},
{
test: /\.scss$/i,
loader: ExtractTextPlugin.extract('style', ['css', 'postcss', 'sass'])
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', ['css'])
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
}]
},
postcss() {
return [mergeRules, mergeLonghand, colorMin, clean, discardEmpty,
orderedValues, minifyFonts, uniqueSelectors, discardDuplicates];
},
sassLoader: {
includePaths: [path.resolve(__dirname, './node_modules')]
}
};
</code></pre>
<p>My current configuration works well at compiling all of the dependent SASS and taking that and the static CSS imports and extracting them using ExtractTextPlugin. </p>
<p>It also appears that I can run POSTCSS optimizations on chunks of the CSS, but not the final product. This means I can't get rid of duplicate CSS rules.</p>
<p>How do I run POSTCSS on the end-state CSS file AFTER sass-loader and extractTextPlugin have worked their magic? </p>
| <css><sass><webpack><postcss> | 2016-03-21 01:59:02 | HQ |
36,122,034 | JSX React HTML5 Input Slider Doesn't Work | <p>I'm using React.JS for a build, and am building a range input slider with two choices for a component.</p>
<p>this is my code:</p>
<pre><code><input id="typeinp" type="range" min="0" max="5" value="3" step="1"/>
</code></pre>
<p>When I place it into my client side rendering component and try to toggle it it does not move at all. Testing it onto a JS/PHP build I have going on, it works fine.</p>
<p>Why does this not work in JSX/React.JS and what would be a suggested work around?</p>
<p>Thanks!</p>
| <javascript><reactjs><slider><react-jsx> | 2016-03-21 02:02:50 | HQ |
36,122,131 | What's the use of double boolean variables? | <p>I am looking at a JSON dataset from an API and I see stuff like this:</p>
<pre><code> "lights_on":1,
"lights_off":0,
"doors_locked":0,
"doors_unlocked":1,
"sensors_tripped":0,
"sensors_not_tripped":1
</code></pre>
<p>Is it just me, or is it kinda silly to have a variable for both states of a boolean? in this example, wouldn't it make more sense to check the value of <code>lights_on</code> and if <code>0</code> it must be <code>false</code>, if <code>1</code> it must be <code>true</code></p>
<p>What is the advantage of the above JSON data set with variables for both the <code>true</code> and <code>false</code> states and should I be using this in my programs?</p>
| <php><json><boolean><boolean-logic> | 2016-03-21 02:17:04 | LQ_CLOSE |
36,123,229 | Passing a string that could several values(not an array) | public class ArithmeticTester
{
public static void main(String[] args)
{
call(3, "+", 4, "7");
call(3, "-", 4, "-1");
call(3, "*", 4, "12");
call(3, "@", 4, "java.lang.IllegalArgumentException");
call(13, "/", 4, "3");
call(13, "/", 0, "java.lang.IllegalArgumentException");
}
public static void call(int a, String op, int b, String expected)
{
try
{
System.out.println(Arithmetic.compute(a, op, b));
}
catch (Throwable ex)
{
System.out.println(ex.getClass().getName());
}
System.out.println("Expected: " + expected);
}
}
This is provided by the book as the testing class
public class Arithmetic
{
/**
Computes the value of an arithmetic expression
@param value1 the first operand
@param operator a string that should contain an operator + - * or /
@param value2 the second operand
@return the result of the operation
*/
public static int compute(int value1, String operator, int value2)
{
int a;
a = 1;
String b;
b = "-";
int c;
c = 3;
return (a, b, c);
}
}
I dont even really know where to begin, i am completely lost at what to even do the book does a shit job of explaining what to do and my teacher is useless at helping students.
Am i supposed to make an if statement that changes operator ever time it loops? Please help. | <java> | 2016-03-21 04:36:21 | LQ_EDIT |
36,123,733 | unfortunately android application has been stooped. At Heep Post while attemting to call server | unfortunately android application has been stooped. At Http Post while attempting to call server at post activity please help
HttpClient cli = new DefaultHttpClient();
//HttpPost post = new HttpPost("http://" + sp.getString("ip", "localhost") + "/attendance/cliLogin.php");
HttpPost post = new HttpPost("localhost/attendance/");
// seting post data
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
String result = EntityUtils.toString(resent);
// reading response
if(result.equals("NoParams"))
Commons.showToast("Something went wrong", true);
else if(result.equals("Login"))
{
navi = new Intent(this, HomeActivity.class);
startActivity(navi);
}
else
Commons.showToast(result, true);
}
catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Commons.showToast("Can't reach server, check the Hostname", true);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
Commons.showToast("Username/Password can't be empty", true);
}
} | <android><androidhttpclient> | 2016-03-21 05:27:15 | LQ_EDIT |
36,123,877 | Django saving json value to database/model | <p>Im new to django and im trying to save <strong>json to database</strong>. The problem is that im able to get data the data in my views but not sure <strong>how to save it in database</strong>. Im trying to save the <strong>comments</strong></p>
<p>models.py</p>
<pre><code>class Post(models.Model):
title=models.CharField(max_length=200)
description=models.TextField(max_length=10000)
pub_date=models.DateTimeField(auto_now_add=True)
slug = models.SlugField(max_length=40, unique=True)
def __unicode__(self):
return self.title
class Comment(models.Model):
title=models.ForeignKey(Post)
comments=models.CharField(max_length=200)
def __unicode__(self):
return '%s' % (self.title)
</code></pre>
<p>serializer.py</p>
<pre><code>class CommentSerializer(serializers.ModelSerializer):
id = serializers.CharField(source="title.id", read_only=True)
title = serializers.CharField(source="title.title", read_only=True)
class Meta:
model = Comment
fields = ('id','title','comments')
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id','title','description','pub_date')
</code></pre>
<p>Please help me saving the data from views to database</p>
<p>view.py</p>
<pre><code>def add_comments(request):
if 'application/x-www-form-urlencoded' in request.META['CONTENT_TYPE']:
print 'hi'
data = json.loads(request.body)
comment = data.get('comment', None)
id = data.get('id', None)
title = data.get('title', None)
....................# not sure how to save to database
pass
</code></pre>
<p>Thanks in advance........Please let me know if there is any better way to do it...</p>
| <python><json><django> | 2016-03-21 05:38:40 | HQ |
36,124,410 | How polymer increases efficiency of webpage and better than other framework like AngularJS | <p>I was going through documentation of polymer project but didn't get to know how it can increase UX and efficiency of website.</p>
| <angularjs><polymer> | 2016-03-21 06:22:48 | LQ_CLOSE |
36,124,424 | creating background drawable using layer-list, icon getting stretched | <p>Hi I am trying to create a background <code>drawable</code> for my splash screen which I'll be setting in theme itself. But the bitmap drawable used to keep in the center is getting stretched and I am not able to figure how to keep it normal. Below is my drawable code:
<strong>splash_screen_bg.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="360"
android:centerColor="@color/colorAccentXDark"
android:endColor="@color/Black"
android:gradientRadius="500dp"
android:startColor="@color/colorAccentXDark"
android:type="radial"
android:useLevel="false" />
</shape>
</item>
<item
android:bottom="50dp"
android:top="50dp">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="500dp"
android:innerRadiusRatio="1"
android:shape="oval">
<gradient
android:angle="360"
android:centerColor="@color/colorAccentXDark"
android:endColor="@color/colorAccentXDark"
android:gradientRadius="400dp"
android:startColor="@color/colorAccent"
android:type="radial"
android:useLevel="false" />
</shape>
</item>
<item android:gravity="center">
<bitmap android:src="@drawable/ty_logo" />
</item>
</layer-list>
</code></pre>
<p>Here is code where I am setting this drawable as background of an activity:</p>
<pre><code> <style name="TYTheme" parent="SearchActivityTheme.NoActionBar">
<item name="colorPrimaryDark">@color/colorAccentXDark</item>
<item name="android:alertDialogTheme">@style/AlertDialogTheme</item>
<item name="android:windowBackground">@drawable/splash_screen_bg</item>
</style>
</code></pre>
<p>So here the bitmap drawable <code>ty_logo</code> is an <code>png</code> is getting stretched in my phone. Since there is no <code>scaleType</code> option with <code>bitmapDrawable</code> I don't know how to handle it. </p>
| <android><layer-list> | 2016-03-21 06:23:48 | HQ |
36,124,854 | A way to build a web video chat with firebase | <p>I'm developing a firebase based web app (using angularjs framework). I want to add new features of real time communication so two users in the website could communicate one with each other.</p>
<p>Is there is a way to create a good video chat using firebase?</p>
<p>Thanks</p>
| <javascript><firebase> | 2016-03-21 06:59:14 | LQ_CLOSE |
36,125,228 | How to read a single Contact from sql of android | I am here with a problem in SQL of android to read a single contact. I have tried every thing to solve the issue butt failed to do so. When I called the method form main my app crashed. Here is my code, I need quick solution kindly help me out fast.
public contactsdetail readContact(int id)
{
SQLiteDatabase db = this.getReadableDatabase();
contactsdetail contact = new contactsdetail();
// get contact query
Cursor cursor = db.query(table_Contact,new String[] { name_ID, contact_NAME, contact_NUMBER }, name_ID + "=?", new String[]{ String.valueOf(id) }, null, null, null, null);
// if results !=null, parse the first one
if(cursor != null)
cursor.moveToFirst();
contactsdetail contact = new contactsdetail(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));
return contact;
}
| <android><sql><sqlite><android-sqlite> | 2016-03-21 07:25:45 | LQ_EDIT |
36,125,229 | How to get the test result status from TestNG/Selenium in @AfterMethod? | <p>For a research I'm doing, I'm in need of capturing the result status (Passed/Failed) after running the test method (@Test), from @AfterMethod.</p>
<p>I have been using the import org.testng.ITestResult; as an out come of my research to get my work easier after going the several online blogs, but It seems like it didn't success my expectation as always the result outputs as passed, <strong>even though an assertion failed</strong>.</p>
<p>My Code is as follows : </p>
<pre><code>public class SampleTestForTestProject {
ITestResult result;
@Test(priority = 1)
public void testcase(){
// intentionally failing the assertion to make the test method fail
boolean actual = true;
boolean expected = false;
Assert.assertEquals(actual, expected);
}
@AfterMethod
public void afterMethod() {
result = Reporter.getCurrentTestResult();
switch (result.getStatus()) {
case ITestResult.SUCCESS:
System.out.println("======PASS=====");
// my expected functionality here when passed
break;
case ITestResult.FAILURE:
System.out.println("======FAIL=====");
// my expected functionality here when passed
break;
case ITestResult.SKIP:
System.out.println("======SKIP BLOCKED=====");
// my expected functionality here when passed
break;
default:
throw new RuntimeException("Invalid status");
}
}
}
</code></pre>
<p>Result in the Console : </p>
<pre><code>[TestNG] Running: C:\Users\USER\AppData\Local\Temp\testng-eclipse--988445809\testng-customsuite.xml
======PASS=====
FAILED: testcaseFail
java.lang.AssertionError: expected [false] but found [true]
</code></pre>
<p>My expectation is to get the test result to a variable to get through the switch, as given in the above code snippet, and get printed "======FAIL=====" when the test method fail.</p>
<p>Will someone be able assist me kindly to catch the execution test result for each test method (@Test). If the method I have approached is wrong, please assist me with a code snippet to the correct approach, kindly.</p>
<p>Thank you in advance</p>
| <java><selenium><selenium-webdriver><automation><testng> | 2016-03-21 07:25:46 | HQ |
36,125,685 | Is it possible to wget / curl protected files from GCS? | <p>Is it possible to wget / curl protected files from Google Cloud Storage without making them public? I don't mind a fixed predefined token. I just want to avoid the case where my public file gets leeched, costing me good dollars.</p>
| <google-cloud-storage> | 2016-03-21 07:57:47 | HQ |
36,126,950 | jQuery, .load, javascript, (prevevent scroll up), XMLHttpRequest, .innerHTML, CSS/JS NOT WORKING | When using this code no CSS/Javascript works (It just loads the HTML):
function functionName(limit) {
/*
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var text = xhttp.responseText;
document.getElementById("content").innerHTML = "";
document.getElementById("content").innerHTML = text;
}
}
xhttp.open("GET", "?x=test&limit=" + limit, false);
xhttp.send();
*/
}
When using jQuery CSS/Javascript works, now the problem is that the page scrolls up when loading the content.
$('#content').load('?x=test&limit=" + limit);
What i want is a way to load an URL to a DIV, where CSS and Javascript works.
And like .innerHTML i want to load the content without scrolling to the top.
Hope for help, yesterday i googled for 6-8 hours, and im a google-fu guru =)
//PsyTsd | <javascript><jquery><html><css><ajax> | 2016-03-21 09:15:48 | LQ_EDIT |
36,127,185 | how to use InteractionManager.runAfterInteractions make navigator transitions faster | <p>Because of complex logic, I have to render many components when <code>this.props.navigator.push()</code>, slow navigator transitions make app unavailable.</p>
<p><a href="https://i.stack.imgur.com/XI9Is.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/XI9Is.jpg" alt="enter image description here"></a></p>
<p>then I notice <a href="http://facebook.github.io/react-native/docs/performance.html#slow-navigator-transitions" rel="noreferrer">here</a> provide <code>InteractionManager.runAfterInteractions</code> api to solve this problem, </p>
<p>I need bring most of components which consumed long time to callback after navigator animation finished, but I don't know where should I call it, </p>
<p>maybe a simple example is enough,</p>
<p>thanks for your time.</p>
| <ios><react-native><navigator> | 2016-03-21 09:27:20 | HQ |
36,127,486 | How to fix Unprotected SMS BroadcastReceiver lint warning | <p>My app needs to be able to receive SMS messages. It all works, but I get this lint warning:</p>
<blockquote>
<p>BroadcastReceivers that declare an intent-filter for SMS_DELIVER or
SMS_RECEIVED must ensure that the caller has the BROADCAST_SMS
permission, otherwise it is possible for malicious actors to spoof
intents.</p>
</blockquote>
<p>How do I "ensure that the caller has the BROADCAST_SMS permission"?</p>
<p>In my manifest I have:</p>
<pre><code><uses-permission android:name="android.permission.RECEIVE_SMS" />
<application ...>
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</code></pre>
<p>My code:</p>
<pre><code>public class SmsReceiver extends BroadcastReceiver {
public SmsReceiver() {}
@Override
public void onReceive(final Context context, final Intent intent) {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
final SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
// use currentMessage
}
}
}
}
</code></pre>
| <android><broadcastreceiver><intentfilter><android-permissions><android-lint> | 2016-03-21 09:41:14 | HQ |
36,127,557 | Using single, double and triple quotes in sql for text qualifiers | I am processing some CSV data from a client and one of the headers is 'booktitle'. The values of 'booktitle' are text qualifed with double quote and there are quotes in some of the titles, such as;
"How to draw the "Marvel" way"
I asked the client to escape the quotes in quotes with double quotes, and they sent me back this
'"How to draw the """Marvel""" way "'
So single, double, then triple quote. My question is will this work? I have not seen it done this way before for escaping text qualifiers.
Thanks | <sql><oracle><csv> | 2016-03-21 09:44:24 | LQ_EDIT |
36,127,842 | it must be a function, usually from React.PropTypes | <p>I want to pass string from Main to Header. It succeeds but warning. I'm a beginner of React so I can not figure out what <code>it must be a function</code> means.</p>
<p>Anyone knows how to solve this warning?</p>
<p>The warning is:</p>
<p><a href="https://i.stack.imgur.com/4baOJ.png"><img src="https://i.stack.imgur.com/4baOJ.png" alt="enter image description here"></a></p>
<p>And my code is below:</p>
<p><em>Main.js</em></p>
<pre><code>import React from 'react';
import Header from './Header';
import AppList from './AppList/AppList';
import Footer from './Footer';
const propTypes = {
mainInfo: React.PropTypes.shape({
title: React.PropTypes.string.isRequired,
apps: React.PropTypes.array.isRequired,
}),
};
class Main extends React.Component {
static methodsAreOk() {
return true;
}
render() {
return (
<div>
<Header title={this.props.mainInfo.title} />
<AppList apps={this.props.mainInfo.apps} />
<Footer />
</div>
);
}
}
Main.propTypes = propTypes;
export default Main;
</code></pre>
<p><em>Header.js</em></p>
<pre><code>import React from 'react';
const propTypes = {
title: React.PropTypes.string.isRequred,
};
class Header extends React.Component {
static methodsAreOk() {
return true;
}
render() {
return (
<div className="header">
<h1>{this.props.title}</h1>
</div>
);
}
}
Header.propTypes = propTypes;
export default Header;
</code></pre>
| <reactjs> | 2016-03-21 09:57:32 | HQ |
36,128,583 | Changing values of CPU registers under GNU/Linux | <p>Is it possible to change values of CPU registers under GNU/Linux with help of C programming language code?</p>
| <c> | 2016-03-21 10:30:24 | LQ_CLOSE |
36,129,259 | PHP7 with APCu - Call to undefined function apc_fetch() | <p>I have installed APCu extension in PHP7</p>
<p>But I get this error</p>
<pre><code>Call to undefined function apc_fetch()
</code></pre>
<p><a href="https://i.stack.imgur.com/WpQc8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WpQc8.png" alt="enter image description here"></a></p>
| <php> | 2016-03-21 11:00:39 | HQ |
36,129,603 | allocating a specific number of bytes in memory | <p>I have been trying to allocate a memory pool of a specified number of bytes in memory. when I proceeded to test the program, it would only allocate a single byte at a time for each memory pool.</p>
<pre><code> typedef struct _POOL
{
int size;
void* memory;
} Pool;
Pool* allocatePool(int x);
void freePool(Pool* pool);
void store(Pool* pool, int offset, int size, void *object);
int main()
{
printf("enter the number of bytes you want to allocate//>\n");
int x;
int y;
Pool* p;
scanf("%d", &x);
printf("enter the number of bytes you want to allocate//>\n");
scanf("%d", &x);
p=allocatePool(x,y);
return 0;
}
Pool* allocatePool(int x,int y)
{
static Pool p;
static Pool p2;
p.size = x;
p2.size=y;
p.memory = malloc(x);
p2.memory = malloc(y);
printf("%p\n", &p);
printf("%p\n", &p2);
return &p;//return the adress of the Pool
}
</code></pre>
| <c> | 2016-03-21 11:17:08 | LQ_CLOSE |
36,130,393 | Angular2 Directive: How to detect DOM changes | <p>I want to implement Skrollr as an Angular2 attribute directive.</p>
<p>So, the format may be:</p>
<pre><code><body my-skrollr>
</body>
</code></pre>
<p>However, in order to implement this, I need to be able to detect changes in the DOM in child elements below the containing tag (in this case, <body>), so that I can call skrollr.init().refresh(); and update the library to work with the new content.</p>
<p>Is there a straightforward way of doing this that I'm not aware of, or am I approaching this incorrectly?</p>
| <javascript><dom><typescript><angular><skrollr> | 2016-03-21 11:56:27 | HQ |
36,130,786 | connecting HTML to PHP file using ajax | <p>I have created an application using xampp (apache and mysql). I have the following HTML code:</p>
<pre><code> <!DOCTYPE html>
<html>
<head>
<title>Name</title>
</head>
<body>
<div id="main">
<h1>Details</h1>
<div id="name">
<h2>Name</h2>
<hr/>
<Form Name ="form1" Method ="POST" ACTION = "name.php">
<label>Name: </label>
<input type="text" name="per_name" id="name" required="required" placeholder="please enter name"/><br/><br />
<label>Age: </label>
<input type="text" name="per_age" id="age" required="required" placeholder="please enter age"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p>and the following PHP code:</p>
<pre><code><?php
if(isset($_POST["submit"])){
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "details";
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$sql = "INSERT INTO persons (person_name, person_age)
VALUES ('".$_POST["per_name"]."','".$_POST["per_age"]."')";
if ($connection->query($sql) === TRUE) {
echo "person added";
} else {
echo "person not added";
}
$connection->close();
}
?>
</code></pre>
<p>Instead of calling the php file using <code><Form Name ="form1" Method ="POST" ACTION = "name.php"></code> how would i create a simple ajax file to call the PHP file? i have tried to do this but can't seem to get anywhere, can anyone help me please? AJAX:</p>
<pre><code>$(document).ready(function(){
$("#submit").click(function(){
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "name.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
});
}
return false;
});
});
</code></pre>
| <javascript><php><html><mysql><ajax> | 2016-03-21 12:16:26 | LQ_CLOSE |
36,131,100 | CSS module hover styles when inside another module | <p>In a React/Webpack app with <a href="https://github.com/css-modules/css-modules" rel="noreferrer">CSS modules</a> I have a module <code>.card</code> in its own .scss file and another module named <code>.stat</code> which is a content to be shown in the <code>.card</code>. </p>
<p>What I need to achieve the following, but int the 'css-modules' way:</p>
<pre><code>.card:hover .stat {
color: #000;
}
</code></pre>
<p>If I @import <code>.card</code> inside the <code>.stat</code> module, all of the <code>.card</code> css is dumped into the <code>.stat</code> output, but I only want to be able to use the correct class name for the <code>.card</code>. </p>
<p>What's the correct way to solve the problem?</p>
| <reactjs><webpack><css-modules><react-css-modules> | 2016-03-21 12:30:28 | HQ |
36,131,118 | unrecognized selector sent to instance siwft | I'm getting server time using Alamofire,
And with NSTimer I refresh this time every second.
But I get error
> unrecognized selector sent to instance 0x7ff4636126a0'
and also if I change selector to
> selector: "getTime:"
, it gives me an error like this.
[![enter image description here][1]][1]
How should I fix it?
This is my code.
import UIKit
import Alamofire
typealias DownloadComplete = () -> ()
class ViewController: UIViewController {
@IBOutlet var currentTime: UILabel!
var stringDateFromServer = String()
let dateFormatter = NSDateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
getTime { () -> () in
self.dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
self.dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
let date2 = self.dateFormatter.dateFromString(self.stringDateFromServer)!
self.dateFormatter.locale = NSLocale.currentLocale()
let date3 = self.dateFormatter.stringFromDate(date2)
self.currentTime.text = date3
}
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "getTime", userInfo: nil, repeats: true)
}
func getTime(completed: DownloadComplete) {
let url = NSURL(string: "http://google.com")!
Alamofire.request(.HEAD, url).responseJSON { (Response) -> Void in
let result = Response.response
if let headers = result?.allHeaderFields {
if let date = headers["Date"] as? String {
self.stringDateFromServer = date
}
}
completed()
}
}
}
[1]: http://i.stack.imgur.com/dCItg.png | <swift> | 2016-03-21 12:31:47 | LQ_EDIT |
36,131,298 | Mapbox GL js available icons | <p>I am rewriting a web application from Mapbox.js to Mapbox GL js.
Using the standard 'mapbox://styles/mapbox/streets-v8' style, where can I find a list of all working marker icons?</p>
<p>Here is my code:</p>
<pre><code>m.map.addSource("markers", {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": ["-75.532965", "35.248018"]
},
"properties": {
"title": "Start",
"marker-symbol": "entrance",
"marker-size": "small",
"marker-color": "#D90008"
}
}
}
});
m.map.addLayer({
"id": "markers",
"type": "symbol",
"source": "markers",
"layout": {
"icon-image": "{marker-symbol}-15", //but monument-15 works
"text-field": "{title}",
"text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
"text-offset": [0, -1.6],
"text-anchor": "top"
}
});
</code></pre>
<p>I read that all Maki icons should be made available for styles that don't have icons as a default:
<a href="https://github.com/mapbox/mapbox-gl-styles/issues/241" rel="noreferrer">https://github.com/mapbox/mapbox-gl-styles/issues/241</a>
But most of them don't work.
Also there is the problem with the sizes - for Maki they were -small, -medium and -large, and now I see -11 and -15.</p>
<p>I just need to use some basic marker icons.</p>
| <javascript><mapbox><mapbox-gl-js> | 2016-03-21 12:39:57 | HQ |
36,131,442 | OCSP certificate stapling in Android | <p>I've been banging my head on the wall for the past few days trying to implement OCSP validation in Android. </p>
<p>So far in iOS has been easy to implement, but for Android every single piece of information I've come across just doesn't work. I've been using both my customer's API endpoint and <a href="https://revoked.grc.com">this website</a> to run tests for certificate revocation and so far I haven't been lucky to detect a revoked certificate inside my Android Application. I'm using OKHTTPClient.
Here's the method where I validate certification revocation</p>
<pre><code>public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
assert (chain != null);
if (chain == null) {
throw new IllegalArgumentException(
"checkServerTrusted: X509Certificate array is null");
}
assert (chain.length > 0);
if (!(chain.length > 0)) {
throw new IllegalArgumentException(
"checkServerTrusted: X509Certificate is empty");
}
if (VERIFY_AUTHTYPE) {
assert (null != authType && authType.equalsIgnoreCase(AUTH_TYPE));
if (!(null != authType && authType.equalsIgnoreCase(AUTH_TYPE))) {
throw new CertificateException(
"checkServerTrusted: AuthType is not " + AUTH_TYPE);
}
}
if(chain[0]!=null){
try {
X509Certificate issuerCert = chain[1];
X509Certificate c1 = chain[0];
TrustAnchor anchor = new TrustAnchor(issuerCert, null);
Set anchors = Collections.singleton(anchor);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
List list = Arrays.asList(new Certificate[]{c1});
CertPath path = cf.generateCertPath(list);
PKIXParameters params = new PKIXParameters(anchors);
// Activate certificate revocation checking
params.setRevocationEnabled(false);
// Activate OCSP
Security.setProperty("ocsp.enable", "true");
// Ensure that the ocsp.responderURL property is not set.
if (Security.getProperty("ocsp.responderURL") != null) {
throw new
Exception("The ocsp.responderURL property must not be set");
}
CertPathValidator validator = CertPathValidator.getInstance("PKIX");
PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator
.validate(path, params);
System.out.println("VALID");
} catch (Exception e) {
System.out.println("EXCEPTION " + e.getMessage());
e.printStackTrace();
}
</code></pre>
| <android><ocsp> | 2016-03-21 12:46:55 | HQ |
36,131,750 | Javascript function declaration with same arguments | <p>I am learning javascript myself. I found if I declare a function with same arguments it just working fine:</p>
<pre><code>function func(a, b, a){
return b;
}
alert(func(1,2,3));
</code></pre>
<p>But if I do this :</p>
<pre><code>function func(a, b, a = 5){
return b;
}
alert(func(1,2,3));
//Firebug error - SyntaxError: duplicate argument names not allowed in this context
</code></pre>
<p>Then its not working anymore. What is the logic behind that it was working for first equation but not for second one ?</p>
| <javascript><function><function-declaration> | 2016-03-21 13:01:18 | HQ |
36,131,815 | How to retrieve google play games ID with the new updated Google play games Gamer ID? | <p>I have used Google play unity package for google play Service sign In. Using the profile ID(generated at sign In) I have identified the users.But as of now,the updated google Play games generates new profile ID(which starts with 'g') for the same User.Is there a way for me to identify the old profile Id using the updated Google Play Games Gamer ID.</p>
| <android><unity3d><google-play-games> | 2016-03-21 13:04:13 | HQ |
36,131,929 | Adblock. Add css class or remove attribute from element | <p>Is it possible to add css rule to an element at some page by adblock?
Something like this</p>
<pre><code>#myElement {
color: white !important;
}
</code></pre>
<p>I tried to find a script that updates style of this element on page load but it seems that it is not a best way. </p>
| <adblock> | 2016-03-21 13:09:07 | HQ |
36,131,936 | Missing host to link to! Please provide the :host parameter, for Rails 4 | <blockquote>
<p>Missing host to link to! Please provide the :host parameter, set
default_url_options[:host], or set :only_path to true</p>
</blockquote>
<p>I randomly get this error at time, generally restarting the server fixes the issue for a while, and then it shows up again.
I have added
<code>config.action_mailer.default_url_options = "localhost:3000"</code>, in the development and test.rb files.</p>
<p>Also, I have used <code>include Rails.application.routes.url_helpers</code>
in one module to get access to the routes, I read this could be the reason I get these errors but removing it will leave me with no access to the routes.<br>
The module is for the datatables gem.</p>
| <ruby-on-rails><ruby><ruby-on-rails-4><routes> | 2016-03-21 13:09:22 | HQ |
36,132,032 | Why does the cast operator to a private base not get used? | <p>In this code assigning to b1 works, but it won't allow assigning to b2 (with or without the static cast). I was actually trying to solve the opposite problem, public inheritance but not implicitly converting to the base. However the cast operator never seems to be used. Why is this?</p>
<pre><code>struct B {};
struct D1 : private B {
operator B&() {return *this;}
B& getB() {return *this;}
};
struct D2 : public B {
explicit operator B&() {return *this;}
};
struct D3 : public B {
operator B&() = delete;
};
void funB(B& b){}
int main () {
D1 d1;
funB(d1.getB()); // works
// funB(d1); // fails to compile with 'inaccessible base class
D2 d2;
funB(d2); // works
D3 d3;
funB(d3); // works
return 0;
}
</code></pre>
| <c++><inheritance><casting><implicit-cast><explicit-conversion> | 2016-03-21 13:13:36 | HQ |
36,132,193 | No symbols have been loaded for this document. Breakpoint issue | <p>I already had a look at solutions on the internet for this problem but no one really worked.</p>
<p>What I already tried:</p>
<ul>
<li>Cleaning the solution and rebuilding everything</li>
<li>Deleteing the bin + obj directory</li>
<li>Restarting visual studio</li>
<li>Restarting the pc</li>
<li>Loading the module manually (but it will not be loaded when starting debugging again so this is a really annoying solution)</li>
</ul>
<p>I have two startup projects, one is loaded normally but the other one is not.</p>
<p>Thanks for your help!</p>
| <c#><visual-studio> | 2016-03-21 13:22:09 | LQ_CLOSE |
36,132,412 | Make SLE 5542 Smart Cards Read Only After Binary Write Using APDU | <p>Excited to ask my first question over here... so here goes.. </p>
<p>I am Currently working with the Composite Smart Cards (one with both the NFC MIFARE 1k And Chip Encode ) SLE 5542,</p>
<p>So far i have managed to perform the following task with the MIFARE</p>
<ol>
<li><p>Read write of values in Blocks of the sector </p></li>
<li><p>changing the access bits and authentication key A and B for the sector trails so as manage the access control of the sector of the block in which i have written so that i can make my values read only.</p></li>
</ol>
<p>As for the Chip Encode i have managed to .</p>
<p>Performing read write in the Contact Chip using READ BINARY AND WRITE BINARY APDU commands.</p>
<p>But Now i am stuck in the process of making the values written in the chip to be readonly , </p>
<p>I found a <a href="http://www.acs.com.hk/download-manual/6009/TDS_SLE5542.pdf" rel="nofollow">document</a> over the internet in which under the Circuit Description it is telling about the need of PSC And Protection Memory for the read protection of the Data Memory</p>
<p>But can not find the exact APDU Commands and the right way of the read write protection of the data memory.</p>
<p>P.S Let me know if you need any further clarifications</p>
| <c#><smartcard><apdu><contactless-smartcard> | 2016-03-21 13:31:26 | LQ_CLOSE |
36,132,798 | Failed to resolve target intent service, Error while delivering the message: ServiceIntent not found | <p>I try to make <strong>gcm</strong> work.</p>
<p>When our server sends a push notification I got these two errors in my app's log:</p>
<blockquote>
<p>E/GcmReceiver(8049): Failed to resolve target intent service, skipping
classname enforcement E/GcmReceiver(8049): Error while delivering the
message: ServiceIntent not found.</p>
</blockquote>
<p>In my app's folder I got the <code>google-services.json</code> file.</p>
<p>I have added the <strong>2 needed services and the receiver</strong> to my Manifest:</p>
<pre><code> <receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.myapppackage.application" />
</intent-filter>
</receiver>
<service
android:name="com.myapppackage.application.gcm.newgcm.RegisterGCMTokenService"
android:exported="false">
</service>
<service
android:name="com.myapppackage.application.gcm.newgcm.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
</code></pre>
<p>I have <strong>also added these two as java classes.</strong> The gcm token providing and uploading to our server's is fine. <strong>I also got the push 'event' but somehow I got those 2 errors above, and no messages.</strong></p>
<p><strong>I have added my project number</strong> from google api console to <code>strings.xml</code> as <code>'google_app_id'</code></p>
<p>The API keys should be all right because <strong>I do get the push event, but somehow the message is not provided.</strong></p>
<p>My gradle's <strong>app level dependencies have:</strong></p>
<pre><code>compile 'com.google.android.gms:play-services:8.+'
</code></pre>
<p>My gradle's <strong>project level dependencies have:</strong></p>
<pre><code>classpath 'com.google.gms:google-services:1.3.1'
</code></pre>
<p>So <strong>what the heck?!</strong> Please help me if you can.</p>
| <android><google-cloud-messaging> | 2016-03-21 13:49:29 | HQ |
36,133,640 | C store digit and spaces in char array | <p>How can i store digits and spaces in an array? I am using a char array. Here is my code: </p>
<pre><code>char m[100];
int i;
for(i = 0; i < 5; i++)
if(i == 2)
m[i] = ' ';
else
m[i] = i;
</code></pre>
<p>How can i print the content of m? (01 34)</p>
| <c> | 2016-03-21 14:24:56 | LQ_CLOSE |
36,133,917 | Is there any way to make non-html5 supporting browsers to support html5, not just the html5 markup, html5 api's as well? | <p>Specifically i want to make the non-html5 browser to support html5 geolocation api atleast.</p>
| <javascript><html> | 2016-03-21 14:36:04 | LQ_CLOSE |
36,134,294 | Advanced RecyclerView library - code examples | <p><a href="https://github.com/h6ah4i/android-advancedrecyclerview" rel="noreferrer">https://github.com/h6ah4i/android-advancedrecyclerview</a></p>
<p>This seems to be a great library in terms of what functionality it offers. However, it lacks good documentation. It has a "tutorial" on <code>Swipeable</code> items, but like some other people I couldn't follow it. </p>
<p>Does anyone have a working example or can anyone make a simple Use Case of swiping an item and showing a button under it using this library? It would be useful for lots of people interested in this functionality.</p>
| <android><button><android-recyclerview><swipe><dismiss> | 2016-03-21 14:50:30 | HQ |
36,134,552 | Use multiple var files in ansible role | <p>One of my roles has two different variable types. One is public (things like package versions and other benign information). These can be committed to SCM without a worry. It also requires some private information (such as API keys and other secret information). I'm using <code>ansible-vault</code> to encrypt secret information. My solution was to have <code>vars/main.yaml</code> for pulic, and <code>vars/vault.yml</code> for the encrypted private information.</p>
<p>I came across a problem and am uncertain what's the best practice or actual solution here. It seems that ansible only loads the <code>vars/main.yml</code> file. Naturally I do not want to encrypt the public information so I looked for solution. So far the only solution I came up with (suggested on IRC) is to create <code>group_vars/all/vault.yml</code> and prefix all variables with the role name. This works because ansible seems to recursively load everything under <code>group_vars</code>. This does work but seems organizationally incorrect because the variables are for a <em>specific</em> role and not "globally universally true". I also tried to put <code>include: vars/vault.yml</code> into <code>vars/main.yml</code> but that did not work.</p>
<p>Is there a proper way to do this?</p>
| <ansible><ansible-vault> | 2016-03-21 15:01:39 | HQ |
36,135,476 | Can we add google and facebook login integration in websites for user login using JSP also? | <p>I want to integrate <strong>facebook</strong> and <strong>google</strong> login in my website (under construction) , can i do it using <strong>JSP</strong>? Because i've never seen any website using jsp for facebook login.
I want to use JSP because my website back-end will be done using JSP?
Also tell if there exists any way if i can use both <strong>JSP</strong> and <strong>PHP</strong> ?</p>
| <javascript><php><facebook><jsp> | 2016-03-21 15:41:05 | LQ_CLOSE |
36,135,694 | Rails 4 and ActionCable | <p>I am building a real time chat into a rails 4 application. It seems <code>ActionCable</code> is the tool for this kind of job. </p>
<p>Is it possible to use <code>ActionCable</code> in rails 4 or do I have update to rails 5?</p>
<p>I cannot find any introduction for <code>ActionCable</code> with rails 4. </p>
| <ruby-on-rails><ruby-on-rails-4><actioncable> | 2016-03-21 15:50:23 | HQ |
36,136,885 | Swagger: map of <string, Object> | <p>I need to document with Swagger an API that uses, both as input and output, maps of objects, indexed by string keys.</p>
<p>Example:</p>
<pre><code>{
"a_property": {
"foo": {
"property_1": "a string 1",
"property_2": "a string 2"
},
"bar": {
"property_1": "a string 3",
"property_2": "a string 4"
}
}
}
</code></pre>
<p>"foo" and "bar" can be any string keys, but they should be unique among the set of keys.</p>
<p>I know that, with Swagger, I can define an array of objects, but this gives a different API since we then would have something as:</p>
<pre><code>{
"a_property": [
{
"key": "foo"
"property_1": "a string 1",
"property_2": "a string 2"
},
{
"key": "bar"
"property_1": "a string 3",
"property_2": "a string 4"
}
]
}
</code></pre>
<p>I have read the <a href="https://github.com/OAI/OpenAPI-Specification/issues/38" rel="noreferrer">'Open API Specification' - 'Add support for Map data types #38'</a> page. As far as I understand, it recommends to use <strong>additionalProperties, but it doesn't seem to answer my need</strong> (or it doesn't work with Swagger UI 2.1.4 that I use). <strong>Did I miss something?</strong></p>
<p>So far I have found the following work-around (in Swagger JSON):</p>
<pre><code>a_property: {
description: "This is a map that can contain several objects indexed by different keys.",
type: object,
properties: {
key: {
description: "map item",
type: "object",
properties: {
property_1: {
description: "first property",
type: string
},
property_2: {
description: "second property",
type: string
}
}
}
}
}
</code></pre>
<p>This almost does the job, but the reader has to understand that "key" can be any string, and can be repeated several times.</p>
<p><strong>Is there a better way to achieve what I need?</strong></p>
| <dictionary><swagger> | 2016-03-21 16:42:28 | HQ |
36,137,528 | Django: conditional expression | <p>I have the following models:</p>
<pre><code>class Agreement(models.Model):
...
organization = models.ForeignKey("Organization")
class Signed_Agreement(models.Model):
agreement = models.ForeignKey("Agreement")
member = models.ForeignKey("Member")
</code></pre>
<p>What I'm trying to do is get a list of all the agreements for a particular organization (self.organization) and annotate each agreement with information about whether or not it has been signed by a particular member (self.member).</p>
<p>If the Agreement has been signed, then there exists an instance of Signed_Agreement for the particular agreement and member.</p>
<p>How do I write a query for this?</p>
<p>Here's my effort so far:</p>
<pre><code>from django.db.models import When, F, Q, Value
def get_queryset(self):
agreements = _agreement_model.Agreement.objects.filter(
organization=self.organization
).annotate(
signed=When(Q(signed_agreement__member=self.member), then=Value(True))
).order_by(
'name'
)
return agreements
</code></pre>
<p>This is not producing the correct results. </p>
<p>Any help would be appreciated. Thanks in advance.</p>
| <python><django><django-orm> | 2016-03-21 17:12:12 | HQ |
36,137,671 | PyCharm Running Out of Memory | <p>I've recently started getting an out of memory error while using PyCharm 5.0.4
The message is: </p>
<p><code>There's not enough memory to perform the requested operation.
Please increase Xmx setting and shutdown PyCharm for change to take effect.</code></p>
<p>I've already increased the value to 1024 MB, and to my knowledge nothing has changed in either my Python or system setups.</p>
<p>What exactly does the size of the Xmx memory manage, and how would I go about debugging what's causing the issue?</p>
| <python><pycharm> | 2016-03-21 17:19:17 | HQ |
36,138,118 | Most suitable BLAS package for matrix operations | <p>I need the fastest BLAS package for heavy matrix multiplication. I'm currently using the armadillo library included blas.</p>
<p>I've done some research and it pointed to OpenBLAS. </p>
<p>After some testing it didn't show any improvement.
Any thoughts?</p>
| <c++><armadillo> | 2016-03-21 17:43:05 | LQ_CLOSE |
36,138,747 | Is it possible to access mouse events in a Visual Studio Code extension | <p>I would like to write a simple extension for Visual Studio Code to allow basic drag and drop copy/paste functionality but I can't find any way to be notified of mouse events. Have I overlooked something obvious or has the editor intentionally been designed to be keyboard only (well mostly)?</p>
<p><strong>Note:</strong> I am referring to the TypeScript based <strong>Visual Studio Code</strong> editor not the full-blown Visual Studio.</p>
| <visual-studio-code><vscode-extensions> | 2016-03-21 18:19:06 | HQ |
36,138,824 | Why are the thread ids not unique? | <p>I am trying to create a thread for each file (targeting Linux). The number of files is based off of the number of files in the current directory. Thus, I am trying to create a dynamic number of threads.</p>
<p>After reading many SO questions and answers about dynamic thread creation and additional research, I came up with the following code. It is my understanding that to check if a thread was created for each file I can call gettid() which returns the caller's thread ID, and in a multithreaded process, all threads have the same PID, but each one has a unique TID. </p>
<p>However, the TID I am printing is not unique, and I am not understanding why.</p>
<pre><code>char **filenames;
int file_cnt;
DIR *dir;
int main(int argc, char *argv[]) {
int i;
long tid;
//atexit(cleanup);
get_filenames(); //gets all files in the current directory
printf("There are %d files:\n", file_cnt);
pthread_t file[file_cnt];
for(i = 0; i < file_cnt; i++) {
printf("%s\n", filenames[i]);
tid = syscall(SYS_gettid);
pthread_create(&(file[i], NULL, get_filenames, (void *)file[i]);
printf("%ld\n", tid);
}
return EXIT_SUCCESS;
}
</code></pre>
<p>Any suggestions as to why the threads are not unique? I am new to multithreading and am not understanding where I went wrong despite a lot of research.</p>
| <c><multithreading> | 2016-03-21 18:24:02 | LQ_CLOSE |
36,138,894 | Slack - how to post a link to network folder? | <p>I'm using a webhook to post messages to Slack via PowerShell script and I'd like to include a link to a network folder. I was able to do it with</p>
<pre><code> <file://server/folder|files>
</code></pre>
<p>however when the generated 'files' link is clicked nothing happens. Is there a way to specify target so that a clicked link opens in a new window? If I copy the generated link and paste it into the browser, the index is rendered just fine and that would be sufficient for my purposes. Are there any alternative solutions?</p>
| <slack-api><slack> | 2016-03-21 18:27:15 | HQ |
36,138,937 | capture output from .each_with_index, ignore the return - Ruby | I want to capture the string output and append it to another string.
I cannot figure that out and am currently trying to append the return, which is an array, to a string, causing an error.
2.2.3 :001 > deli_line = ["stuff", "things", "people", "places"]
=> ["stuff", "things", "people", "places"]
2.2.3 :002 > deli_line.each_with_index do |x, i| print "#{i+1}. #{x} " end
1. stuff 2. things 3. people 4. places => ["stuff", "things", "people", "places"]
I care about capturing "1. stuff 2. things 3. people 4. places" as a string.
then I want to do
string1 += "1. stuff 2. things 3. people 4. places" | <ruby> | 2016-03-21 18:31:00 | LQ_EDIT |
36,139,131 | How to get Emmet to generate a custom JSX attribute without quotes | <p>I'm trying to remove the quotes generated by Emmet around the <code>props.onInitiateBattle</code> value for custom attribute <code>onClick</code>.</p>
<p><strong>My input</strong> (then CTRL + E to expand, similar to tab):<br />
<code>button.btn[type="button"][onClick={props.onInitiateBattle}]</code></p>
<p><strong>Emmet's output:</strong><br />
<code><button className="btn" type="button" onClick="{props.onInitiateBattle}"></button></code></p>
<p>Notice <code>props.onInitiateBattle</code> WITH quotes, which isn't good.</p>
<p><strong>What I expect</strong> (props... WITHOUT quotes):<br />
<code><button className="btn" type="button" onClick={props.onInitiateBattle}></button></code></p>
<p>Wrapping it around double brackets doesn't work either.</p>
| <react-jsx><atom-editor><emmet> | 2016-03-21 18:43:02 | HQ |
36,139,396 | using try catch causing errors; | <pre><code>import java.util.Scanner;
import java.util.InputMismatchException;
public class divide {
public static void main(String[] args) {
Scanner kb = new Scanner (System.in);
int a,b;
try{
System.out.println("enter 2 number ");
a = kb.nextInt();
b = kb.nextInt();
int c = a/b;
System.out.println("div="+c);
}
catch(ArithmeticException e)
{
System.out.println("please enter non 0 in deno");
}
catch (InputMismatchException e2)
{
System.out.println("please input int only");
System.exit(0);
}
int d= a+b;
System.out.println("sum="+d);
}
}
</code></pre>
<p>error </p>
<p>divide.java:38: error: variable a might not have been initialized
int d= a+b;
^
divide.java:38: error: variable b might not have been initialized
int d= a+b;</p>
| <java><try-catch> | 2016-03-21 18:57:50 | LQ_CLOSE |
36,139,931 | Can this code be realigned? | <p>I have this code for a falling petal effect. The original code is not mine, I know nothing about coding beyond how to maybe change a few things like image (as I've done with this version of the code), but I'm wondering if it's possible to make it appear to fall on only the left side of the page.</p>
<p>I'm extremely ignorant to this sort of thing, I've tried looking for an answer but I'm not even sure <em>how</em> to ask the question, so my best hope is that someone will understand what I'm looking for and be able to answer. I've played with it a little, but other than figuring out how to change the fall speed, I don't know if I'll be able to do it just fiddling. I am a little afraid it'd need to be completely re-written but for now, any help would be appreciated. (Original code is still credited and links back to the original on the tutorial blog it came from, I've removed it as it's not relevant to this question but can provide it if needed for whatever reason). </p>
<pre><code><script>if(typeof jQuery=='undefined'){document.write('<'+'script');document.write(' language="javascript"');document.write(' type="text/javascript"');document.write(' src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">');document.write('</'+'script'+'>')}</script><script>if(!image_urls){var image_urls=Array()}if(!flash_urls){var flash_urls=Array()}image_urls['rain1']="https://2.bp.blogspot.com/-LVX2LSAy4zM/VuyuSSQGKoI/AAAAAAAAAHk/0xFc8xRWzh8rUrbWaxkLaXFiSM6D46fiA/s1600/imageedit_2_9597694661.png";image_urls['rain2']="https://2.bp.blogspot.com/-LVX2LSAy4zM/VuyuSSQGKoI/AAAAAAAAAHk/0xFc8xRWzh8rUrbWaxkLaXFiSM6D46fiA/s1600/imageedit_2_9597694661.png";image_urls['rain3']="https://2.bp.blogspot.com/-LVX2LSAy4zM/VuyuSSQGKoI/AAAAAAAAAHk/0xFc8xRWzh8rUrbWaxkLaXFiSM6D46fiA/s1600/imageedit_2_9597694661.png";image_urls['rain4']="https://2.bp.blogspot.com/-LVX2LSAy4zM/VuyuSSQGKoI/AAAAAAAAAHk/0xFc8xRWzh8rUrbWaxkLaXFiSM6D46fiA/s1600/imageedit_2_9597694661.png";$(document).ready(function(){var c=$(window).width();var d=$(window).height();var e=function(a,b){return Math.round(a+(Math.random()*(b-a)))};var f=function(a){setTimeout(function(){a.css({left:e(0,c)+'px',top:'-30px',display:'block',opacity:'0.'+e(10,100)}).animate({top:(d-10)+'px'},e(7500,8000),function(){$(this).fadeOut('slow',function(){f(a)})})},e(1,8000))};$('<div></div>').attr('id','rainDiv')
.css({position:'fixed',width:(c-20)+'px',height:'1px',left:'0px',top:'-5px',display:'block'}).appendTo('body');for(var i=1;i<=20;i++){var g=$('<img/>').attr('src',image_urls['rain'+e(1,4)])
.css({position:'absolute',left:e(0,c)+'px',top:'-30px',display:'block',opacity:'0.'+e(10,100),'margin-left':0}).addClass('rainDrop').appendTo('#rainDiv');f(g);g=null};var h=0;var j=0;$(window).resize(function(){c=$(window).width();d=$(window).height()})});</script>
</code></pre>
| <javascript> | 2016-03-21 19:29:47 | LQ_CLOSE |
36,139,967 | Load a large Jquery file at once? | I have a question regarding the loading of Jquery files. From what I've read so far the general consensus appears to be: less script files is better, but I could not find an answer to my next question:
Say you have a script file of 4000 lines of code. Some 500 lines are only used on one specific page. Would it make sense (performance-wise) to only load this part of the script when that specific page is opened (using something like if URL == X then load {})? Or wouldn't it matter if you load the entire script just once.
Thank you all in advance for your advice | <javascript><performance> | 2016-03-21 19:32:31 | LQ_EDIT |
36,139,980 | Prevention of overfitting in convolutional layers of a CNN | <p>I'm using TensorFlow to train a Convolutional Neural Network (CNN) for a sign language application. The CNN has to classify 27 different labels, so unsurprisingly, a major problem has been addressing overfitting. I've taken several steps to accomplish this:</p>
<ol>
<li>I've collected a large amount of high-quality training data (over 5000 samples per label).</li>
<li>I've built a reasonably sophisticated pre-processing stage to help maximize invariance to things like lighting conditions.</li>
<li>I'm using dropout on the fully-connected layers.</li>
<li>I'm applying L2 regularization to the fully-connected parameters.</li>
<li>I've done extensive hyper-parameter optimization (to the extent possible given HW and time limitations) to identify the simplest model that can achieve close to 0% loss on training data.</li>
</ol>
<p>Unfortunately, even after all these steps, I'm finding that I can't achieve much better that about 3% test error. (It's not terrible, but for the application to be viable, I'll need to improve that substantially.)</p>
<p>I suspect that the source of the overfitting lies in the convolutional layers since I'm not taking any explicit steps there to regularize (besides keeping the layers as small as possible). But based on examples provided with TensorFlow, it doesn't appear that regularization or dropout is typically applied to convolutional layers.</p>
<p>The only approach I've found online that explicitly deals with prevention of overfitting in convolutional layers is a fairly new approach called <a href="http://www.matthewzeiler.com/pubs/iclr2013/iclr2013.pdf" rel="noreferrer">Stochastic Pooling</a>. Unfortunately, it appears that there is no implementation for this in TensorFlow, at least not yet.</p>
<p>So in short, is there a recommended approach to prevent overfitting in convolutional layers that can be achieved in TensorFlow? Or will it be necessary to create a custom pooling operator to support the Stochastic Pooling approach?</p>
<p>Thanks for any guidance!</p>
| <tensorflow><conv-neural-network> | 2016-03-21 19:33:25 | HQ |
36,140,065 | PHP GET error $ | <p>I want to collect information from <a href="http://mywebsite1.com/register.php?log=firstname=Yoga&lastname=Galih" rel="nofollow">http://mywebsite1.com/register.php?log=firstname=Yoga&lastname=Galih</a></p>
<p>but i want to get that info to my 2nd website using PHP $_GET and save it to <code>reg.log</code></p>
<pre><code><?php
$txt = "reg.log";
if (isset($_GET["log"]) && isset($_GET["firstname"]) && isset($_GET["lastname"]) && isset($_GET["address"]) && isset($_GET["city"]) && isset($_GET["state"]) && isset($_GET["zip"]) && isset($_GET["country"]) && isset($_GET["phone"]) $$ isset($_GET["gender"]) && isset($_GET["haircolor"]) && isset($_GET["eyecolor"]) && isset($_GET["high"]) isset($_GET["weight"])) {
$firstname = $_GET["fname"];
$lastname = $_GET["lname"];
$address = $_GET["address"];
$city = $_GET["city"];
$state = $_GET["state"];
$zip = $_GET["zip"];
$country = $_GET["country"];
$gender = $_GET["gender"];
$haircolor = $_GET["hcolor"];
$eyecolor = $_GET["ecolor"];
$high = $_GET["high"];
$weight = $_GET["weight"];
$phone = $_GET["phone"];
echo $firstname .PHP_EOL. $lastname .PHP_EOL. $address .PHP_EOL. $city .PHP_EOL. $state .PHP_EOL. $zip .PHP_EOL. $country .PHP_EOL. $phone .PHP_EOL. $hcolor .PHP_EOL. $ecolor .PHP_EOL. $high .PHP_EOL. weigh .PHP_EOL. gender;
$fh = fopen($txt, 'a');
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the fil
}
?>
</code></pre>
<p>but I get error [21-Mar-2016 15:17:09 America/New_York] PHP Parse error: syntax error, unexpected '$' in /home/my2ndweb/public_html/includes/register.php on line 3</p>
<p>I need help</p>
<p>Thanks</p>
| <php> | 2016-03-21 19:37:42 | LQ_CLOSE |
36,140,252 | Browser: Identifier X has already been declared | <p>I am using ES6 with Babel in my project and I am getting an error when I declare one of my <code>const</code></p>
<pre><code>'use strict';
const APP = window.APP = window.APP || {};
const _ = window._;
APP.personalCard = (function () {
...
}());
</code></pre>
<p>the error</p>
<blockquote>
<p>Uncaught TypeError: Identifier 'APP' has already been declared</p>
</blockquote>
<p>and that is the whole file, I don't have that declare anywhere else in that file. But I have declared that var in the top of the other files.</p>
<p>What do you think it should be ?</p>
| <javascript><ecmascript-6> | 2016-03-21 19:48:33 | HQ |
36,140,395 | Getting [Object HTMLInputElement] error | <p>looping through a json encoded output for a Month Year value, and trying to convert it a month number before passing it to next step in code ...</p>
<pre><code>... foreach loop
var month_number = null;
var dateOf = JSON.stringify(v.date);
if(dateOf.indexOf("January")>-1){month_number=1}else
if(dateOf.indexOf("February")>-1){month_number=2}else
if(dateOf.indexOf("March")>-1){month_number=3}
});
htmlStr += '<input type="hidden" id="month_number" value="' + month_number + '" />';
</code></pre>
<p>returning [Object HTMLInputElement] for month_number ... everything else is working ...</p>
| <javascript><jquery><html><json><string> | 2016-03-21 19:57:01 | LQ_CLOSE |
36,140,440 | What IP's are in this IP block and how to use them? | <p>I am very new to this IP block thing so please excuse any "nooby" mistakes.</p>
<p>I just purchased a dedicated server and in my control panel it says:</p>
<blockquote>
<p>IPv4 Assignment #1: 192.151.150.194/29</p>
</blockquote>
<p>Does this mean the following IP addresses are usable? </p>
<ul>
<li>192.151.150.193</li>
<li>192.151.150.194</li>
<li>192.151.150.195 </li>
<li>192.151.150.196</li>
<li>192.151.150.197</li>
<li>192.151.150.198</li>
</ul>
<p>If the IP's listed above are correct, do I have to enable them to use them?</p>
<p>Thanks,
Faraaz</p>
| <centos><ip><subnet> | 2016-03-21 19:58:59 | LQ_CLOSE |
36,141,302 | Why is it recommended to include the private key used for assembly signing in open-source repositories? | <p>According to <a href="https://msdn.microsoft.com/en-us/library/wd40t7ad(v=vs.110).aspx" rel="noreferrer">MSDN</a>, it is a recommended practice to include both the private and public keys used for strong-naming assemblies into the public source control system if you're developing open-source software:</p>
<blockquote>
<p>If you are an open-source developer and you want the identity benefits of a strong-named assembly, consider checking in the private key associated with an assembly into your source control system.</p>
</blockquote>
<p>This is something that confuses me greatly. Making the private key public? Wouldn't the whole purpose and security of asymmetric cryptography be defeated in this case?</p>
<p>I see in the same article this note:</p>
<blockquote>
<p>Do not rely on strong names for security. They provide a unique identity only.</p>
</blockquote>
<p>This does not help reduce my confusion. Why then use a private-public key pair if security is not the aim? Is the strong-naming mechanism in .NET using private-public key pairs in an inappropriate way? My guess is that I'm missing or misunderstanding something.</p>
| <c#><.net><open-source><signing><strongname> | 2016-03-21 20:49:04 | HQ |
36,141,388 | How can I get all keys from a JSON column in Postgres? | <p>If I have a table with a column named <code>json_stuff</code>, and I have two rows with</p>
<p><code>{ "things": "stuff" }</code> and <code>{ "more_things": "more_stuff" }</code></p>
<p>in their <code>json_stuff</code> column, what query can I make across the table to receive <code>[ things, more_things ]</code> as a result?</p>
| <json><postgresql> | 2016-03-21 20:53:45 | HQ |
36,141,619 | Can't use global variable in PHP | <p>I'm trying to use a global variable, but it's saying that there's a unexpected equal sign? How is that...?</p>
<pre><code><?php
global $text = "text";
echo $text;
?>
</code></pre>
<p>Parse error: syntax error, unexpected '=', expecting ',' or ';' in /home/chatwith/public_html/chatwithibot/test.php on line 3</p>
| <php><global> | 2016-03-21 21:07:29 | LQ_CLOSE |
36,142,239 | Use host networking and additional networks in docker compose | <p>I'm trying to set up a dev environment for my project.</p>
<p>I have a container (ms1) which should be put in his own network ("services" in my case), and a container (apigateway) which should access that network while exposing an http port to the host's network.</p>
<p>Ideally my docker compose file would look like this:</p>
<pre><code>version: '2'
services:
ms1:
expose:
- "13010"
networks:
services:
aliases:
- ms1
apigateway:
networks:
services:
aliases:
- api
network_mode: "host"
networks:
services:
</code></pre>
<p>docker-compose doesn't allow to use network_mode and networks at the same time.</p>
<p>Do I have other alternatives?</p>
<p>At the moment I'm using this:</p>
<pre><code> apigateway:
networks:
services:
aliases:
- api
ports:
- "127.0.0.1:10000:13010"
</code></pre>
<p>and then apigateway container listens on 0.0.0.0:13010. It works but it is slow and it freezes if the host's internet connection goes down.</p>
<p>Also, I'm planning on using vagrant in the future upon docker, does it allow to solve in a clean way?</p>
| <networking><docker><vagrant><docker-compose><devops> | 2016-03-21 21:47:17 | HQ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.