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 |
|---|---|---|---|---|---|
38,971,436 | error while executing do in background android | <p>I've two things I want to ask about. I'm ready to eat this laptop at this stage.
My location permissions seem to be working as I haven't had a crash or a dialogue saying I haven't permission for it, (although I haven't seen the dialogue requesting permissions either...) but the setText() to the textView doesn't seem to be doing the job either. My latest problem is retrieving the image to encode for image upload after the picture is taken. </p>
<p>Here is my code. The permissions are requested in the manifest. I will drive this laptop across the garden with a boot if I'm looking at this for much longer. Stuck on this for 3 days with a project due in two weeks with a months worth of work left in it. Save me stackoverflow!</p>
<pre><code>package com.example.gary.natureallv2;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class CameraPicActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static final int CAMERA_REQUEST = 10;
public static final int IMAGE_GALLERY_REQUEST = 20;
private ImageView ivPicSelected;
private FusedLocationProviderApi locationProviderApi = LocationServices.FusedLocationApi;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
public final static int MILLISECONDS_PER_SECOND = 1000;
public final static int MINUTE = 60 * MILLISECONDS_PER_SECOND;
private static final int MY_PERMISSION_REQUEST_FINE_LOCATION = 101;
private static final int MY_PERMISSION_REQUEST_COARSE_LOCATION = 102;
private boolean permissionIsGranted = false;
private TextView tvLatValue;
private TextView tvLongValue;
private double longitude;
private double latitude;
private String encoded_string, image_name;
private Bitmap bitmap;
private File file;
private Uri file_uri;
private Button btnUploadPic;
private Parcelable picUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_pic);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
//initialise the location request with the accuracy and frequency with which we want location updates
locationRequest = new LocationRequest();
locationRequest.setInterval(MINUTE);
locationRequest.setFastestInterval(15 * MILLISECONDS_PER_SECOND);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
ivPicSelected = (ImageView) findViewById(R.id.ivPicSelected);
tvLatValue = (TextView) findViewById(R.id.tvLatValue);
tvLongValue = (TextView) findViewById(R.id.tvLongValue);
btnUploadPic = (Button) findViewById(R.id.btnUploadPic);
btnUploadPic.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
getFileUri();
}
});
}
/**
* Method called when btnFromCamera is clicked.
* @param view
*/
public void btnFromCameraClicked(View view){
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);//
// String pictureName = getPictureName();//
// File imageFile = new File(pictureDirectory, pictureName);//
// Uri pictureUri = Uri.fromFile(imageFile);//
// cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);//
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* This method is invoked when the user presses the From Gallery button.
* @param view
*/
public void onBtnGalleryClicked(View view){
//Invoke the image gallery with an implicit intent.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//Where to find the data.
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
//get a Uri representation.
Uri data = Uri.parse(pictureDirectoryPath);
//set the data and type/get all image types.
photoPickerIntent.setDataAndType(data, "image/*");
startActivityForResult(photoPickerIntent, IMAGE_GALLERY_REQUEST);
}
private String getPictureName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timeStamp = sdf.format(new Date());
return "natureall" + timeStamp +".jpg";
}
private void getFileUri() {
image_name = "testing123.jpg";
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ File.separator + image_name);
file_uri = Uri.fromFile(file);
}
public void onBtnUploadClick(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
getFileUri();
i.putExtra(MediaStore.EXTRA_OUTPUT, file_uri);
startActivityForResult(i, 10);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
if (requestCode == CAMERA_REQUEST){
Bitmap cameraImage = (Bitmap) data.getExtras().get("data");
ivPicSelected.setImageBitmap(cameraImage);
}
if (requestCode == IMAGE_GALLERY_REQUEST){
Uri imageUri = data.getData();
//declare a stream to read the image data.
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);
Bitmap image = BitmapFactory.decodeStream(inputStream);
ivPicSelected.setImageBitmap(image);
} catch (FileNotFoundException e) {
Toast.makeText(this, "Unable to open the image",Toast.LENGTH_LONG ).show();
}
}
if(requestCode == 10 && resultCode == RESULT_OK) {
new Encode_image().execute();
}
}
}
/*Possible way to recover pics after saving to external storage*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("picUri", picUri);
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
picUri= savedInstanceState.getParcelable("picUri");
}
/*End of/Possible way to recover pics after saving to external storage*/
private class Encode_image extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
bitmap = BitmapFactory.decodeFile(file_uri.getPath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte [] array = stream.toByteArray();
encoded_string = Base64.encodeToString(array, 0);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
makeRequest();
}
}
private void makeRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.1.15/myDocs/mainProject/res/connection.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams ()throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("encoded_string", encoded_string);
map.put("image_name", image_name);
return map;
}
};
requestQueue.add(request);
}
@Override
public void onConnected(Bundle bundle){requestLocationUpdates();}
private void requestLocationUpdates(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_FINE_LOCATION);
}
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
protected void onStart() {
super.onStart();
if (permissionIsGranted) {
googleApiClient.connect();
}
}
@Override
protected void onStop() {
super.onStop();
if (permissionIsGranted) {
googleApiClient.disconnect();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case MY_PERMISSION_REQUEST_FINE_LOCATION:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
permissionIsGranted = true;
Toast.makeText(this, "Permission Granted", Toast.LENGTH_LONG).show();
}
else{
permissionIsGranted = false;
Toast.makeText(getApplicationContext(), "This app requires location permissions to be granted", Toast.LENGTH_SHORT).show();
tvLatValue.setText("Lat permission denied");
tvLongValue.setText("Long permission denied");
}
break;
}
}
@Override
protected void onResume() {
super.onResume();
if (permissionIsGranted){
if (googleApiClient.isConnected())
requestLocationUpdates();
}}
@Override
protected void onPause() {
super.onPause();
if(permissionIsGranted) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
@Override
public void onLocationChanged(Location location) {
if (permissionIsGranted){
//Toast.makeText(this, "Location Changed:" + location.getLatitude() + " " + location.getLongitude(), Toast.LENGTH_LONG).show();
longitude = location.getLongitude();
latitude = location.getLatitude();
tvLongValue.setText(Double.toString(longitude));
tvLatValue.setText(Double.toString(latitude));
}
}
}
</code></pre>
<p>The image is saved to external storage but I'm getting this error:</p>
<pre><code> java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getPath()' on a null object reference
at com.example.gary.natureallv2.CameraPicActivity$Encode_image.doInBackground(CameraPicActivity.java:217)
at com.example.gary.natureallv2.CameraPicActivity$Encode_image.doInBackground(CameraPicActivity.java:214)
</code></pre>
| <android><android-asynctask><permissions> | 2016-08-16 09:38:11 | LQ_CLOSE |
38,971,786 | Do stuffs inside a for in a thread android | @Override
public void run() {
act.runOnUiThread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < randomNumber.size(); i++) {
Log.d("N",randomNumber.get(i).toString());
if (randomNumber.get(i).intValue() == 1) imgColor.setBackgroundColor(Color.RED);
if (randomNumber.get(i).intValue() == 2) imgColor.setBackgroundColor(Color.GREEN);
if (randomNumber.get(i).intValue() == 3) imgColor.setBackgroundColor(Color.BLUE);
if (randomNumber.get(i).intValue() == 4) imgColor.setBackgroundColor(Color.YELLOW);
try {
Thread.sleep(1750);
} catch (Exception e) {
Thread.currentThread().interrupt();
}
imgColor.setBackgroundColor(Color.BLACK);
try {
Thread.sleep(400);
} catch (Exception e) {
Thread.currentThread().interrupt();
}
}
Toast.makeText(act, "Ripeti la sequenza", Toast.LENGTH_SHORT).show();
}
});
}
I'm trying to have imgColor ImageView colored each 1,75 second with a different color according to the value of the number in the randomColor ArrayList, but it doesn't work ! What should I do ?
Thanks in advance | <java><android> | 2016-08-16 09:53:44 | LQ_EDIT |
38,972,341 | What's the best/proper way to set up my database | <p>I have a database, image below, and I feel that there must be an efficient way to add separate books for each child. For example... there may be 50 clubbers in the database. Each clubber will be in their own book and to make it simple, each book has 10 sections a clubber must complete. I was thinking of making a table for each child with the 10 sections, but that would end up with over 50 tables in my database. I also thought of creating a table called book and just having that table contain the 10 sections, but the problem with that is each child may be in one of 8 different books. So one table called book wouldn't work either. </p>
<p>Does anyone have a good suggestion on how to set this up in the database? My ultimate goal is to have each child linked to one of the 8 books that is available. Then the database will track which section each child is in for their certain book. So... today clubber A could finish section 1 and 2 in book 1, but clubber B might only finish section 1 in book 2. I'm wanting to pull this information from the database to see where each clubber is in their books... but... I first need to set the database up correctly.</p>
<p>Should I create 8 separate tables for each of the books and have the table data be section 1... section 2...? Or should I create one table and list 8 books in it and then link that to another table that has the section info? Or is there an even better way?</p>
<p>Thanks for any help<img src="https://i.stack.imgur.com/oem72.jpg" alt="![mydatabase"> </p>
| <php><mysql><database> | 2016-08-16 10:20:38 | LQ_CLOSE |
38,973,206 | sqlzoo:what's wrong with the answer for 'The award for the first time (Economics) who is the winner?' | here is my answer,but the result shows wrong,i want to know why and the correct answer!!
SELECT winner FROM nobel
WHERE subject='Economics' AND yr IN (SELECT min('yr') FROM nobel
WHERE subject='Economics'); | <sql> | 2016-08-16 11:02:31 | LQ_EDIT |
38,973,946 | i am new to angular js trying to addclass but getting error addclass not a function | i am new to angular js trying to addclass but getting error addclass not a function plz help
$scope.viewReport = function(ev,element) {
window.location="#tab7";
$scope.tabact = document.getElementById('tab7');
console.log($scope.tabact);
$scope.tabact.addClass('active');
$rootScope.callOrder = false
$rootScope.step1=true
$rootScope.step2=false
$rootScope.step3=false
} | <angularjs> | 2016-08-16 11:39:22 | LQ_EDIT |
38,974,623 | SimpleDateFormat is giving wrong Date | <p><strong>I am inputting a specific date (dd/MM/yyyy) , while displaying it the Output is something else.</strong></p>
<pre><code>import java.text.*;
import java.io.*;
import java.util.*;
class InvalidUsernameException extends Exception //Class InvalidUsernameException
{
InvalidUsernameException(String s)
{
super(s);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class InvalidPasswordException extends Exception //Class InvalidPasswordException
{
InvalidPasswordException(String s)
{
super(s);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class InvalidDateException extends Exception //Class InvalidPasswordException
{
InvalidDateException(String s)
{
super(s);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class EmailIdb1 //Class Email Id b1
{
String username, password;
int domainid;
Date dt;
EmailIdb1()
{
username = "";
domainid = 0;
password = "";
dt = new Date();
}
EmailIdb1(String u, String pwd, int did, int d, int m, int y)
{
username = u;
domainid = did;
password = pwd;
dt = new Date(y,m,d); // I think There is a problem
SimpleDateFormat formater = new SimpleDateFormat ("yyyy/MM/dd"); //Or there can be a problem
try{
if((username.equals("User")))
{
throw new InvalidUsernameException("Invalid Username");
}
else if((password.equals("123")))
{
throw new InvalidPasswordException("Invalid Password");
}
else{
System.out.println("\nSuccesfully Login on Date : "+formater.format(dt));
}
}
catch(Exception e)
{
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class EmailId //Class Email Id
{
public static void main(String args[])
{
int d,m,y,did;
String usn,pwd;
EmailIdb1 eml;
try{
usn = args[0];
pwd = args[1];
did = Integer.parseInt(args[2]);
d = Integer.parseInt(args[3]);
m = Integer.parseInt(args[4]);
y = Integer.parseInt(args[5]);
switch(m)
{
case 2: if(d==29 && y%4 == 0)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else if(d<=28 && d>=1)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else{
throw new InvalidDateException("Wrong Date.");
}
break;
case 1: case 3: case 5: case 7: case 8: case 10:
case 12: if(d>=1 && d<=31)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else
{
throw new InvalidDateException("Invalid Date");
}
break;
case 4: case 6: case 9:
case 11: if(d>=1 && d<=30)
{
eml = new EmailIdb1(usn,pwd,did,d,m,y);
}
else
{
throw new InvalidDateException("Invalid Date");
}
break;
default : throw new InvalidDateException("Invalid Date");
}
}
catch(InvalidDateException ed)
{
System.out.println(ed);
}
}
}
</code></pre>
<p>Me and my two friends have similar kind of problem. Don't know why This is Happening. My teacher also couldn't find what's the problem</p>
<p>The Output Should be</p>
<pre><code>Successfully Login on Date : 1994/05/04
</code></pre>
<p>As the Input Is</p>
<pre><code>Successfully Login on Date : 3894/06/04
</code></pre>
| <java><date><simpledateformat> | 2016-08-16 12:11:00 | LQ_CLOSE |
38,974,675 | what does "echo" mean when it comes to using maven | I'm currently learning how to use Maven and have encountered a term called "echo". I was just wondering what it actually means? Thanks in advance for any suggestions and help!
[![enter image description here][1]][1]
[1]: http://i.stack.imgur.com/7MhXb.png | <maven><maven-antrun-plugin> | 2016-08-16 12:12:59 | LQ_EDIT |
38,974,918 | How to set priorities for multiple threads in java | <p>How does one set different priorities for different threads on JAVA?
Let us assume I have three threads A,B,C..and i want A to be of high priority..
How do I set the priority value in each case? Can I get a sample code for that?</p>
| <java> | 2016-08-16 12:24:56 | LQ_CLOSE |
38,975,773 | Simple math in a string (Java) | This is what I have :`
final EditText Pikkus = (EditText)findViewById(R.id.editText);
final EditText Laius = (EditText)findViewById(R.id.editText3);
final TextView pindala1 = (TextView)findViewById(R.id.editText2);
final TextView ymbermoot1 = (TextView)findViewById(R.id.textView5);
ImageButton button = (ImageButton)findViewById(R.id.teisenda);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String pindala2 = "" + Integer.parseInt(Pikkus.getText().toString()) * Integer.parseInt(Laius.getText().toString());
pindala1.setText(pindala2);
String ymbermoot2 = "" + Integer.parseInt(Pikkus.getText().toString()) + Integer.parseInt(Laius.getText().toString())
ymbermoot1.setText(ymbermoot2);
}
});
}`
But the `String ymbermoot2 = "" + Integer.parseInt(Pikkus.getText().toString()) + Integer.parseInt(Laius.getText().toString())
ymbermoot1.setText(ymbermoot2);`part doesn't work like its supposed to. Instead of adding up the values, it simply types them together. Example: integer Pikkus is 26, Laius is 23. The value should end up being 49, but my code somehow makes it to up to be 2623. Where's the mistake in the code? | <java><android><math> | 2016-08-16 13:04:47 | LQ_EDIT |
38,976,961 | executing a block of stetement at one go | <p>I have some block statements which fetches data from database increment it's value by one and again update in database,If am firing 5 requests it's working fine but if I am firing number of request (consider 10) within few seconds(consider 10 to 15 secs) I am getting same value for 2 to 3 request out of 10 request. what is solution so that I can get next value for each request ? I have tried synchronised block but it's not working...!</p>
| <java><synchronization> | 2016-08-16 13:59:51 | LQ_CLOSE |
38,977,424 | Replace Words in the parentheses to put into quotations - Unix / Linux | I want to replace the words in the parentheses to put into quotations.
Below is the data I have in one of the variable data -
SELECT * FROM ( SELECT Table1 file2.txt file.txt QUEUES QDefinitions
Parameters TRAP-Deposit-DSTran.dat.2016-08-07 FROM CS_CASE WHERE
ANT_CD='FI_BASE_TENANT') t1 LEFT OUTER JOIN Table2 t2 ON t2.CASE_ID=t1.CASE_ID LEFT OUTER JOIN Table3 t3 ON t3.SERVICE_XID=t1.SERVICE_XID LEFT OUTER JOIN Table4 t4 ON t4.SERVICE_ID=t1.SERVICE_ID WHERE ( t1.CASESTATUs_CD = (NEW,RETIRED,PENDING,OPEN,CLOSED) OR t1.CASE_STATUS_NUM = (1,2,3,4) ) GROUP BY t1.CASE_REFERENCE,t2.LAST_SCRFP,t1.SERVICE_ID ORDER BY t2.LAST_SCRFP DESC
Here is what I want.
SELECT * FROM ( SELECT Table1 file2.txt file.txt QUEUES QDefinitions
Parameters TRAP-Deposit-DSTran.dat.2016-08-07 FROM CS_CASE WHERE
ANT_CD='FI_BASE_TENANT') t1 LEFT OUTER JOIN Table2 t2 ON t2.CASE_ID=t1.CASE_ID LEFT OUTER JOIN Table3 t3 ON t3.SERVICE_XID=t1.SERVICE_XID LEFT OUTER JOIN Table4 t4 ON t4.SERVICE_ID=t1.SERVICE_ID WHERE ( t1.CASESTATUs_CD = ('NEW','RETIRED','PENDING','OPEN','CLOSED') OR t1.CASE_STATUS_NUM = (1,2,3,4) ) GROUP BY t1.CASE_REFERENCE,t2.LAST_SCRFP,t1.SERVICE_ID ORDER BY t2.LAST_SCRFP DESC
Previously I have used sed command as below
sed -E 's/\(([^(,$1)'\'']+)\)/('\''\1'\'')/g' Filename.txt
| <linux><perl><awk><sed><sas> | 2016-08-16 14:20:33 | LQ_EDIT |
38,978,107 | How to split the Billion or million | I am looking for an algorithm which splits the input number to number of millions .
suppose if the input number is 51000000 and my lot size is 50 million, then i want an output as 2.
if 110 million, then it would be 50+50+10 which means output as 3.
I tried a number of ways to calculate, but still i am unlucky , please give some clue on this | <java> | 2016-08-16 14:52:21 | LQ_EDIT |
38,978,211 | How do you access global variables updated in functions in JavaScipt? | I have two functions that update previously defined global variables. When I want to add the updated versions of the variables and print them to the console, JavaScript adds the original values that the variables were defined as. How do I add the updated values? I have included the code below.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var number1 = 1;
var number2 = 2;
function function1() {
number1 = 3;
}
function function2() {
number2 = 4;
}
console.log(number1 + number 2);
<!-- end snippet -->
| <javascript> | 2016-08-16 14:56:36 | LQ_EDIT |
38,978,719 | Need to validate textbox for a value, and a value between two numbers. Throwing an error | So i have a textbox which needs validation upon clicking my "Add" button.
The first check works fine when the other two checks aren't in the code. The bottom two checks are fine if I enter a value into the textbox. However when I have all three checks, when there isn't a value, the program throws back an error saying "input string was not in correct format".
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
if (txtAge.Text == "")
{
message += "<br>Please fill in your Age.</br>";
}
if (Convert.ToInt32(txtAge.Text) > 120)
{
message += "<br>Age cannot be greater than 120</br>";
}
if (Convert.ToInt32(txtAge.Text) < 6)
{
message += "<br>Age cannot be less than 6</br>";
}
<!-- end snippet -->
| <c#> | 2016-08-16 15:22:16 | LQ_EDIT |
38,980,241 | Making a text field required only if another text field has been filled out in C# | <p>I'm making a web form to enter customer information into a database. I have 4 textboxes for billingAddress, billingCity, billingState, and billingZip. BillingAddress is an optional field.</p>
<p>My question is: how can I set up requiredfieldvalidators on billingCity, billingState, and billingZip so that these fields are only required if billingAddress has been filled out?</p>
<p>*Side Note: Database requirements have separate columnms for address, city, state, and zip code, so I can't just combine them into one field.</p>
| <c#><validation> | 2016-08-16 16:40:44 | LQ_CLOSE |
38,981,110 | PHP not selecting my first row from mysql database | <p>My connection to the database works fine. My application can display all my data, except the first row. When I run it locally through MySQL workbench, it fetches my first row, and every row after that. It is just my PHP code that is not getting the first row, and I am unsure why. </p>
<pre><code><?php
//connect with database
$connect= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect to the database!");
$query="select * from college";
$result=$connect->query($query);
$jsonData = array();
while ($array = mysqli_fetch_assoc($result)) {
$jsonData[] = $array;
}
echo json_encode($jsonData);
?>
</code></pre>
| <php><mysql><sql> | 2016-08-16 17:32:07 | LQ_CLOSE |
38,981,863 | Can empty HTML elements have attirbutes in HTML? | Empty HTML elements(i.e. elements having no content and no closing tag) like
- br
- hr
or any other HTML elements which I'm not aware of can have attributes in latest HTML5 standard?
Somebody please explain me in simple and easy to understand language.
Thanks. | <html> | 2016-08-16 18:18:09 | LQ_EDIT |
38,981,960 | Ordering numbers by random | <p>i have some list with 5 numbers (exp. 1 2 3 4 5) i want to order them in random ordering each time (page refresh) examples: (2 4 3 1 5) (1 3 5 4 2) (5 1 2 3 4)... code in C#, Thanks</p>
<pre><code>var loadcards = (from card in db.GameCards
select card).Take(5).ToList();
foreach (var item in loadcards)
{
Response.Write("<script>alert('" + item.cardId + "');</script>");
}
</code></pre>
| <c#><linq> | 2016-08-16 18:23:08 | LQ_CLOSE |
38,982,302 | How to add an event on a menu in C# visual basic project? | I have a C# Visual Basic Windows Forms App that contain a menu bar.
I want to display a Help Message when I press on the "HELP" menu button.
All that I can see when I press view code is this:
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
I think that I need to create inside the function a MessageBox or an event that will display the desired message.
Do you have any idea how should I do this, please? | <c#> | 2016-08-16 18:44:11 | LQ_EDIT |
38,982,749 | What programming language is best suited for a 2D platformer game with my experience? | <p>Me and a few friends want to start building a 2D puzzle platformer. It uses a lot of tiles and we experienced that our test level did not run smoothly with Java. Do any of you have suggestions on which programming language/engine would be best suited to make the game? </p>
<p>We have experience with Java and Actionscript 3.</p>
<p>Thank you in advance for your advise.</p>
| <2d><game-engine><tiles> | 2016-08-16 19:12:25 | LQ_CLOSE |
38,983,815 | Reset USB port power with Windows command prompt | <p>I have an USB equipment that stops working when my computer reboots. The only solution is to kill the power of the port. Is there a command in the Windows Prompt that can kill the USB power? </p>
<p>Any tip will be very helpful,</p>
<p>Thanks</p>
| <windows><cmd><usb> | 2016-08-16 20:22:31 | LQ_CLOSE |
38,986,092 | How can I change the finder background color on mac Yosemite 10.10.5 | <p>Every post I've seen says to open a finder, click view > Show View Options, and there is a background section to change the color of thew background. But when I go into show view options all it has is arrange by:, sort by: and text size. </p>
<p>Did the background option get moved? If not what can I do to make it show?</p>
| <macos><osx-yosemite> | 2016-08-16 23:41:34 | LQ_CLOSE |
38,986,365 | How to make a tablet screen open on command? | <p>i want to make my samsung galaxy tab 3 t111 screen to be permanent open only when it's connected to the microUSB. Trying to make a car navigation.</p>
| <android><tablet> | 2016-08-17 00:21:06 | LQ_CLOSE |
38,986,861 | save pictures while i scrap them from website using vb.net | hi guys i find a code on youtube when i use it on my visual basic and debug it and find pictures but when i want to save them software gives me this message
[enter image description here][1]
[1]: http://i.stack.imgur.com/EJhK7.jpg
and this is code i use
Private Sub btnSaveImages_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnSaveImages.Click
Dim dir_name As String = txtDirectory.Text
If Not dir_name.EndsWith("\") Then dir_name &= "\"
For Each pic As PictureBox In flpPictures.Controls
Dim bm As Bitmap = pic.Image
Dim filename As String = pic.Tag
filename = _
filename.Substring(filename.LastIndexOf("/") + _
1)
Dim ext As String = _
filename.Substring(filename.LastIndexOf("."))
Dim full_name As String = dir_name & filename
Select Case ext
Case ".bmp"
bm.Save(full_name, Imaging.ImageFormat.Bmp)
Case ".gif"
bm.Save(full_name, Imaging.ImageFormat.Gif)
Case ".jpg", "jpeg"
bm.Save(full_name, Imaging.ImageFormat.Jpeg)
Case ".png"
bm.Save(full_name, Imaging.ImageFormat.Png)
Case ".tiff"
bm.Save(full_name, Imaging.ImageFormat.Tiff)
Case Else
MessageBox.Show( _
"Unknown file type " & ext & _
" in file " & filename, _
"Unknown File Type", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Select
Next pic
Beep()
End Sub | <vb.net><vb.net-2010> | 2016-08-17 01:36:56 | LQ_EDIT |
38,987,079 | Return first letter of each word capitalized | C | I'm learning C for fun, I just started and I'm trying to write a function to take a string, and return the first letter of each word capitalized.
Eg: 'The sun in the sky' => TSITS
Here is my code, after tinkering quite a bit I manage to be able to compile; but seems like it only print the spaces of the string
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
string s = GetString();
for (int i=0;i<strlen(s);i++){
if(i == s[0] || s[i-1] == ' ' ){
s[i] = toupper(s[i]);
printf("%c",i);
i++;
}
}
}
What's wrong with it? Thanks in advanced :) | <c><cs50> | 2016-08-17 02:10:44 | LQ_EDIT |
38,988,370 | How to insert struct data to a file? | <p>I've been working on a records system, everything looks good but </p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
struct students{
string studentID;
string surname;
string firstname;
string birthdate;
string sex;
};
int main()
{
fstream collection;
string filename;
short choice;
do{
int ctr=1;
system("cls");
if(collection.is_open()){
cout<<"Active File: ["<<filename<<"]"<<endl;
}else{
cout<<"Active File|: [None opened]"<<endl;
}
cout<<"[1] Create new file"<<endl;
cout<<"[2] Open existing file"<<endl;
cout<<"[3] Manage data"<<endl;
cout<<"[4] Exit"<<endl;
cout<<"Enter operation index: ";
cin>>choice;
switch(choice){
case 1:
cout<<"Enter file name: ";
cin>>filename;
collection.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);
collection<<"------------------------------------------------------------------------------"<<endl;
collection<<"Rec \t Student ID \t Surname \t Firstname \t Birthdate \t Sex \t"<<endl;
collection<<"------------------------------------------------------------------------------"<<endl;
collection.close();
collection.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);
break;
case 2:
cout<<"Enter file name: ";
cin>>filename;
collection.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);
break;
case 3:
string lines;
char menu;
students student[10];
do{
ifstream collection(filename, std::fstream::in | std::fstream::out | std::fstream::app);
if(collection.is_open()){
cout<<"Active File: ["<<filename<<"]";
system("cls");
while(getline(collection,lines)){
cout<<lines<<endl;
}
}
collection.close();
cout<<"[A]dd [E]dit [D]elete [S]ort [F]ilter Sa[V]e e[X]it";
cin>>menu;
if(menu=='A'){
string lines2;
collection.open(filename,ios::app);
system("cls");
ifstream collection(filename, std::fstream::in | std::fstream::out | std::fstream::app);
if(collection.is_open()){
while(getline(collection,lines)){
cout<<lines<<endl;
}
}
cout<<endl<<"Adding data to "<<filename<<endl;
cout<<"Student ID: ";
cin>>student[ctr].studentID;
cout<<"Surname: ";
cin>>student[ctr].surname;
cout<<"Firstname: ";
cin>>student[ctr].firstname;
cout<<"Birthdate: ";
cin>>student[ctr].birthdate;
cout<<"Sex: ";
cin>>student[ctr].sex;
</code></pre>
<p>Why do I keep getting errors here?</p>
<pre><code> //data insertion code heree
collection.open(filename, std::fstream::in | std::fstream::out | std::fstream::app);
collection<<ctr<<"\t"student[ctr].studentID<<"\t"student[ctr].surname<<"\t"student[ctr].firstname<<"\t"student[ctr].birthdate<<"\t"student[ctr].sex<<endl;
collection.close();
ctr++;
}else if(menu=='E'){
}else if(menu=='D'){
}else if(menu=='F'){
}else if(menu=='V'){
cout<<"Saving file..."<<endl;
collection.close();
cout<<"File saved."<<endl;
system("pause");
}else{
cout<<"Invalid input."<<endl;
system("pause");
};
}while(menu!='X');
break;
}
}while(choice!=4);
}
</code></pre>
<p>Why am I getting error: no match for 'operator<<' in 'collection << ctr'| errors? The code worked on the early part of the system and it just didn't work.</p>
| <c++> | 2016-08-17 04:56:34 | LQ_CLOSE |
38,989,288 | ng-click is not working in angularjs. Please help some one. | <li>
<a href="javascript:;">
<i class="fa fa-file-excel-o" ng-click="export()"></i> Export to Excel </a>
</li>
Here is the click function.but it is not working properly. pleas help. | <angularjs> | 2016-08-17 06:14:36 | LQ_EDIT |
38,990,119 | how to solve this json error | iam new in json i dont know how to stringify the the data . below i write a code for alert the content but some error is shown how i solve that error
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$('.savebutton').on('click', function (){
var myjson = {}
var mainobject =[]
myjson.push(mainobject);
mainobject.main = {}
mainobject.main.tittle = "'hai'";
mainobject.main.sub = [];
var subobejct = {}
mainobject.main.sub.push(subobejct);
subobejct.tittle = "levler";
subobejct.tasks = []
var task = {};
subobejct.tasks.push(task);
alert(JSON.stringify(myjson));
return myjson;
});
<!-- end snippet -->
| <javascript><jquery><json> | 2016-08-17 07:03:30 | LQ_EDIT |
38,990,742 | Who know hot convert this from curl to php | Does someone know how to convert this to php? Or may be can convert..
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/fjsdf834u8fhsdfh343/purge_cache" \
-H "X-Auth-Email: user@example.com" \
-H "X-Auth-Key: c254fsdfg34320b638f5e225c545fsddasc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}' | <php><curl> | 2016-08-17 07:39:04 | LQ_EDIT |
38,991,523 | How to get proper url rewriting with proper ReWriting Rule in localhost? | **My .htaccess file as below,**
DirectoryIndex routing.php
RewriteEngine on
RewriteBase /
RewriteCond %{THE_REQUEST} \s/+Milan_Practice/Milan_Mvc/routing\.php[\s?] [NC]
RewriteRule ^ Milan_Practice/Milan_Mvc/ [L,R=302]
RewriteRule ^Milan_Mvc/?$ Milan_Mvc/routing.php [L,NC]
**By Appling above code I got url like below,**
http://localhost/Milan_Practice/Milan_Mvc/?name=about
**in above,there after "?",data is not in valid format as I want like this,**
http://localhost/Milan_Practice/Milan_Mvc/about/
**So please give your suggestion with proper ReWriting Rule for above code**
*ThankYou in Advance !!!* | <php><localhost> | 2016-08-17 08:21:48 | LQ_EDIT |
38,993,048 | Fastest way to get a distributed spark cluster to parallelize a massive compressed local directory? | How can I get a distributed spark cluster to parallelize a massive compressed directory (1 terabyte uncompressed) of small text files, if that file is on one local machine? Ideally, this entire document would already be on a shared file system like HDFS or Hive, but it's currently on a local machine. sanitizing and placing each file in this directory onto a distributed data store will take on the order of days if done locally. is there any way for remote spark workers to partition this zipped file, and just start batch processing their chunks and dumping their results in a distributed store? if so, what is the fastest store i should be using? | <apache-spark><mapreduce><etl><distributed-computing><bigdata> | 2016-08-17 09:39:54 | LQ_EDIT |
38,993,405 | How to add an element to a existing json array | I have a JSON object:
var data = [{"name":"albin"},{"name, "alvin"}];
How can I add an element to all the records?
I want to add "age":"18" to all the records:
[{"name":"albin", "age":"18"},{"name, "alvin", "age":"18"}]; | <javascript><node.js> | 2016-08-17 09:56:35 | LQ_EDIT |
38,993,535 | Out of Memory Exception during serialization | <p>I am fetching 300k+ records in a object from database. I am trying to serialize the heavy object below:</p>
<pre><code>List<user> allUsersList = businessProvider.GetAllUsers();
string json = JsonConvert.SerializeObject(allUsersList);
</code></pre>
<p>I am getting following exception while serializing the list - allUsersList.</p>
<p><em>Out of memory exception</em></p>
<p>i am using newtonsoft.json assembly to deserialize it.</p>
| <c#><json><serialization> | 2016-08-17 10:02:23 | LQ_CLOSE |
38,995,173 | Spring Security show home page only after succes login | <p>I would like to show user home page only after succes login.</p>
<p>I mean, when somebody will hit the url for application like "ht'tp://localhost:8081/example", I want to redirect him to "ht'tp://localhost:8081/example/login" and only after loging in, user will see default home page which will be on "url/example" where he can do some actions or logout.</p>
<p>Using example from mkyong <a href="http://www.mkyong.com/spring-security/spring-security-hibernate-annotation-example/" rel="nofollow">http://www.mkyong.com/spring-security/spring-security-hibernate-annotation-example/</a>.</p>
<p>Didn't find answer on stack, maybe someone will help me with this.</p>
| <java><spring><hibernate><spring-mvc> | 2016-08-17 11:18:24 | LQ_CLOSE |
38,997,992 | setting python object property not changing value | <p>If you look at my code below, I'm creating a FileNode and passing it the string(filename). When the filename setter is triggered it should then populate the remaining fields, however it doesn't appear to work. </p>
<p>I'm currently just trying to test setting the property 'extension' within the 'filename' setter, but it doesn't seem to change the property, Why is this?</p>
<pre><code>import os
import pprint
class FileNode(object):
def __init__(self, filename):
self.filename = filename
self.show = ""
self.episode = ""
self.sequence = ""
self.shot = ""
self.task = ""
self.version = ""
self.extension = ""
self.isValid = False
@property
def filename(self):
return self.filename
@property
def extension(self):
return self.extension
@filename.setter
def filename(self, value):
self._filename = value
fl, ex = os.path.splitext(value)
self._extension = "candles"
@extension.setter
def extension(self, value):
self._extension = value
a = FileNode("BTMAN_1005_001_007_model_cup_v001.max")
# print (vars(a))
pp = pprint.PrettyPrinter(depth=6)
pp.pprint(vars(a))
b = FileNode("BTMAN_1005_001_007_model_v001.max")
# print (vars(b))
pp = pprint.PrettyPrinter(depth=6)
pp.pprint(vars(b))
</code></pre>
| <python> | 2016-08-17 13:25:27 | LQ_CLOSE |
38,998,596 | Get .tsv file from an archive in java without unzipping the archive | <p>I have an archive <code>_2016_08_17.zip</code> that contains 8 .tsv files. I need to extract the file named <code>hit_data.tsv</code> and upload it to bigquery. The files are in a bucket on the google cloud platform.</p>
<p>Can someone give me a simple program that opens the archive, finds the correct file and then prints its rows to screen. I can take it from there. My idea is to replace the path <code>gs://path_name/*hit_data.tsv</code> with the buffer that contains the <code>hit_data.tsv</code> data.</p>
<pre><code> public static void main(String[] args) {
Pipeline p = DataflowUtils.createFromArgs(args);
p
.apply(TextIO.Read.from("gs://path_name/*hit_data.tsv"))
\\.apply(Sample.<String>any(10))
.apply(ParDo.named("ExtractRows").of(new ExtractRows('\t', "InformationDateID")))
.apply(BigQueryIO.Write
.named("BQWrite")
.to(BigQuery.getTableReference("ddm_now_apps", true))
.withSchema(getSchema())
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED));
p.run();
}
</code></pre>
| <java> | 2016-08-17 13:51:01 | LQ_CLOSE |
38,998,713 | can I export a database that I only have access through "select" (oracle database) | If someone give me access to "select" his oracle database, can I export all his data using sqldeveloper? How?
He gave me access through grant statement. | <oracle><export><oracle-sqldeveloper> | 2016-08-17 13:54:33 | LQ_EDIT |
38,999,317 | how to simulate saturations and thresholds with scipy? | how to simulate saturations and thresholds with scipy?
If it is not directly possible, you have another method to simulate? | <python><scipy> | 2016-08-17 14:22:05 | LQ_EDIT |
39,000,830 | Add something in front of domain name | <p>I own a domain, suppose <strong>www.something.com</strong>. How can I make a web page with a link like <strong>www.abc.something.com</strong> ? I want to add something in front of the root domain name. Please help.</p>
| <php><web><dns><subdomain> | 2016-08-17 15:33:59 | LQ_CLOSE |
39,001,305 | Can't finish the loop when asking for valid asnwers | I have a problem with my code that I can't find the solution to. I ask for questions that has to be valid but the loops just continues, and let me input.
print('Do you want to go to the store or woods?')
lists = ('woods', 'store')
while True:
answers = input()
if answers == 'store':
break
print('Going to the store...')
elif answers == 'woods':
break
print('Going to the woods...')
while lists not in answers:
print('That is not a valid answer') | <python><adventure> | 2016-08-17 15:57:39 | LQ_EDIT |
39,002,640 | Set up Rmonkey API key, secret, client id,redirect uri...still not working | <p>I followed the directions on this page to set up my Mashery Survey Monkey account. I set my API key and secret options using their values on the app. I used my client ID, which I assume is my "display name" to set sm_client_id. I then used smlogin(), and was directed to a page with the following error:</p>
<p>SurveyMonkey</p>
<p>The authorization request failed:
Invalid client_id and/or redirect_uri</p>
<p>What else could I be doing wrong?</p>
<p>BTW, I tried this setting the app both as Public and Private. Same problem each time.</p>
| <r><surveymonkey> | 2016-08-17 17:13:29 | LQ_CLOSE |
39,003,015 | How to traverse through three selection related combo boxes with enable disable state in C#? | I spend a lot of time trying to resolve this.
I have 3 combo boxes, i`m trying to make first active when the form is loaded and the rest inactive.
When the value (double type) is selected in first cmb, second is activated and first become inactive, than the value is selected in second and first remain inactive and second become inactive activating the third one after selecting value from the third combo box first become active and the rest inactive until the selection start again.
I tried with loops but quickly become very complicated :-(
I hope this is clear enough :-)
Thank you | <c#><winforms><combobox> | 2016-08-17 17:35:35 | LQ_EDIT |
39,003,173 | PHP or Javascript - Getting values out of a string | <p>I have the following string:</p>
<pre><code>[(33, 165) (1423, 254)]
</code></pre>
<p>How can I bring the 4 numbers into an Array? I tried with regex so far.</p>
<p>Result should be an array containing 33,165,1423,254.</p>
<p>I can use a PHP and Javascript solution.</p>
| <javascript><php><arrays><regex><string> | 2016-08-17 17:45:27 | LQ_CLOSE |
39,004,718 | Android button style | My button looks like this
[Button][1]
How can i make a simple button same as this [desired][2]
[1]: http://i.stack.imgur.com/xDcE1.png
[2]: http://i.stack.imgur.com/oUYB7.png | <android><xml><button> | 2016-08-17 19:24:05 | LQ_EDIT |
39,006,126 | Read strings from a file | <pre><code> FILE *fp;
char name[50];
fp=fopen("stu.txt","r");
while(fgets(name,50,fp)!=NULL)
{
printf(" %s",name);
fgets(name,50,fp);
}
fclose(fp);
</code></pre>
<p>In my file there are 4 names in 4 different lines but the output only displays the 1st and the 3rd name.What's wrong?I know it's very basic but this has taken up a lot of my time.</p>
| <c><string><io> | 2016-08-17 20:56:03 | LQ_CLOSE |
39,006,278 | How does Bash modulus/remainder work? | <p>Can somebody explain how it works? I just don't understand it. Why we get 2 from </p>
<pre><code>expr 5 % 3
</code></pre>
<p>or 1 from </p>
<pre><code>expr 5 % 4
</code></pre>
| <bash><expression><modulus> | 2016-08-17 21:06:00 | LQ_CLOSE |
39,006,430 | Php convert a date to string character | <p>I have searched but I could not find out how to convert a date from a character string. For example string date is 18-08-2016 I want to convert 18 August 2016 How can I do?</p>
| <php> | 2016-08-17 21:18:01 | LQ_CLOSE |
39,006,438 | How do I insert PHP variables in a MySQL table? | <p>I have the following code that should create a table and populate it with two users. The create table query works, but the insert does not. Any help would be appreciated.</p>
<pre><code> <?php
require_once 'login12.php';
$link = mysqli_connect($db_hostname, $db_username, $db_password);
if (!$link) die ("Unable to connect to MySQL: " .mysqli_error());
mysqli_select_db($link, $db_database) or die("Unable to select database: " .mysqli_error());
$query = "CREATE TABLE `users` (
forename VARCHAR(32) NOT NULL,
surname VARCHAR(32) NOT NULL,
username VARCHAR(32) NOT NULL UNIQUE,
password VARCHAR(32) NOT NULL)";
$result = mysqli_query($link, $query);
if (!$result) die ("Database access failed: " .mysqli_error());
$salt1 = 'G3tD0wnonIT!';
$salt2 = 'Y0uwant2';
$forename = 'Bill';
$surname = 'Smith';
$username = 'bsmith';
$password = 'mysecret';
$token = sha1("$salt2$password$salt1");
add_user($forename, $surname, $username, $token);
$forename = 'Pauline';
$surname = 'Jones';
$username = 'pjones';
$password = 'acrobat';
$token = sha1("$salt2$password$salt1");
add_user($forename, $surname, $username, $token);
function add_user($fn, $sn, $un, $pw) {
$query = "INSERT INTO `users` (`forename`, `surname`, `username`, `password`) VALUES ('$fn', '$sn', '$un', '$pw')";
$result = mysqli_query($link, $query);
if (!$result) die ("Database access failed: " .mysqli_error());
}
?>
</code></pre>
| <php><mysql><apache><ubuntu> | 2016-08-17 21:18:30 | LQ_CLOSE |
39,007,693 | Include an array of 20k zip codes or call MySQL | <p>I have a list of about 20,000 zip codes that I need to check against. Should I store them in an PHP file as an array? How much memory would that occupy?</p>
<p>Or should I call MySQL every time to check against its database table to see if it exists? Which way is faster? I assume the first option should be faster? The connection to database alone may slow down the database call option quite significantly? I'm just a bit concerned about that memory problem if I do it by including PHP file on every call.</p>
| <php><mysql> | 2016-08-17 23:23:27 | LQ_CLOSE |
39,008,080 | my html form doesn't work with my php code | if i make insert_teacher('bla bla','bla bla','dqsd') in php file , but when i want to make it with html form it doesn't show me anything, and nothing inserted in my db
====
if i make insert_teacher('bla bla','bla bla','dqsd') in php file , but when i want to make it with html form it doesn't show me anything, and nothing inserted in my db
===
if i make insert_teacher('bla bla','bla bla','dqsd') in php file , but when i want to make it with html form it doesn't show me anything, and nothing inserted in my db
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<?php
include_once("resources/functions.php");
echo 1;
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$exp=$_POST['exp'];
$sub=$_POST['sub'];
$insert=insert_teacher($name,$exp,'dqsd');// return 1 or 0
echo $insert;
}
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<header>
<h1>City Gallery</h1>
</header>
<ul class="sidenav">
<li><a href="index.php">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a class="active" href="setup_teachers.php">Teachers Section</a></li>
</ul>
<div class="content">
<h3 class="warning"><?php if(isset($b)) echo $b; ?></h3>
<h3>Adding teachers information</h3>
<div>
<form action="" method="POST" >
<label for="fname">FullName</label>
<input type="text" id="fname" name="name">
<label for="lname">Experience</label>
<input type="text" id="lname" name="exp">
<label for="subject">Subject</label>
<select id="country" name="sub">
<option value="physics">physique</option>
<option value="maths">mathematique</option>
<option value="english">Anglais</option>
</select>
<input type="submit">
</form>
</div>
</div>
</body>
</html>
<!-- end snippet -->
| <javascript><php><jquery><html><css> | 2016-08-18 00:10:14 | LQ_EDIT |
39,008,682 | Can you lock notepad files? | <p>I am currently working on a little (quite bad) batch file password protected folder. To increase the security of my password and files what can I do to somehow make the file "un-viewable" to others?</p>
| <batch-file><notepad++><notepad> | 2016-08-18 01:38:33 | LQ_CLOSE |
39,010,267 | Is there any coding standards needs to be followed before minifying the javascript file? | I have a set of java script file which are using in my project. I want to minify all these java script. I am able to minify also. But i want want to know how this minify is happening & to minify any java script file the source code should follow any coding standard ? | <javascript><minify> | 2016-08-18 04:56:26 | LQ_EDIT |
39,012,320 | Can you make a feature that allows users to choose color C# (Console) | <p>Any ideas? I have a way but that would only change from downwards, and the menu is in the top.</p>
| <c#><colors><console> | 2016-08-18 07:31:10 | LQ_CLOSE |
39,012,786 | How to write string to on pdf? | Δ± want to string write to pdf file .But my code dont work.
//iTextSharp.text.Document d = new iTextSharp.text.Document();
//string dosya = (@"C:\Deneme.pdf");
//PdfWriter.GetInstance(d, new System.IO.FileStream(dosya, System.IO.FileMode.Create));
//d.AddSubject(text); | <c#><itext> | 2016-08-18 07:59:53 | LQ_EDIT |
39,013,320 | C++ - Convert Hex to DIN-Code | so first of all, I wanted to thank this Community. This Forum helped me a lot over years. Now it was time to register. So I need help.
I want convert a HEX-Code to a DIN-Code. The calculation is in the picture below.
The Hex-Code gets converted to Binary-Code. After that, it will get reversed bytewise and converted to DEC halfbyte-wise.
I have problems here. Eventhough I would have done a solution to this, it still would be really inefficent. So please support me. Maybe you can give me hints, on which functions too look at.
Thank you so much!
[Image - HEX to DIN][1]
[1]: http://i.stack.imgur.com/azUTp.jpg | <c++> | 2016-08-18 08:27:30 | LQ_EDIT |
39,013,618 | parent parent children children etc | Im trying to target a div outside of my Jquery button element. The way I'm doing it right now is
$(this).parent().parent().parent().parent().parent().parent().parent().children(":nth-child(3)").children().children().children(":nth-child(4)");
There must be and easier way? The element has a class but there are more identical elements I also need to adjust individually.
Thanks. | <jquery><html><this><parent><children> | 2016-08-18 08:43:25 | LQ_EDIT |
39,015,097 | Convert Json from MVC controller to Array in Jquery | I have a controller in MVC, and return Json like below:
public JsonResult getData()
{
var data = new[]{
new
{
x = 10,
y = 20,
name = "Jim",
},
new
{
x = 11,
y = 21,
name = "Tom",
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
And I have ajax request like below:
$.ajax({
type: "GET",
url: "https://localhost:44361/home/getdata",
dataType: "json",
success: function (result) {
return result;
},
error: function (response) {
return "faut";
}
});
I want to convert the json result to below Array
var arr = [
['x','y','name'],
[10,20,'Jim'],
[11,21,'Tom']
];
Any help would be appreciated.
| <javascript><jquery><arrays><json> | 2016-08-18 09:51:53 | LQ_EDIT |
39,015,500 | loop for print number 1 to 50 no print 10 and 20 and 30 and 40 and 50 | <p>I want the for loop print number 1 to 50, but without this number (10,20,30,40,50)</p>
<p>For example</p>
<p>1
2
3
4
5
6
7
8
9
11
12
13
14
15
16
17
18
19
21
22
.
.
.
.
.
99</p>
<p>Thanks</p>
| <loops><for-loop> | 2016-08-18 10:11:20 | LQ_CLOSE |
39,015,990 | Decentralized Chat Communication Protocl | I am designing a chat application in which there is no central server or db handling all the incoming and outgoing messages. It will be entirely decentralized.
A sum up of my project and its requirements
- Each user will communicate via android phone to a particular `node` allotted to them. This node will then communicate directly with the `node` belonging to the user he wishes to message
- Chat messages will be communicated between `nodes` via a `p2p` protocol forked from one of the libraries used for `Ethereum`
- The chat will have a limited number of users, 1500-2500
- Mapping the nodes to the users will be done via DHT and is not an issue
- I want to depend as little as possible on GCM
- The server will be written entirely in Node js. I have read extensively on XMPP, socketio and websockets but am unable to come to a conclusion on what to use. Keeping in mind that the code I write will be deployed across multiple `nodes` i.e. servers
- And of course, the app will have a backround server running and will need to show notifications for new messages when the app is in the back ground or not running at all
- A quick deployment is the least important factor for me. I am just looking for the most powerful and customizable end product
- I would like to stick with nodejs for the server
Is the primary advantage of XMPP over websockets that in XMPP a lot of the features needed for chat is out-of-the-box? Or is there more to it?
I have a list of libraries obtained from various stack questions and seen examples for xmpp and websocket implementations.
An increase in delay of a 1-2 seconds is NOT a problem in my case, but battery conversation is important.
[This link][1] suggests battery consumption with websockets is not a problem.
[1]: http://stackoverflow.com/questions/19033390/nodejs-socketio-android-battery-issue | <android><node.js><websocket><xmpp><chat> | 2016-08-18 10:35:33 | LQ_EDIT |
39,016,057 | Retrieving xml nodes in c# using linq | i have xml like
<century>
<question>What is silvia</question>
<answer>silvia is artificial intelligence</answer>
<question>What is your name</question>
<answer>my name is RAMESH</answer>
</century>
ihave multiple questions and answers.How to retrieve answer based on question using linq ?
Thanks advance | <c#><linq><linq-to-xml> | 2016-08-18 10:38:49 | LQ_EDIT |
39,016,070 | r: convert a string to date | <p>I have a string like that:</p>
<pre><code>201601
201603
201604
201606
201501
</code></pre>
<p>And I'd like to convert to Date, like so:</p>
<pre><code>2016-01
2016-03
2016-04
2016-06
2015-01
</code></pre>
<p>I have tried:<code>df$month_key=as.Date(df$month_key,format="YYYYmm")</code>
But it asks for the origin, which we don't need to care about.
Is there a way to do that, or maybe add a dash between character 4 and 5 in the whole column?
Thanks</p>
| <r><as.date> | 2016-08-18 10:39:55 | LQ_CLOSE |
39,016,131 | parse json by empty property | Am getting set of JSON objects as below in my ajax response
{
"id": 2,
"name": "An ice sculpture",
"price": 12.50,
"tags": ["cold", "ice"],
"dimensions": {
"length": 7.0,
"width": 12.0,
"height": 9.5
},
"warehouseLocation": {
"latitude": -78.75,
"longitude": 20.4
}
},
{
"id": 3,
"name": "A blue mouse",
"price": 25.50,
"dimensions": {
"length": 3.1,
"width": 1.0,
"height": 1.0
},
"warehouseLocation": {
"latitude": 54.4,
"longitude": -32.7
}
}
{
"id": 3,
"name": "A blue mouse",
"price": 25.50,
"dimensions": {
"length": 3.1,
"width": 1.0,
"height": 1.0
},
"warehouseLocation": ""
}
i want to parse these objects by `warehouseLocation` which means i need only json objects of non `warehouseLocation`empty | <javascript><jquery> | 2016-08-18 10:42:36 | LQ_EDIT |
39,016,905 | why String is not convertible to datetime? | I am passing 2 dates to store procedure but conversion throws error 'String not convertible to datetime'
txtFromDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
txtToDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
System.Data.DataTable dt = RejFiles.RejectedFiles(Convert.ToDateTime(txtFromDate.Text.Trim()), Convert.ToDateTime(txtToDate.Text.Trim()), user.OfficeID, user.Type_ID);
SP:
ALTER PROCEDURE [dbo].[usp_RejectedFiles]
(
@FromDate SMALLDATETIME,
@ToDate SMALLDATETIME,
@OfficeID INT=0,
@Type INT=0
)
and db stores the dates in particular table like this:
2014-03-01 00:00:00
| <c#><sql-server><tsql><c#-4.0><ado.net> | 2016-08-18 11:21:07 | LQ_EDIT |
39,017,107 | How to add two scanner strings together? in 'if' statement | <p>I'm new to Java and I'm trying to add two strings of data together from a scanner object. </p>
<p>I'm wanting to say </p>
<pre><code>if(age.equals("child")) AND sex.equals("male")) THEN System.out.println etc;
</code></pre>
<p>This code below is all I have so far. I also have a code: sex.equals("male")</p>
<pre><code>if(age.equals("child")){
System.out.println("1. Male child shirts are on the 5th floor");
System.out.println("2. Male child trousers are on the 6th floor");
System.out.println("3. Male child shoes are on the 6th floor");
}
</code></pre>
<p>I hope this isn't too confusing. I'm new to learning Java and only just learning the terminology. </p>
<p>Thanks</p>
| <java><if-statement> | 2016-08-18 11:31:36 | LQ_CLOSE |
39,017,852 | why my jquery toggle is not working | **Here why my toggle is not working**
<script>
$(document).ready(function () {
$("#tab").hide()
$("#btn1").click(function () {
$("#tab").toggle();
}) })
</script>
**Html Code**
<div>
<table>
<tr>
<th>
<b>Employee Name</b>
</th>
</tr>
<tr ng-repeat="Emp in John">
<td>
<input type="button" id="btn1" value="click" />
{{Emp.Name}}
<table id="tab">
<tr>
<th>
<b>OrderId</b>
</th>
</tr>
<tr ng-repeat="Joy in Emp.order">
<td>
{{Joy.OrderId}}
</td>
</tr>
</table>
</td>
</tr>
</table>
</div> | <jquery><html><angularjs> | 2016-08-18 12:08:44 | LQ_EDIT |
39,018,327 | Batch file that compare prefix | im really lost now..
--( FOLDER )
RAW_123432542_343.text
231453254_213.text
RAW_324324_32432423.text
32432423_4543.text
that is a sample files inside the folder
what i want is.. to raname all the files that doesn't have RAW_ prefix
the folder have thousand of file inside
| <batch-file><prefix><filecompare> | 2016-08-18 12:32:05 | LQ_EDIT |
39,018,504 | Parsing SQL into a hierachial result to analyze it | <p>Is there any library (prefferably in Python) which can parse SQL queries (the PostgreSQL kind), and give me a structured representation of them? There is <a href="https://github.com/andialbrecht/sqlparse" rel="nofollow">sqlparse</a>, but that doesn't allow me to easily figure out (say) the table that a query is using. I only need support for <code>SELECT</code> queries, but some of them can be quite complex.</p>
| <python><sql><postgresql><parsing> | 2016-08-18 12:40:05 | LQ_CLOSE |
39,018,742 | Creating hierarchy of methods in python class | I have class with hundreds of methods
I want create hierarchy of them that will let easy find method.
For example
class MyClass:
def SpectrumFrequencyStart()...
def SpectrumFrequencyStop()...
def SpectrumFrequencyCenter()...
def SignalAmplitudedBm()...
I want that call will:
`
MyClassObject.Spectrum.Frequency.Start()
MyClassObject.Spectrum.Frequency.Stop()
MyClassObject.Signal.Amplitude.dBm()
`
Thanks, Nadav
| <python> | 2016-08-18 12:50:48 | LQ_EDIT |
39,019,026 | Bootstrap nav bar with home icon issue | <p>i want to display home icon on bootstrap nav bar. i follow this link <a href="http://www.tutorialrepublic.com/codelab.php?topic=bootstrap&file=pills-nav-with-icons" rel="nofollow">http://www.tutorialrepublic.com/codelab.php?topic=bootstrap&file=pills-nav-with-icons</a></p>
<p>my html looks like</p>
<pre><code> <nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">
<a href="#">
<span class="glyphicon glyphicon-home"></span>
</a>
</li>
<li><a href="#">Home</a></li>
<li><a href="#">All Parts</a></li>
</ul>
</div>
</div>
</nav>
</code></pre>
<p>but still no luck. my home icon does not look good. jsfiddle is <a href="https://jsfiddle.net/0gjw5rzg/1/" rel="nofollow">https://jsfiddle.net/0gjw5rzg/1/</a></p>
| <css><twitter-bootstrap> | 2016-08-18 13:04:34 | LQ_CLOSE |
39,019,520 | deleting elements from array containing specific string keywords | <p>i have an array <strong>$link</strong> which contains some links inside it and i wanna delete all the links which are from sites present in <strong>$Blocklinks</strong> </p>
<pre><code> $links=array(
'http://ckfht.ca/sultan/files/2016/',
'http://dl1.uploadplus.net/dl2/2016/Sultan.2016/',
'http://www.google.com',
'http://subindomovie.xyz/film/indexof-sultan-720p'
'http://subindomovie.xyz/film/sultan-720-p'
'http://www.liveaccountbook.com/sultan/'
);
$Blocklinks=array(
'subindomovie.xyz',
'www.liveaccountbook.com'
);
/* remove urls containing link from $Blocklinks .. What should i do here??*/
$links=deletelinks($links,$Blocklinks);
/* output */
print_r($links);
output I want
------
Array
(
[0] => http://ckfht.ca/sultan/files/2016/
[1] => http://dl1.uploadplus.net/dl2/2016/Sultan.2016/
[2] => http://www.google.com
)
</code></pre>
| <php><arrays><regex><preg-replace> | 2016-08-18 13:29:42 | LQ_CLOSE |
39,020,252 | Add label text on table view cell | <p>How can i convert labels to integers and sum all of them up </p>
<pre><code> var totalCount:Int?
if let number = Int(price.text!) {
let myNumber = NSNumber(integer:number)
totalCount = totalCount! + myNumber.integerValue
print(totalCount)
} else {
print("'\(price.text)' did not convert to an Int")
}
</code></pre>
<p>here is my code it is not working</p>
| <ios><swift><uitableview><uilabel><tableviewcell> | 2016-08-18 14:01:57 | LQ_CLOSE |
39,020,603 | Mean for every columm of a matrix in R | How,can I get the mean of each column, each column contain multiple value, and there are 1000 of column. I dont want to use loop for efficiency reason.
For example data look like
col1 col2 .........coln
v1 c(10,11,12....) c(12,11,9....) c(12,11,9....)
v2 c(1,1,1,1,1,1...) c(1,1,1,1,1,1...) c(1,1,1,1,1,1...)
v3 c(0 ,0,1,2,3,..) c(0 ,0,2,2,2,3,..) c(0 ,0,2,2,2,3,..)
v4 c(date1,dat2,....) c(date1,dat2,....) c(date1,dat2,....)
I want to calculate the mean for V1 row for every column.
Thanks | <r><dataframe><statistics> | 2016-08-18 14:18:34 | LQ_EDIT |
39,022,779 | count the no. of employee group by department and fill the counting in respecting experience column | I have two tables employee and department,Employee table schema(Eid,Ename,DOJ,Sal,Dept ID) and Department schema(Dept id,Dname).So what i want in output is count the no. of employee by each department and according to experience.
O/P->
dept 0-5yrs 5-10yrs 10-15yrs above15yrs
HR 4 9
Account 2 3 1
like this.. | <sql><sql-server><database> | 2016-08-18 16:00:16 | LQ_EDIT |
39,025,335 | Show page by variable ?page= and some help needed? | <p>Hi m i want to display some page via the variable ?page= its giving error
Parse error: syntax error, unexpected '/' in C:\AppServ\www\index.php on line 11</p>
<pre><code><?php
include 'assets/config.php';
$page = $_GET["page"];
if ($page == "script") {
include("/pages/script.php");
}
if ($page == "how") {
include(/pages/"how.php");
?>
</code></pre>
<p>Please i need help on that and also</p>
<p>i want to redirect urls via a new variable ?go= page on my website my code Please customize it .... </p>
<pre><code>*<?php
include '/assets/config.php';
$goto = $_SERVER['QUERY_STRING'];
$RedirectTo = "$goto";
header("Location: $RedirectTo");
exit;
?>*
</code></pre>
<p>Thanks </p>
| <php> | 2016-08-18 18:39:35 | LQ_CLOSE |
39,025,539 | Passing an array as an argument in a function | <p>I have initialised an array of integers which i later call in a function. I noticed that the values have changed. What can i do to stop that from happening?</p>
<pre><code>void check(int arr[5][6]){
printf("%s", arr[0][0]);
}
int main(){
int arr[5][6];
arr[0][0] = 5;
check(arr);
}
</code></pre>
| <c><arrays> | 2016-08-18 18:51:16 | LQ_CLOSE |
39,025,704 | What system to use for auto login via URL | <p>I have limited skill with PHP and need to accomplish the discouraged/low security practice of passing credentials by URL-- which for my particular purpose is a perfectly good, relevant solution. </p>
<p>I have an area of my site with trivial/non-sensitive content that, nevertheless, I want to have hidden and control access to. However, I want them to <strong>not need to log in</strong> nor deal with credentials. So I'm thinking the group's credentials are passed by URL to auto login any user, allowing them to navigate around that area of the site. This content isn't sensitive and these aren't user accounts/pws/data, but group ones I set up.</p>
<p>I should be able to distribute links to any of the pages like
<a href="http://example.com/home.php?&username=GROUPNAME&password=PW123" rel="nofollow">http://example.com/home.php?&username=GROUPNAME&password=PW123</a>
and allow them to nav all of the protected pages without getting logged out.</p>
<p><strong>More context</strong>: Offline a group would request an account for that area/those pages (a group account I create myself and later could delete/modify preventing access). I don't want people without a membership to have access to the content, and I'm not worried about the people sharing links outside of their group.</p>
<p>Should I go with something like User Frosting/User Cake? Or will it be overkill and create challenges with passing the credentials with GET/POST? Not sure if this method doesn't work if passwords get encrypted.</p>
<p>Or should a follow some low-security tutorial to set up a login system and another for using GET/POST to pass the credentials? </p>
| <php><url><login><parameters> | 2016-08-18 19:01:56 | LQ_CLOSE |
39,025,740 | MongoDB geospatial: how to find if a point is within range from any other point | <p>I'm struggling with completing this query but maybe I'm using the wrong approach. Right now I'm doing it like this:</p>
<pre><code>db.cells.find(
{
loc: {
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ 31.0, 31.0 ]
},
$minDistance: 0,
$maxDistance: $range
}
}
}
)
</code></pre>
<p>Here <code>$range</code> should be a field of my document but in a previous answer they told me that there is no option to do that in MongoDB.</p>
<p>So I would like to retrieve all the documents where the field <code>loc</code> is a point within distance inferior to field <code>range</code>. Is it possible to do it with a single query? I can restructure the document format if necessary.</p>
<p>Thanks</p>
| <mongodb><geospatial> | 2016-08-18 19:04:53 | LQ_CLOSE |
39,025,793 | javascript variable's weird behaviour | <p>Case 1 - If I console.log(variable) before the variable declaration I get undefined. eg;</p>
<pre><code> // code
console.log(a);
var a ;
// output
undefined
</code></pre>
<p>Case 2 - If I console.log(variable) without variable declaration I get Uncaught ReferenceError: variable is not defined. </p>
<pre><code>// code
console.log(a);
// output
Uncaught ReferenceError: a is not defined
</code></pre>
<p>But incase of functions we can call a function before or after function definition it never give any issue. eg;</p>
<pre><code> console.log(example());
function example(){
return 'test done';
}
console.log(example());
// output without any issue
</code></pre>
<p>Now My question is, what is the difference between <strong>undefined</strong> and <strong>not defined</strong>.</p>
| <javascript> | 2016-08-18 19:07:27 | LQ_CLOSE |
39,026,741 | Best software to view OLAP Cube | <p>I connected to an analysis server using (32-bit) Ms Excel, but it crashed since the amount of data was big.
Then I used SQL Server Management Studio, even that did not worked for me since it seems like SSMS is an administrator tool and you need to have administrator rights for the DB you like to view (Which I do not and cannot have).
Please suggest me a software that can allow me to work with the large amount of data (without crashing) coming from an OLAP server?</p>
| <server><olap><analysis><cube> | 2016-08-18 20:13:16 | LQ_CLOSE |
39,027,437 | Google maps work locally but not online. | <p>I cannot find out why Google Map works perfectly local but not online.
Check it: www.giacomobartoli.xyz at the end of the page.</p>
<p>Thanks in advance</p>
| <javascript><google-maps> | 2016-08-18 21:00:38 | LQ_CLOSE |
39,028,285 | not able to compile code with "std::pair" | <p>I try to study and modify this program "<a href="https://github.com/PetterS/monte-carlo-tree-search.git" rel="nofollow">https://github.com/PetterS/monte-carlo-tree-search.git</a>" like this.</p>
<pre><code>diff --git a/games/connect_four.h b/games/connect_four.h
index a575217..52f59cf 100644
--- a/games/connect_four.h
+++ b/games/connect_four.h
@@ -3,6 +3,7 @@
#include <algorithm>
#include <iostream>
+#include <utility>
using namespace std;
#include <mcts.h>
@@ -15,6 +16,9 @@ public:
static const char player_markers[3];
+ typedef std::pair <int, int> MyMove;
+ static const MyMove my_no_move (-1, -1);
+
ConnectFourState(int num_rows_ = 6, int num_cols_ = 7)
: player_to_move(1),
num_rows(num_rows_),
</code></pre>
<p>i.e., introduce a new type "MyMove" with std::pair and a constant. This code does not compile. If I remove those lines, it compiles with no problem.</p>
<pre><code>.../monte-carlo-tree-search/games/connect_four.h:20:41: error: expected identifier before β-β token
.../monte-carlo-tree-search/games/connect_four.h:20:41: error: expected β,β or β...β before β-β token
</code></pre>
<p>However, on the same machine, I test the same part of code which compiles.</p>
<pre><code>#include <utility>
int main ()
{
typedef std::pair <int, int> MyMove;
static const MyMove my_no_move (-1, -1);
return 0;
}
$ g++ temp.C -std=c++0x
$
</code></pre>
<p>Why? I admit the compiler on my machine is not updated which does not fully support c++11, but how come same lines of code have different result. </p>
| <c++><c++11> | 2016-08-18 22:12:19 | LQ_CLOSE |
39,029,459 | Why is my JavaScript code refusing to run on my website? | <p>The following is what my HTML document looks like:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="scripts/homepage-script.js"></script>
</head>
<body>
<div id="how-it-works">
<p>How It Works</p>
<img src="some-imageurl">
<div id="steps">
<p>Step 1</p>
<p>Step 2</p>
<p>Step 3</p>
</div>
</code></pre>
<p></p>
<p>And here is my script:</p>
<pre><code>$('#steps > p').on('click' , function(){
$('steps > p').css('background', 'yellow');
});β
</code></pre>
<p>Why is my script not running on my website?</p>
| <javascript><jquery> | 2016-08-19 00:35:04 | LQ_CLOSE |
39,030,194 | Copy Two-dimensional arrays in Javascript |
**
Hello everyone, I met a problem when coding in Javascript, and I'm seeking for a solution for "What should I do with a Two Dimensional Array if I want copy each line of them and make them a new Two-Dim array?" Thx a lot if any one can help~ Here is the format of this two-Dim array:
------------------------------------------------------------------------
**
------------------------------------------------------------------------
========================================================================
> {"localTrain":"T7", "TC":"2", "TimeSheet":[
> ["01","London","BXP","T7","1632","1640"],
> ["02","Shanghai","QWE","T7","1200","1240"],
> ["03","LosAngeles","DFG","T7","1300","1340"],
> ["04","NewDelhi","VGH","T7","1400","1440"],
> ["05","Sydney","SAW","T7","1500","1540"],
> ["06","Tokyo","SAT","T7","1600","1640"],
> ["07","Seoul","BBT","T7","1700","1740"],
> ["08","CapeTown","OOP","T7","1800","1840"],] }
And they should be look like this:
> {"localTrain":"T7", "TC":"2", "TimeSheet":[
> ["01","London","BXP","T7","1632","1640"],
> ["01","London","BXP","T7","1632","1640"],
> ["02","Shanghai","QWE","T7","1200","1240"],
> ["02","Shanghai","QWE","T7","1200","1240"],
> ["03","LosAngeles","DFG","T7","1300","1340"],
> ["03","LosAngeles","DFG","T7","1300","1340"],
> ["04","NewDelhi","VGH","T7","1400","1440"],
> ["04","NewDelhi","VGH","T7","1400","1440"],
> ["05","Sydney","SAW","T7","1500","1540"],
> ["04","NewDelhi","VGH","T7","1400","1440"],
> ["06","Tokyo","SAT","T7","1600","1640"],
> ["06","Tokyo","SAT","T7","1600","1640"],
> ["07","Seoul","BBT","T7","1700","1740"],
> ["07","Seoul","BBT","T7","1700","1740"],
> ["08","CapeTown","OOP","T7","1800","1840"],
> ["08","CapeTown","OOP","T7","1800","1840"],] } | <javascript><arrays> | 2016-08-19 02:23:16 | LQ_EDIT |
39,032,067 | When click "clear data", database is deleting. How i solve this | I want to don't delete database of application when click the "clear data" button. How i solve my problem..
I searched but could not find something.
Please help, thanks.. | <android><sqlite><android-sqlite> | 2016-08-19 06:02:05 | LQ_EDIT |
39,032,564 | Recursively check if all digit's of a number are different | How can I check recursively if all the digits of an integer are different numbers in C++ | <c++><recursion> | 2016-08-19 06:37:54 | LQ_EDIT |
39,032,938 | How many IN, OUT and IN OUT parameters can be used in pl sql function and procedure? | <p>I want to know how many IN, OUT and IN OUT parameters can be used in a function and how many in a procedure?</p>
| <oracle><plsql> | 2016-08-19 07:02:06 | LQ_CLOSE |
39,034,394 | how to add image from iPhone gallery to an array IOS | As i am very much new to iOS development,i am trying to add an uiimage from image gallery to an array.But when i try to use the array to add image to uiimageview it shows me an error [UIImage stringByDeletingPathExtension]: unrecognized selector sent to instance 0x7fefd3ea02f0. | <ios><objective-c><uiimageview><uiimage> | 2016-08-19 08:24:44 | LQ_EDIT |
39,034,969 | Notification DropBox Api Android | I 'm trying to implements notifications for an android Application : i am using dropbox api : https://www.dropbox.com/developers/apps.
The point is i'm a newbie, i've never done something like that, i have read a bit about that i should use a JSON request ? I have not found any tutorial related to notification with dropbox api for android.
Can someone help me ? Which steps should i follow etc ??
Any help is welcomed.
Thank you very much.
| <android><notifications><dropbox-api> | 2016-08-19 08:58:12 | LQ_EDIT |
39,035,236 | Genrate random color IOS objective c? | Genrate random color
float red = (float)(arc4random() % 255)/255.0;
float blu = (float)(arc4random() % 255)/255.0;
float green = (float)(arc4random() % 255)/255.0;
view.backgroundColor = [UIColor colorWithRed:red green:green blue:blu alpha:1.0];
| <ios><objective-c><uicolor> | 2016-08-19 09:11:09 | LQ_EDIT |
39,035,525 | grouping the batch in sql server | have a scenario wherein I have
Id|rank| date
1 | 7 |07/08/2015
1 | 7 |09/08/2015
1 | 8 |16/08/2015
1 | 8 |17/08/2015
1 | 7 |19/08/2015
1 | 7 |15/08/2015
2 | 7 |01/08/2015
2 | 7 |02/08/2015
2 | 8 |16/08/2015
2 | 8 |17/08/2015
2 | 7 |26/08/2015
2 | 7 |28/08/2015
My desired solution is
1 | 7 |07/08/2015 |1
1 | 7 |09/08/2015 |1
1 | 8 |16/08/2015 |2
1 | 8 |17/08/2015 |2
1 | 7 |19/08/2015 |3
1 | 7 |15/08/2015 |3
2 | 7 |01/08/2015 |4
2 | 7 |02/08/2015 |4
2 | 8 |16/08/2015 |5
2 | 8 |17/08/2015 |5
2 | 7 |26/08/2015 |6
2 | 7 |28/08/2015 |6
i.e for each block of id and rank I want to add the new column and updated the same. | <sql><sql-server><sql-server-2008> | 2016-08-19 09:25:01 | LQ_EDIT |
39,035,565 | NULL help please | I am currently using SQL Server 2008R2.
I am using this script:
SELECT a.productname, a.orderdate, a.workarea
FROM database1table1 AS a
WHERE a.orderdate >='2016/08/01'
Which gives the output:
PRODUCT NAME ORDER DATE WORKAREA
x 2016/08/07 NULL
y 2016/08/09 HOLDING
z 2016/08/10 ACTION
a 2016/08/12 ACTION
My problem arises when I amend the above script to read,
...
WHERE a.orderdate >='2016/08/01'
**AND a.workarea NOT IN ('HOLDING')**
When I do this, not only does it remove 'HOLDING', but it also removes the NULL rows as well, which I definitely do not want.
Please can you suggest an amendment to the script to prevent the NULLS being removed - I only want to see the value 'HOLDING' taken out.
With many thanks!
| <tsql><sql-server-2008-r2> | 2016-08-19 09:27:15 | LQ_EDIT |
39,037,015 | How to generate FB Page access token | <p>I have a Page with ID: 1620295414849355
I need to generate Page Access Token.
Need Page access token to post content on FB page from my website.</p>
| <php><facebook> | 2016-08-19 10:42:39 | LQ_CLOSE |
39,037,041 | Codeigniter loading a view into a view | I need to load a view into a view within Codeigniter, but cant seem to get it to work.
I have a loop.
I need to place that loop within multiple views (same data different pages)
So I have the loop by itself, as a view, to receive the array from the controller and display the data.
But I cant seem to load multiple views from a controller:
SO, I've tried many things, but according to the docs I can do something like this:
Controller:
$data['due_check_data'] = $combined_checks;
// gather data for view
$view_data = array(
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests'
);
$this->load->view('checks/due_checks',$view_data);
$this->load->view('checks/include/due_checks_table',$data, TRUE);
So then how do i call the loop in the view?
I've tried this:
<?=$due_check_data?>
And
<? echo $due_check_data; ?>
But I'm just getting this error, saying the variable is empty?
Message: Undefined variable: due_check_data | <php><codeigniter> | 2016-08-19 10:43:36 | LQ_EDIT |
39,038,996 | @RestController @ResponseBody @RequestBody cant ready Model | We has "web service" rest with this
O problem consist in ready object with model, when ready attribute for attribute can ready,
- Project with spring 4.2.4-RELEASE
- User jackson 2.8.0
same stacktrace wrong, same call method create
<pre><code>
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'event': was expecting ('true', 'false' or 'null')
at [Source: java.io.ByteArrayInputStream@4efc31a9; line: 1, column: 7]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'event': was expecting ('true', 'false' or 'null')
at [Source: java.io.ByteArrayInputStream@4efc31a9; line: 1, column: 7]
</code></pre>
how configure can read a model "Invoice"?
one stacktrace
| <java><json><spring> | 2016-08-19 12:24:35 | LQ_EDIT |
39,039,123 | Python error in my program opening window | I'm getting an error trying to open a window in python
I'm using tkinter so the code looks a bit like this
import tikneter
Window = Tk()
Window.create_rectangle(0, 0, 100, 100) # border around window
| <python><tkinter> | 2016-08-19 12:31:19 | LQ_EDIT |
39,039,625 | image not showing inside webpage, but works outside | <p>Please take a look at this URL </p>
<p><a href="http://www.viewpromocode.com/product/redmi-3s-prime-silver-32-gb-4/#" rel="nofollow">http://www.viewpromocode.com/product/redmi-3s-prime-silver-32-gb-4/</a></p>
<p>It has a broken image in it, but if you open the image in another tab, it work !! </p>
<p>why ?</p>
<p>I am using the following image compression script.
It is even generating correct thumbnails, but the it is loading inside the webpage.</p>
<p><a href="https://github.com/whizzzkid/phpimageresize" rel="nofollow">https://github.com/whizzzkid/phpimageresize</a></p>
| <php> | 2016-08-19 12:55:47 | LQ_CLOSE |
39,040,581 | creating login , using mysql server 5.7.14 and workbench 6.3 and c# window form application | i am trying to make a check (login) on the user which is entering into my application. i have made a database and table named 'mydb', 'employee' respectively. i have entered username and password into uname and pasword columns of table employee. what i want to do is that whether the username and password entered by user is valid or not? it means is it exists in table employee or not? if yes allow access and if not access denied.
for this purpose i have written following code in my c# window form application using visual studio 2013 ultimate.
try
{
string myconnection = "datasource=localhost; port=3306; username=root; password=shaban; ";
MySqlCommand selectcommand = new MySqlCommand(" slect * from mydb.employee where uname= "+this.username_txt.Text+" and pasword = "+this.pasword_txt.Text+"", myconn);
MySqlDataReader myreader;
myconn.Open();
myreader = selectcommand.ExecuteReader();
int count = 0;
while (myreader.Read())
{ count = count + 1; }
if (count == 1)
{ MessageBox.Show("username and pasword is correct"); }
else if (count > 1)
{ MessageBox.Show("Duplicate username and password...! Access Denied "); }
else
{ MessageBox.Show(" username and pasword not existing.. Try again" ); }
myconn.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
| <c#><mysql> | 2016-08-19 13:42:59 | LQ_EDIT |
39,040,582 | HTML/JAVASCRIPT Animation like on storj.io | <p>I found this site <a href="https://storj.io/" rel="nofollow">Storj.io</a>. I really like the design of the site and was looking at the header. There is a background-image and then on top of this there are those points that are moving. How can such a animation be achieved? Is this done with html5 and how or is JavaScript used?</p>
| <javascript><jquery><html> | 2016-08-19 13:43:00 | LQ_CLOSE |
39,040,929 | how to make a textbox show me double? | I am trying to get myself used to c#, currently I am using SharpDevelop for that Task, anyway, I have a simple question, lets say I want to have a TextBox that Shows me the outcome of a mathematical code as shown below, how do I get the TextBox to actually Show me types like double, int or other stuff? It always tells me it cant convert double to string or whatever, I am pretty noob so yeah.
void CmdWriteClick(object sender, EventArgs e)
{
double var = 8.40;
double start = 9.00;
double end = var + start;
textbox_end.Text = end;
}
I already tried to not use the .text but something like .value but didnt work, any help?
thanks | <c#><textbox><var> | 2016-08-19 13:58:31 | LQ_EDIT |
39,042,586 | How to remove one polyline of several with jquery.ui.map | <p>
I have two polylines on the gmap:<br />
Polyline 1 as 'route'<br />
Polyline 2 as 'other'<br />
i want to clear only one. How can i do that?<br />
I have tried with $('#map_canvas').gmap('clear', 'overlays > Polyline').route<br />
but it does not work<br />
</p> | <google-maps><jquery-gmap3> | 2016-08-19 15:18:33 | LQ_EDIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.