Examples On Programing Languages

How can I merge two MySQL tables?

How can I merge two MySQL tables that have the same structure? The primary keys of the two tables will clash, so I have take that into account....

I don't understand -Wl,-rpath -Wl,

For convenience I added the relevant manpages below. My (mis)understanding first: If I need to separate options with ,, that means that the second -Wl is not another option because it comes before , which means it is an argument to the -rpath optio...

gem install: Failed to build gem native extension (can't find header files)

I am using Fedora 14 and I have MySQL and MySQL server 5.1.42 installed and running. Now I tried to do this as root user: gem install mysql But I get this error: Building native extensions. This could take a while... ERROR: Error installing mys...

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

I have been getting a ClassNotFoundException with org.glassfish.jersey.servlet.ServletContainer but it peculiarly started last night when I tried to start/re-start my Tomcat server (v7) with Eclipse Juno. Not sure what is going on. What's bizarre i...

Using media breakpoints in Bootstrap 4-alpha

In Bootstrap 3 I use this: .something { padding: 5px; @media screen and (min-width: $screen-sm-min) { padding: 20px; } @media screen and (min-width: $screen-md-min) { padding: 40px; } } How can I do the same t...

fatal: early EOF fatal: index-pack failed

I have googled and found many solutions but none work for me. I am trying to clone from one machine by connecting to the remote server which is in the LAN network. Running this command from another machine cause error. But running the SAME clone com...

Get size of all tables in database

I have inherited a fairly large SQL Server database. It seems to take up more space than I would expect, given the data it contains. Is there an easy way to determine how much space on disk each table is consuming?...

VBA copy cells value and format

How can I amend the following code in order to copy not only the value but also the fonts style, e.g. bold or not bold. Thanks Private Sub CommandButton1_Click() Dim i As Integer Dim a As Integer a = 15 For i = 11 To 32 If Worksheets(1).Cells(i, 3...

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

Solution Guys... FYI i am using xampp to use phpmyadmin. and this error happens during the process of creating a database on localhost. Below is the code for config.inc file under phpmyadmin directory: <?php /* * This is needed for cookie base...

Clear screen in shell

Just a quick question: How do you clear the screen in shell? I've seen ways like: import os os.system('cls') This just opens the windows cmd, clears the screen and closes but I want the shell window to be cleared (PS: I don't know this helps, but ...

How can I force a hard reload in Chrome for Android

In Chrome for desktop I have options in the dev tools to disable cache completely when dev tools are opened and I have the options to manually do a hard reload when long clicking on the reload button (with dev tools open). Is there any such techniqu...

How big can a MySQL database get before performance starts to degrade

At what point does a MySQL database start to lose performance? Does physical database size matter? Do number of records matter? Is any performance degradation linear or exponential? I have what I believe to be a large database, with roughly 15M r...

Select element based on multiple classes

I have a style rule I want to apply to a tag when it has two classes. Is there any way to perform this without JavaScript? In other words: <li class="left ui-class-selector"> I want to apply my style rule only if the li has both .lef...

Reorder bars in geom_bar ggplot2 by value

I am trying to make a bar-plot where the plot is ordered from the miRNA with the highest value to the miRNA with the lowest. Why does my code not work? > head(corr.m) miRNA variable value 1 mmu-miR-532-3p pos 7 2 m...

What are naming conventions for MongoDB?

Is there a set of preferred naming conventions for MongoDB entitites such as databases, collections, field names? I was thinking along these lines: Databases: consist of the purpose (word in singular) and end with “db” – all lower case: imag...

Display Adobe pdf inside a div

I have a pdf file that the user has to see and click on the "I agree" button. How do you display a pdf inside a div?...

Importing the private-key/public-certificate pair in the Java KeyStore

I used the following steps to create a new Java keystore with a pair of private/public key to be used by a Java (internal) server with TLS. Please notice that the certificate is selfsigned: 1) Generate key with AES256 openssl genrsa -aes256 -out se...

How to calculate time elapsed in bash script?

I print the start and end time using date +"%T", which results in something like: 10:33:56 10:36:10 How could I calculate and print the difference between these two? I would like to get something like: 2m 14s ...

jquery ui Dialog: cannot call methods on dialog prior to initialization

I have an app on jquery 1.5 with dialogs worked fine. While I have a lot of .live handlers, I changed this to .on. For that, I have to update jquery (now 1.8.3 an jquerui 1.9.1). Now, I got: Error: cannot call methods on dialog prior to initializati...

get index of DataTable column with name

I have some code which sets the value of cells in a DataRow by column name i.e. row["ColumnName"] = someValue; I want to also set the value for this row in the column immediately to the right of the one found above. Clearly if I was getting the c...

How to hide the title bar for an Activity in XML with existing custom theme

I want to hide the titlebar for some of my activities. The problem is that I applied a style to all my activities, therefore I can't simply set the theme to @android:style/Theme.NoTitleBar. Using the NoTitleBar theme as a parent for my style would ...

No log4j2 configuration file found. Using default configuration: logging only errors to the console

$ java -Dlog4j.configuration=file:///path/to/your/log4j2.xml -jar /path/to/your/jar_file.jar Written to the console, you get ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. ...

How do you do relative time in Rails?

I'm writing a Rails application, but can't seem to find how to do relative time, i.e. if given a certain Time class, it can calculate "30 seconds ago" or "2 days ago" or if it's longer than a month "9/1/2008", etc....

How to change a package name in Eclipse?

In Eclipse I have a simple Java project that contains a package named (default package) and inside this package I have a class. I want to rename this package into something like: com.myCompany.executable I tried to select the (default package) --->...

Disable back button in react navigation

I'm using react native navigation (react-navigation) StackNavigator. it starts from the Login page throughout the whole lifecycle of the app. I don't want to have a back option, returning to the Login screen. Does anyone know how it can be hidden on...

Redirect stdout to a file in Python?

How do I redirect stdout to an arbitrary file in Python? When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the ...

Visual Studio 2015 is very slow

I just finished the installation and the whole IDE is super slow. It seems like it's making some kind of heavy CPU calls in the background where the whole IDE literally freezes and becomes unresponsive for about 2-3 seconds. I was not having this is...

How to bind a List to a ComboBox?

I want to connect a BindingSource to a list of class objects and then objects value to a ComboBox. Can anyone suggest how to do it? public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } pu...

ant build.xml file doesn't exist

After the installation of my ant in my windows 7 . In cmd i typed ant -v it's given the ant version but it says the following also. Buildfile: build.xml does not exist! Build failed What's the problem in the system. How i can rectify this issue? ...

Is there a difference between "==" and "is"?

My Google-fu has failed me. In Python, are the following two tests for equality equivalent? n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' Does this hold true for objects where you would be comparing instan...

Django Cookies, how can I set them?

I have a web site which shows different content based on a location the visitor chooses. e.g: User enters in 55812 as the zip. I know what city and area lat/long. that is and give them their content pertinent to that area. My question is how can I st...

How to create ls in windows command prompt?

I want to use ls in windows command prompt and make it run the dir command. How can I do that?...

Call PHP function from jQuery?

I have a PHP function on my site which takes a couple of seconds to complete. This holds the whole page up which I don't want. Would it be possible with jquery to call this PHP function after the page has loaded and display the results in a div? Als...

How to make two plots side-by-side using Python?

I found the following example on matplotlib: import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0.0, 5.0) x2 = np.linspace(0.0, 2.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) plt.subplot(2, 1, 1) plt....

XPath:: Get following Sibling

I have following HTML Structure: I am trying to build a robust method to extract second color digest element since there will be many of these tag within the DOM. <table> <tbody> <tr bgcolor="#AAAAAA"> <tr> <...

Convert a Python list with strings all to lowercase or uppercase

I have a python list variable that contains strings. Is there a python function that can convert all the strings in one pass to lowercase and vice versa, uppercase?...

for each loop in Objective-C for accessing NSMutable dictionary

I am finding some difficulty in accessing mutable dictionary keys and values in Objective-C. Suppose I have this: NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init]; I can set keys and values. Now, I just want to access each key and valu...

JavaScript Adding an ID attribute to another created Element

I have some code here that will do the following. The code creates an element "p" then I append it to a "div" in the HTML. I would like that "p" I just created have an unique identifier (ID) and set the name of the ID. So later on when the user wants...

Resize a large bitmap file to scaled output file on Android

I have a large bitmap (say 3888x2592) in a file. Now, I want to resize that bitmap to 800x533 and save it to another file. I normally would scale the bitmap by calling Bitmap.createBitmap method but it needs a source bitmap as the first argument, whi...

List names of all tables in a SQL Server 2012 schema

I have a schema in SQL Server 2012. Is there a command that I can run in SQL to get the names of all the tables in that schema that were populated by user? I know a similar query for MySQL SHOW TABLES; but this does not work with SQL Server....

Need to make a clickable <div> button

Kindly go through this link and notice the solution given by "thepeer": https://stackoverflow.com/a/3494108 I am having trouble understanding his solution. Let me illustrate with the example of a webpage that I am trying to build. I am using HTML5 t...

How to perform a mysqldump without a password prompt?

I would like to know the command to perform a mysqldump of a database without the prompt for the password. REASON: I would like to run a cron job, which takes a mysqldump of the database once everyday. Therefore, I won't be able to insert the passwo...

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

I'm getting the exception java.lang.ClassNotFoundException when I am trying to run my code, My Code try { Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/simple", ...

Running multiple commands in one line in shell

Say I have a file /templates/apple and I want to put it in two different places and then remove the original. So, /templates/apple will be copied to /templates/used AND /templates/inuse and then after that I’d like to remove the original. Is c...

Get latitude and longitude based on location name with Google Autocomplete API

I have a textbox in my page which gets a location name and button with text getLat&Long. Now on clicking my button I have to show an alert of latitude and longitude of the location in the textbox. Any suggestion?...

AngularJs .$setPristine to reset form

I been struggling to reset form once form is submitted. Someone posted this Here which I want to make it work but no success. Here is my My Code Example. $scope.form.$setPristine(); is not setting Pristine: {{user_form.$pristine}} to true. See examp...

Retrofit and GET using parameters

I am trying to send a request to the Google GeoCode API using Retrofit. The service interface looks like this: public interface FooService { @GET("/maps/api/geocode/json?address={zipcode}&sensor=false") void getPositionByZip(@Path("...

How do I round a double to two decimal places in Java?

This is what I did to round a double to 2 decimal places: amount = roundTwoDecimals(amount); public double roundTwoDecimals(double d) { DecimalFormat twoDForm = new DecimalFormat("#.##"); return Double.valueOf(twoDForm.format(d)); } This ...

ImportError: No module named 'MySQL'

I have downloaded the Connector/Python for MySQL successfully. I used the following code in Python's shell to test my connection: import mysql.connector I received the following error message: Traceback (most recent call last): File "<pyshel...

jQuery CSS Opacity

What's wrong? I want to change the opacity if #nav .drop is display:block; jQuery(document).ready(function(){ if (jQuery('#nav .drop').css('display') === 'block') { jQuery('#main').css('opacity') = '0.6'; } }); ...

Round to at most 2 decimal places (only if necessary)

I'd like to round at most 2 decimal places, but only if necessary. Input: 10 1.7777777 9.1 Output: 10 1.78 9.1 How can I do this in JavaScript? ...

PHP send mail to multiple email addresses

What code I should do change in this PHP script to send one email to more than 20 email addresses? <?php $email_to = "[email protected]"; // your email address $email_subject = "Contact Form Message"; // email subject line $thankyo...

Delete sql rows where IDs do not have a match from another table

I'm trying to delete orphan entries in a mysql table. I have 2 tables like this: Table files: | id | .... ------------ | 1 | .... | 2 | .... | 7 | .... | 9 | .... table blob: | fileid | .... ------------ | 1 | .... | 2 | .... | 3 | .... ...

How can I get the count of milliseconds since midnight for the current?

Note, I do NOT want millis from epoch. I want the number of milliseconds currently on the clock. So for example, I have this bit of code. Date date2 = new Date(); Long time2 = (long) (((((date2.getHours() * 60) + date2.getMinutes())* 60 ) + date2....

Java regex to extract text between tags

I have a file with some custom tags and I'd like to write a regular expression to extract the string between the tags. For example if my tag is: [customtag]String I want to extract[/customtag] How would I write a regular expression to extract onl...

package android.support.v4.app does not exist ; in Android studio 0.8

I've recently updated the android studio IDE to 0.8 to work with the new android L SDK. To start I imported a finished android project that receives no errors in the older version of android studio. In version 0.8 i lines such as import android.supp...

how do I check in bash whether a file was created more than x time ago?

I want to check in linux bash whether a file was created more than x time ago. let's say the file is called text.txt and the time is 2 hours. if [ what? ] then echo "old enough" fi ...

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

I have read the documentation on this and I think I understand. An AutoResetEvent resets when the code passes through event.WaitOne(), but a ManualResetEvent does not. Is this correct?...

Image style height and width not taken in outlook mails

I have a following dom structure in html content I am sending as email. <a href="http://content.mindmatrix.net/email/814xjqjmpj5r/b59tqx7tzz2x7" target="_new"> <span style='text-decoration:none;text-underline:none'> <img border=0 id=...

Head and tail in one line

Is there a pythonic way to unpack a list in the first element and the "tail" in a single command? For example: >> head, tail = **some_magic applied to** [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >> head 1 >>> tail [1, 2, 3, 5, 8, 13, ...

Make Div overlay ENTIRE page (not just viewport)?

So I have a problem that I think is quite common but I have yet to find a good solution for. I want to make an overlay div cover the ENTIRE page... NOT just the viewport. I don't understand why this is so hard to do... I've tried setting body, htm...

Make columns of equal width in <table>

How do I make columns of equal width in <table>? I am dynamically changing the number of columns. Today I have 13 columns. Tomorrow it will be raised to 16. I do not particularly want to recalculate....

How do I turn a python datetime into a string, with readable format date?

t = e['updated_parsed'] dt = datetime.datetime(t[0],t[1],t[2],t[3],t[4],t[5],t[6] print dt >>>2010-01-28 08:39:49.000003 How do I turn that into a string?: "January 28, 2010" ...

How to convert timestamp to datetime in MySQL?

How to convert 1300464000 to 2011-03-18 16:00:00 in MySQL?...

How do I pass variables and data from PHP to JavaScript?

I have a variable in PHP, and I need its value in my JavaScript code. How can I get my variable from PHP to JavaScript? I have code that looks like this: <?php ... $val = $myService->getValue(); // Makes an API and database call ?&g...

Call external javascript functions from java code

By using Java Scripting API, I am able to execute JavaScript within Java. However, can someone please explain what I would need to add to this code in order to be able to call on functions that are in C:/Scripts/Jsfunctions.js import javax.script.*;...

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

Ran the new Lint tool against my code. It came up with a lot of good suggestions, but this one I cannot understand. This tag and its children can be replaced by one and a compound drawable Issue: Checks whether the current node can be replaced by ...

Difference between \n and \r?

What’s the difference between \n (newline) and \r (carriage return)? In particular, are there any practical differences between \n and \r? Are there places where one should be used instead of the other?...

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I am deploying sql express with my application. I will like that database engine to accept remote connections. I know how to configure that manual by launching the sql server configuration manager, enabling tcp/ip connections, specifying the ports et...

XML Serialize generic list of serializable objects

Can I serialize a generic list of serializable objects without having to specify their type. Something like the intention behind the broken code below: List<ISerializable> serializableList = new List<ISerializable>(); XmlSerializer xml...

Getting multiple selected checkbox values in a string in javascript and PHP

I have location name and location Id in database table. Using foreach loop i'm printing the values in checkbox in PHP. I have a submit button which triggers a javascript. I want the user selected all checkbox values separated by comma, in a javascrip...

Which is the fastest algorithm to find prime numbers?

Which is the fastest algorithm to find out prime numbers using C++? I have used sieve's algorithm but I still want it to be faster!...

How to set a Javascript object values dynamically?

It's difficult to explain the case by words, let me give an example: var myObj = { 'name': 'Umut', 'age' : 34 }; var prop = 'name'; var value = 'Onur'; myObj[name] = value; // This does not work eval('myObj.' + name) = value; //Bad codi...

get all characters to right of last dash

I have the following: string test = "9586-202-10072" How would I get all characters to the right of the final - so 10072. The number of characters is always different to the right of the last dash. How can this be done?...

Spring @Transactional read-only propagation

I'm experimenting with using the command pattern to allow my web layer to work with Hibernate entities within the context of a single transaction (thus avoiding lazy loading exceptions). I am, however, confused now with how I should deal with transac...

How do you clear a slice in Go?

What is the appropriate way to clear a slice in Go? Here's what I've found in the go forums: // test.go package main import ( "fmt" ) func main() { letters := []string{"a", "b", "c", "d"} fmt.Println(cap(letters)) fmt.Println(len(...

How to override and extend basic Django admin templates?

How do I override an admin template (e.g. admin/index.html) while at the same time extending it (see https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template)? First - I know that this question has been aske...

"Fatal error: Unable to find local grunt." when running "grunt" command

I uninstalled grunt with following command. npm uninstall -g grunt Then I again installed grunt with following command. npm install -g grunt-cli Visit following link: https://npmjs.org/package/grunt-html I want to use the above grunt plugin ...

JPA entity without id

I have a database with the following structure: CREATE TABLE entity ( id SERIAL, name VARCHAR(255), PRIMARY KEY (id) ); CREATE TABLE entity_property ( entity_id SERIAL, name VARCHAR(255), value TEXT ); When I try to create...

How to check the multiple permission at single request in Android M?

I want to use the android.permission.CAMERA android.permission.WRITE_EXTERNAL_STORAGE in single request using ActivityCompat.requestPermissions(Activity activity,new String permisionList[],int permissionRequestcode); But my problem is at tim...

Best Practices for securing a REST API / web service

When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management) ? When building a SOAP API you have WS-Security as a guide and much literature exists on the...

passing object by reference in C++

The usual way to pass a variable by reference in C++(also C) is as follows: void _someFunction(dataType *name){ // dataType e.g int,char,float etc. /**** definition */ } int main(){ dataType v; _somefunction(&v); //address of variable ...

PHP removing a character in a string

My php is weak and I'm trying to change this string: http://www.example.com/backend.php?/c=crud&m=index&t=care ^ to be: http://www.example.com/backend.php?c=crud&m=index&t=care ...

jQuery location href

I remember there's a redirect function in jQuery. It was like: $(location).href('http://address.com') But what was it exactly? I couldn't remember and can't find it using Google Search....

How to retrieve form values from HTTPPOST, dictionary or?

I have an MVC controller that has this Action Method: [HttpPost] public ActionResult SubmitAction() { // Get Post Params Here ... return something ... } The form is a non-trivial form with a simple textbox. Question How I access the param...

How do I properly escape quotes inside HTML attributes?

I have a drop down on a web page which is breaking when the value string contains a quote. The value is "asd, but in the DOM it always appears as an empty string. I have tried every way I know to escape the string properly, but to no avail. <op...

Making heatmap from pandas DataFrame

I have a dataframe generated from Python's Pandas package. How can I generate heatmap using DataFrame from pandas package. import numpy as np from pandas import * Index= ['aaa','bbb','ccc','ddd','eee'] Cols = ['A', 'B', 'C','D'] df = DataFrame(a...

How to store values from foreach loop into an array?

Need to store values from foreach loop into an array, need help doing that. The code below does not work, only stores the last value, tried $items .= ..., but that is not doing the trick either, any help will be appreciated. foreach($group_members...

How to set a maximum execution time for a mysql query?

I would like to set a maximum execution time for sql queries like set_time_limit() in php. How can I do ?...

Android getting value from selected radiobutton

I have a piece of code with three RadioButtons within a RadioGroup. I want to set an onCheckedListener that will show the value of the RadioButton in a Toast. However what I have gotten so far is not working. How do I get the value of the RadioButton...

Intent from Fragment to Activity

I was trying to go to another page using button, but it always fail. Here is my First Class with its XML: public class FindPeopleFragment extends Fragment { public FindPeopleFragment(){} @Override public View onCreateView(LayoutInflat...

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

Just got XAMPP 1.8.1 installed on my Windows 8 PC, this version includes packages mentioned below: Apache 2.4.3 MySQL 5.5.27 PHP 5.4.7 phpMyAdmin 3.5.2.2 FileZilla FTP Server 0.9.41 Tomcat 7.0.30 (with mod_proxy_ajp as connector) Strawberry Perl 5.1...

Use PHP to create, edit and delete crontab jobs?

Is it possible to use PHP to create, edit and delete crontab jobs? I know how to list the current crontab jobs of the Apache user: $output = shell_exec('crontab -l'); echo $output; But how to add a cron job with PHP? 'crontab -e' would just open ...

how to update spyder on anaconda

I have Anaconda installed (Python 2.7.11 |Anaconda custom (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)] on win32) and I am using Spyder 2.3.8 Would like to update Spyder to the latest version, so I went through the command...

Setting a WebRequest's body data

I'm creating a web request in ASP.NET and I need to add a bunch of data to the body. How do I do that? var request = HttpWebRequest.Create(targetURL); request.Method = "PUT"; response = (HttpWebResponse)request.GetResponse(); ...

Using a PagedList with a ViewModel ASP.Net MVC

I'm trying to using a PagedList in my ASP.Net application and I found this example on the Microsoft website http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-ap...

Compare DATETIME and DATE ignoring time portion

I have two tables where column [date] is type of DATETIME2(0). I have to compare two records only by theirs Date parts (day+month+year), discarding Time parts (hours+minutes+seconds). How can I do that?...

Check if PHP session has already started

I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn't have session started. Therefore when I have session_start() on this script I sometimes get the error message for "session already...

Is JavaScript object-oriented?

There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO." Is JavaScript an object-oriented language?...

How to use pagination on HTML tables?

I am trying to use this Pagination library in my HTML table page (specifically light theme) but somehow I am not able to understand how to plugin this library in such a way in my HTML page so that I can have pagination code working in my HTML table.....

How to set underline text on textview?

How to set underline text on textview? I have used following code but it is not working. tvHide.setText(Html.fromHtml("<p><u>Hide post</u></p>").toString()); ...

Iterate keys in a C++ map

Is there a way to iterate over the keys, not the pairs of a C++ map?...

Use jQuery to navigate away from page

I will only have a relative link available to me but I want to use jQuery to navigate to this rel link. I only see AJAX functionality in jQuery. How can I do this using jQuery or just pure HTML/JavaScript?...

How can I build multiple submit buttons django form?

I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter: <form action="" method="post"> {{ form_newsletter }} <input type="submit" name="newsletter_sub" value="Subscribe" /> <input type...

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

When I try to connect to any server (e.g. google.com) using curl (or libcurl) I get the error message: curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number Verbose output: $ curl www.google.com --verbose * Rebuilt URL ...

How to do a batch insert in MySQL

I have 1-many number of records that need to be entered into a table. What is the best way to do this in a query? Should I just make a loop and insert one record per iteration? Or is there a better way?...

JavaScript blob filename without link

How do you set the name of a blob file in JavaScript when force downloading it through window.location? function newFile(data) { var json = JSON.stringify(data); var blob = new Blob([json], {type: "octet/stream"}); var url = wi...

Android Studio - Importing external Library/Jar

I recently downloaded Android Studio to develop Android applications (I'm coming from Eclipse), and I am having issues using external libraries and/or external JAR files alongside my own project. NOTE: the following tests were conducted on a new appl...

How to convert timestamps to dates in Bash?

I need a shell command or script that converts a Unix timestamp to a date. The input can come either from the first parameter or from stdin, allowing for the following usage patterns: ts2date 1267619929 and echo 1267619929 | ts2date Both comman...

Get MD5 hash of big files in Python

I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in hashlib.md5() function. The problem is with very big files that their sizes could exceed RAM size. How to get the MD5 hash of a ...

Create Excel files from C# without office

I am writing a program that generates excel reports, currently using the Microsoft.Interop.Excel reference. My dev computer has Excel on it, but the end user may or may not have Office installed. Will this tool fail if Office isn't installed on the...

Simple way to create matrix of random numbers

I am trying to create a matrix of random numbers, but my solution is too long and looks ugly random_matrix = [[random.random() for e in range(2)] for e in range(3)] this looks ok, but in my implementation it is weights_h = [[random.random() for e...

Disable beep of Linux Bash on Windows 10

Having a Linux Bash on Windows 10 is pretty cool, but as far as I've got to struggle with the not-so-good terminal provided from Microsoft I'm gonna get stuck with Ubuntu for everything. Anyway, is there a way to turn off that beep whenever you do s...

How to connect Android app to MySQL database?

I have a website already setup which uses mysql database. I want to know how can i connect my app to that database. What i wanna achieve is that my app should make a request to find a table of a defined "ID" or name. The table contains links to imag...

window.open with headers

Can I control the HTTP headers sent by window.open (cross browser)? If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window? I need some cunning hacks....

Google reCAPTCHA: How to get user response and validate in the server side?

I am doing a Java (JSP + Servlet) web application (I understand that this question is technology-independent). I hope to use the latest Google reCAPTCHA service. I am playing with a Google reCAPTCHA example found here: https://developers.google.com/r...

mysql Foreign key constraint is incorrectly formed error

I have two tables, table1 is the parent table with a column ID and table2 with a column IDFromTable1 (not the actual name) when I put a FK on IDFromTable1 to ID in table1 I get the error Foreign key constraint is incorrectly formed error. I would lik...

What is the T-SQL syntax to connect to another SQL Server?

If I need to copy a stored procedure (SP) from one SQL Server to another I right click on the SP in SSMS and select Script Stored Procedure as > CREATE to > New Query Editor Window. I then change the connection by right clicking on that window and se...

Exception from HRESULT: 0x800A03EC Error

I am getting "HRESULT: 0x800A03EC" error when running Excel add-in with following code: Excel.Range rng = ActiveSheet.Cells[x, y] as Excel.Range; string before = rng.Value2; string cleanV = System.Text.RegularExpressions.Regex.Repla...

AngularJS : ng-click not working

I am new in AngularJs, ng-click is not working as expected. I searched on the internet , Follow the tutorial , (that was working) - but this is not working!!! My Code: <div class="row" ng:repeat="follower in myform.all_followers | partition:2"&...

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

I have a pom.xml in C:\Users\AArmijos\Desktop\Factura Electronica\MIyT\componentes-1.0.4\sources\pom.xml and I executed: mvn install:install-file -DgroupId=es.mityc.jumbo.adsi -DartifactId=xmlsec-1.4.2-ADSI -Dversion=1.0 -Dpackaging=jar -Dfile=C:\Us...

how to add css class to html generic control div?

I created a div tag like this: System.Web.UI.HtmlControls.HtmlGenericControl dynDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV"); I added style to the div tag like this: dynDiv.Style.Add(HtmlTextWriterStyle.BorderStyle, "1px so...

Arithmetic operation resulted in an overflow. (Adding integers)

I can't understand this error: In this call to method SetVolume, Volume = 2055786000 and size = 93552000. Volume is an Integer property, and size is also Integer, as you can see. The class is a partial class of a dbml entity class, however this V...

How to secure the ASP.NET_SessionId cookie?

I have set the .ASPXAUTH cookie to be https only but I am not sure how to effectively do the same with the ASP.NET_SessionId. The entire site uses HTTPS so there is no need for the cookie to work with both http and https....

npm install doesn't create node_modules directory

I am trying to do a homework for a mongodb uni course. They gave us some files, instructions are: run npm install mongodb then node app.js for some reason npm install does not create a node_modules directory but I don't see any build errors: mongo...

Math.random() explanation

This is a pretty simple Java (though probably applicable to all programming) question: Math.random() returns a number between zero and one. If I want to return an integer between zero and hundred, I would do: (int) Math.floor(Math.random() * 1...

How can I find an element by CSS class with XPath?

In my webpage, there's a div with a class named Test. How can I find it with XPath?...

How to verify that a specific method was not called using Mockito?

How to verify that a method is not called on an object's dependency? For example: public interface Dependency { void someMethod(); } public class Foo { public bar(final Dependency d) { ... } } With the Foo test: public class...

Eclipse change project files location

I have an Eclipse project (Flex Builder) of which the actual files have changed location on the drive. When I start Eclipse I can see the project listed but there are no actual files listed. Right clicking the project and selecting properties will sh...

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

I need to change the src for an html image tag from relative to absolute url. I am using the following code. urlRelative and urlAbsolute are created correctly but I cannot modify the image in the last line. What could be wrong wrong in my script? ...

What does "#pragma comment" mean?

What does #pragma comment mean in the following? #pragma comment(lib, "kernel32") #pragma comment(lib, "user32") ...

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

I developed a Windows service using C#.NET to generate PDF report. To generate PDF file I am using a third party dll. The application is running in my Windows XP platform. When I deployed the service in Windows Server 2008 64 bit version, I got this ...

When to use malloc for char pointers

I'm specifically focused on when to use malloc on char pointers char *ptr; ptr = "something"; ...code... ...code... ptr = "something else"; Would a malloc be in order for something as trivial as this? If yes, why? If not, then when is it necessary...

Change Image of ImageView programmatically in Android

When I change the image programmatically?, it shows new image on top of the old image which is set originally in layout file? Here is a snippet of my layout file: <LinearLayout android:layout_width="match_parent" android:layout_height="3...

Convert String to int array in java

I have one string String arr= "[1,2]"; ie "[1,2]" is like a single string How do convert this arr to int array in java...

C++/CLI Converting from System::String^ to std::string

Can someone please post a simple code that would convert, System::String^ To, C++ std::string I.e., I just want to assign the value of, String^ originalString; To, std::string newString; ...

Regex to remove letters, symbols except numbers

How can you remove letters, symbols such as 8§¶•ªºº«==÷ but leaving plain numbers 0-9, I want to be able to not allow letters or certain symbols in an input field but to leave numbers only. Demo. If you put any symbols like ¡ € # ¢ 8 �...

Calling method using JavaScript prototype

Is it possible to call the base method from a prototype method in JavaScript if it's been overridden? MyClass = function(name){ this.name = name; this.do = function() { //do somthing } }; MyClass.prototype.do = function() { ...

How to store Emoji Character in MySQL Database

I am using Emoji character in my project. That characters are saved (??) into mysql database. I had used database Default collation in utf8mb4_general_ci. It show 1366 Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column 'comment' ...

Running Java Program from Command Line Linux

I am not very experience with java and this is driving me crazy. I wrote a java program FileManagement and I need to run it from the command line. I can compile it from the command line with javac FileManagement/*.java which will create all the clas...

Using jQuery to programmatically click an <a> link

I know this question has been asked before, but after a search on the web I can't seem to find a straight forward answer. the HTML <a id=myAnchor href=index.php> the jQuery (Both of these do not work) $('#myAnchor').click(); or $('#my...

Query to list all stored procedures

What query can return the names of all the stored procedures in a SQL Server database If the query could exclude system stored procedures, that would be even more helpful....

How do I create/edit a Manifest file?

I have this code from a coworker (probably got it from the web somewhere) but he's out on vacation and I need to add this to the manifest file <?xml version="1.0" encoding="utf-8" ?> <asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas...

How to know if a DateTime is between a DateRange in C#

I need to know if a Date is between a DateRange. I have three dates: // The date range DateTime startDate; DateTime endDate; DateTime dateToCheck; The easy solution is doing a comparison, but is there a smarter way to do this?...

How to install mod_ssl for Apache httpd?

Ok So I installed Apache httpd a while ago and have recently come back to it to try setup SSL and get it serving several different tomcat servers. At the moment I have two completely separate Tomcat instances serving up to slightly different versio...

SQL keys, MUL vs PRI vs UNI

What is the difference between MUL, PRI and UNI in MySQL? I'm working on a MySQL query, using the command: desc mytable; One of the fields is shown as being a MUL key, others show up as UNI or PRI. I know that if a key is PRI, only one record p...

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

What is acutally the functionality of WPFFontCache in WPF?. Sometime it is takeing too much CPU usage because of this system in hanging and my Application. Is there any problem disabling the service from the windows service. The big concern is why it...

OpenCV - Apply mask to a color image

How can I apply mask to a color image in latest python binding (cv2)? In previous python binding the simplest way was to use cv.Copy e.g. cv.Copy(dst, src, mask) But this function is not available in cv2 binding. Is there any workaround without usi...

Cannot assign requested address using ServerSocket.socketBind

When I'm trying to set up a socket server, I've got an error message: Exception in thread "main" java.net.BindException: Cannot assign requested address: JVM_Bind at java.net.PlainSocketImpl.socketBind(Native Method) at java.net.PlainSocketI...

How does one capture a Mac's command key via JavaScript?

How does one capture a Mac's Cmd key via JavaScript?...

Getting the class name of an instance?

How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived? Was thinking maybe the inspect module might have helped me ...

Why am I getting a " Traceback (most recent call last):" error?

I'm sorry for asking, but I can't find why I'm getting this errors, especially after the program is running. The erros to be exact are: >>> Welcome! This program will convert measures for you. Select operation. 1.Miles to Kilometers 2.Fah...

How to calculate UILabel width based on text length?

I want to display an image next to a UILabel, however UILabel has variable text length, so I don't know where to place the image. How can I accomplish this?...

How can I determine the sector size in windows?

How can I determine the Physical Sector Size (e.g. if i have an Advanced Format drive with 4,096 byte sectors rather than the legacy 512 byte sectors) in Windows 7? I know that by clicking on a file and get properties we can find out the NTFS Cluste...

How to set ANDROID_HOME path in ubuntu?

How to set ANDROID_HOME path in ubuntu? Please provide the steps....

Anaconda-Navigator - Ubuntu16.04

This is ubuntu16.04. I can open Anaconda-Navigator from the terminal using anaconda-navigator, but when I click on it, it doesn't open. What am I missing?...

PHP mkdir: Permission denied problem

I am trying to create a directory with PHP mkdir function but I get an error as follows: Warning: mkdir() [function.mkdir]: Permission denied in .... How to settle down the problem?...

System.currentTimeMillis vs System.nanoTime

Accuracy Vs. Precision What I would like to know is whether I should use System.currentTimeMillis() or System.nanoTime() when updating my object's positions in my game? Their change in movement is directly proportional to the elapsed time since the...

Android - running a method periodically using postDelayed() call

I have a situation in an Android app where I want to start a network activity (sending out some data) which should run every second. I achieve this as follows: In the onCreate() I have the code: tv = new TextView(this); tv.postDelayed(sendData, 100...

Generic Interface

Let's say I wanted to define an interface which represents a call to a remote service. Now, the call to the remote service generally returns something, but might also include input parameters. Suppose that an implementing class will typically only im...

How to list the certificates stored in a PKCS12 keystore with keytool?

I wanted to list the certificates stored in a PKCS12 keystore. The keystore has the extension .pfx...

"Unable to locate tools.jar" when running ant

When running ant, I get the following message: Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre6\lib\tools.jar I have JAVA_HOME set to C:\Program Files\Java\jdk1.7.0_02, PATH includes C:\Program Files (x86)\Java\jdk1.7.0...

php: Get html source code with cURL

How can I get the html source code of http://www.example-webpage.com/file.html without using file_get_contents()? I need to know this because on some webhosts allow_url_fopen is disabled so you can't use file_get_contents(). Is it possible to get th...

Convert Java object to XML string

Yes, yes I know that lots of questions were asked about this topic. But I still cannot find the solution to my problem. I have a property annotated Java object. For example Customer, like in this example. And I want a String representation of it. Goo...

Iterate a list with indexes in Python

I could swear I've seen the function (or method) that takes a list, like this [3, 7, 19] and makes it into iterable list of tuples, like so: [(0,3), (1,7), (2,19)] to use it instead of: for i in range(len(name_of_list)): name_of_list[i] = someth...

Add User to Role ASP.NET Identity

I know the new Membership includes a "Simple Role Provider." I can't find any help related to creating a user and assigning a role when the user is created. I've added a user which created the tables on the DB correctly. I see the AspNetRoles, AspN...

Dynamic Height Issue for UITableView Cells (Swift)

Dynamic text of variable length are being injected into tableview cell labels. In order for the tableview cells' heights to be dynamically sized, I have implemented in viewDidLoad(): self.tableView.estimatedRowHeight = 88.0 self.tableView.rowHeight ...

Select the values of one property on all objects of an array in PowerShell

Let's say we have an array of objects $objects. Let's say these objects have a "Name" property. This is what I want to do $results = @() $objects | %{ $results += $_.Name } This works, but can it be done in a better way? If I do something lik...

CASE in WHERE, SQL Server

I'm doing some search, where users are choosing in dropdown some clauses. When they leave some box empty, I want query to ignore clause. I know CASE, and best I thought of is that if I pass 0 to parameter in stored procedure, it ignores that paramete...

How to execute python file in linux

I am using linux mint, and to run a python file I have to type in the terminal: python [file path], so is there way to make the file executable, and make it run the python command automatically when I doublr click it? And since I stopped dealing wit...

Is there a NumPy function to return the first index of something in an array?

I know there is a method for a Python list to return the first index of something: >>> l = [1, 2, 3] >>> l.index(2) 1 Is there something like that for NumPy arrays?...

How can I undo a mysql statement that I just executed?

How can I undo the most recently executed mysql query?...

Download image from the site in .NET/C#

I am trying to download images from the site. The code which I am using is working fine while the image is available. If the image it not available it is creating a problem. How to validate availability of the image? Code: Method 1: WebRequest req...

Installing a specific version of angular with angular cli

I searched through google and angular cli doc but couldn't find any way to install a specific version of angular using angular cli. is it even possible?...

Is there an equivalent method to C's scanf in Java?

Java has the notion of format strings, bearing a strong resemblance to format strings in other languages. It is used in JDK methods like String#format() for output conversion. I was wondering if there an input conversion method akin to C's scanf in ...

Jquery assiging class to th in a table

I am trying to assign class to table headers. I am trying to read class names of td's and assign it to related th header. Any help would be appreciated. <table > <tr> <th>hdrcol1</th> <th>hdrcol2</th> ...

How do I create a unique ID in Java?

I'm looking for the best way to create a unique ID as a String in Java. Any guidance appreciated, thanks. I should mention I'm using Java 5....

jquery ajax get responsetext from http url

Neither: var response = $.ajax({ type: "GET", url: "http://www.google.de", async: false, success : function() { alert (this); } }); Nor: var response2 = $.get("http://www.google.de", function(data) { alert("D...

Javascript: console.log to html

I would like to write the console.log output to a div layer. For example: document.write(console.log(5+1)); //Incorrect, random example Can someone give me a solution to my problem? Thank you. EDIT: what i meant is, for example: console.log("...

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

I'm trying to merge a (Pandas 14.1) dataframe and a series. The series should form a new column, with some NAs (since the index values of the series are a subset of the index values of the dataframe). This works for a toy example, but not with my da...

Pressed <button> selector

I'd like to create a button that changes its style when it gets pressed. This is my CSS code: _x000D_ _x000D_ button {_x000D_ font-size: 18px;_x000D_ border: 2px solid gray;_x000D_ border-radius: 100px;_x000D_ width: 100px;_x000D_ ...

Programmatically scroll a UIScrollView

I have a UIScrollView which has several views. When a user flicks their finger, the view scrolls to the right or left depending on the direction of the finger flick. Basically my code works in a way similar to the iPhone photo app. Now, is there a w...

Can't bind to 'formGroup' since it isn't a known property of 'form'

THE SITUATION: Please help! I am trying to make what should be a very simple form in my Angular2 app but no matter what it never works. ANGULAR VERSION: Angular 2.0.0 Rc5 THE ERROR: Can't bind to 'formGroup' since it isn't a known property of 'f...

How to turn off the Eclipse code formatter for certain sections of Java code?

I've got some Java code with SQL statements written as Java strings (please no OR/M flamewars, the embedded SQL is what it is - not my decision). I've broken the SQL statements semantically into several concatenated strings over several lines of cod...

NSDate get year/month/day

How can I get the year/month/day of a NSDate object, given no other information? I realize that I could probably do this with something similar to this: NSCalendar *cal = [[NSCalendar alloc] init]; NSDateComponents *components = [cal components:0 fr...

You are trying to add a non-nullable field 'new_field' to userprofile without a default

I know that from Django 1.7 I don't need to use South or any other migration system, so I am just using simple command python manage.py makemigrations However, all I get is this error: You are trying to add a non-nullable field 'new_field' to user...

python: [Errno 10054] An existing connection was forcibly closed by the remote host

I am writing python to crawl Twitter space using Twitter-py. I have set the crawler to sleep for a while (2 seconds) between each request to api.twitter.com. However, after some times of running (around 1), when the Twitter's rate limit not exceeded ...

SQL Server using wildcard within IN

Since I believe this should be a basic question I know this question has probably been asked, but I am unable to find it. I'm probably about to earn my Peer Pressure badge, but I'll ask anyway: Is there a way in SQL Server that I am not aware of for...

MongoDB: How to find the exact version of installed MongoDB

I have mongoDB 3.2 installed locally for Windows 7. I would like to find out its specific version (like is it 3.2.1, or 3.2.3 or...). How could I find it? If I open the database shell (mongo.exe), I can see it outputs: MongoDB shell version: 3.2....

Apply function to each column in a data frame observing each columns existing data type

I'm trying to get the min/max for each column in a large data frame, as part of getting to know my data. My first try was: apply(t,2,max,na.rm=1) It treats everything as a character vector, because the first few columns are character types. So max...

$(document).ready not Working

I am trying to run jQuery and WebMethods with ASP.NET; I have added a ScriptManager to the master page, and a content on the content page <asp:Content ID="ch" ContentPlaceHolderID="cHead" runat="server"> <script language="javascript" ty...

How to set focus to a button widget programmatically?

Is it possible to set a focus to a button widget which lies somewhere down in my layout? onCreate of the activity my control/focus should be on that button programmatically....

How to delete a file after checking whether it exists

How can I delete a file in C# e.g. C:\test.txt, although apply the same kind of method like in batch files e.g. if exist "C:\test.txt" delete "C:\test.txt" else return nothing (ignore) ...

List of remotes for a Git repository?

I have a Git repository. This repository has multiple remote repositories (I think). How can I get a list of the remote repositories that belong to said repository? Like git list --remotes or something like that?...

Is it better practice to use String.format over string Concatenation in Java?

Is there a perceptible difference between using String.format and String concatenation in Java? I tend to use String.format but occasionally will slip and use a concatenation. I was wondering if one was better than the other. The way I see it, Stri...

How do I use method overloading in Python?

I am trying to implement method overloading in Python: class A: def stackoverflow(self): print 'first method' def stackoverflow(self, i): print 'second method', i ob=A() ob.stackoverflow(2) but the output is second me...

Get immediate first child element

I'm writing a Chrome content script extension and I need to be able to target a specific element that, unfortunately, has no unique identifiers except its parent element. I need to target the immediate first child element of parentElement. console.l...

Basic Ajax send/receive with node.js

So I'm trying to make a very basic node.js server that with take in a request for a string, randomly select one from an array and return the selected string. Unfortunately I'm running into a few problems. Here's the front end: function newGame() {...

Where is the Java SDK folder in my computer? Ubuntu 12.04

I know it's installed because when I type: $java -version I get: OpenJDK Runtime Environment (IcedTea6 1.12.5) (6b27-1.12.5-0ubuntu0.12.04.1) OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode) And when I type: $locate jdk I get: /home/ar...

jquery save json data object in cookie

How do I save JSON data in a cookie? My JSON data looks like this $("#ArticlesHolder").data('15', {name:'testname', nr:'4',price:'400'}); $("#ArticlesHolder").data('25', {name:'name2', nr:'1', price:'100'}); $("#ArticlesHolder").data('37', {name:'n...

Access And/Or exclusions

I have some sample data like: |H.RISK|NOTE|NORMAL| The | are actually in the data, it's a String. I am using Access, and am trying to exclude records that contain RISK in the String. Sample query: SELECT * FROM someTable WHERE (UCase(someTable....

How to create a database from shell command?

I'm looking for something like createdb in PostgreSQL or any other solution that would allow me to create database with a help of a shell command. Any hints?...

Python Progress Bar

How do I use a progress bar when my script is doing some task that is likely to take time? For example, a function which takes some time to complete and returns True when done. How can I display a progress bar during the time the function is being e...

Typescript: React event types

What is the correct type for React events. Initially I just used any for the sake of simplicity. Now, I am trying to clean things up and avoid use of any completely. So in a simple form like this: export interface LoginProps { login: { [k: st...

Control the dashed border stroke length and distance between strokes

Is it possible to control the length and distance between dashed border strokes in CSS? This example below displays differently between browsers: _x000D_ _x000D_ div {_x000D_ border: dashed 4px #000;_x000D_ padding: 20px;_x000D_ display: inli...

How to check object is nil or not in swift?

Suppose I have String like : var abc : NSString = "ABC" and I want to check that it is nil or not and for that I try : if abc == nil{ //TODO: } But this is not working and giving me an error. Error Says : Can not invoke '=='with ...

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

For example if I have this: <a style="" href="page.html">page link</a> Is there anything I can use for the style attribute that will make it so the link isn't clickable and won't take me to page.html? Or, is my only option to simply no...

How to uncommit my last commit in Git

How can I uncommit my last commit in git? Is it git reset --hard HEAD or git reset --hard HEAD^ ?...

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

How to I get mongo to use a mounted drive on ec2? I really do not understand. I attached a volume on ec2 formatted the drive as root and start as root and yet as root I cant access? I am running on ubuntu 12.04. No other mongo is running I see t...

Running interactive commands in Paramiko

I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec_command and the execution hangs. Is there a way to send values to the t...

Why can't I display a pound (£) symbol in HTML?

I'm trying to display the pound symbol in HTML (from PHP) but all I get is a symbol with a question mark. The following are things that I've tried. In PHP: header('Content-type: text/html; charset=utf-8'); In HTML, put this in the head tag: <...

SQL SERVER DATETIME FORMAT

Studying SQL Server there is something I am not sure of: A datetime field with the value: 2012-02-26 09:34:00.000 If I select out of the table using: CAST(dob2 AS VARCHAR(12) ) AS d1 It formats it as: Feb 26 2012 What I am unsure of his how or ...

Getting output of system() calls in Ruby

If I call a command using Kernel#system in Ruby, how do I get its output? system("ls") ...

Iterate through string array in Java

I have String array with some components, this array has 5 components and it vary some times. What I would like to do is to iterate through that array and get the first component and the component next to that one. So the first time I would get the c...

Stopping Excel Macro executution when pressing Esc won't work

I'm running excel 2007 on XP. Is there a way to stop a macro from running during its execution other than pressing escape? Usually if I think I created an infinate loop or otherwise messed something up I hit escape and it throws an error but the ma...

Using the "animated circle" in an ImageView while loading stuff

I am currently using in my application a listview that need maybe one second to be displayed. What I currently do is using the @id/android:empty property of the listview to create a "loading" text. <TextView android:id="@id/android:empty" ...

How should I declare default values for instance variables in Python?

Should I give my class members default values like this: class Foo: num = 1 or like this? class Foo: def __init__(self): self.num = 1 In this question I discovered that in both cases, bar = Foo() bar.num += 1 is a well-define...

How to handle click event in Button Column in Datagridview?

I am developing a windows application using C#. I am using DataGridView to display data. I have added a button column in that. I want to know how can I handle click event on that button in DataGridView....

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

There is a script running which mirrors a bunch of folders from one volume to another. The problem is that now there are going to be subdirectories within those folders at the destination which are not part of the original mirroring script. They are ...

Android: how to get the current day of the week (Monday, etc...) in the user's language?

I want to know what the current day of the week is (Monday, Tuesday...) in the user's local language. For example, "Lundi" "Mardi" etc... if the user is French. I have read this post, it but it only returns an int, not a string with the day in the ...

Data truncation: Data too long for column 'logo' at row 1

I am trying to insert a photo into a BLOB column of a MySQL table, and I get an exception: Data too long for column 'logo' at row 1. Here is the JDBC: int idRestaurant = 42; String restoname= "test"; String restostatus= "test"; ...

SQL query: Delete all records from the table except latest N?

Is it possible to build a single mysql query (without variables) to remove all records from the table, except latest N (sorted by id desc)? Something like this, only it doesn't work :) delete from table order by id ASC limit ((select count(*) from ...

SQL Server - Return value after INSERT

I'm trying to get a the key-value back after an INSERT-statement. Example: I've got a table with the attributes name and id. id is a generated value. INSERT INTO table (name) VALUES('bob'); Now I want to get the id back in the same step. How...

How can I create keystore from an existing certificate (abc.crt) and abc.key files?

I am trying to import a certificate and a key file into the keystore but I'm unable to do that. How can I create a keystore by importing both an existing certificate (abc.crt) and abc.key files?...

How to embed YouTube videos in PHP?

Can anyone give me an idea how can we show or embed a YouTube video if we just have the URL or the Embed code?...

Add hover text without javascript like we hover on a user's reputation

In stackoverflow, when we hover on a user's reputation we see a text. I have seen this at many places and the source code tells me that it can be done without js. And i tried and got only this- <div="text">hover me</div> ...

jQuery get content between <div> tags

This'll probably be easy for someone: var x = '<p>blah</p><div><a href="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=brd&FlightID=2997227&Page=&PluID=0&Pos=9088" target="_blank"><img src="http://bs...

Replace multiple strings at once

Is there an easy equivalent to this in JavaScript? $find = array("<", ">", "\n"); $replace = array("&lt;", "&gt;", "<br/>"); $textarea = str_replace($find, $replace, $textarea); This is using PHP's str_replace, which allows y...

Saving data to a file in C#

So i am currently working on a project to make an automated Character Sheet for the Pathfinder Roleplaying Game, and am at a loss as to how to save the data. I want to save the current value of all my variables to a file with the extension .pfcsheet ...

pandas dataframe columns scaling with sklearn

I have a pandas dataframe with mixed type columns, and I'd like to apply sklearn's min_max_scaler to some of the columns. Ideally, I'd like to do these transformations in place, but haven't figured out a way to do that yet. I've written the followi...

Twitter Bootstrap: Print content of modal window

I'm developing a site using Bootstrap which has 28 modal windows with information on different products. I want to be able to print the information in an open modal window. Each window has an id. <!-- firecell panel & radio hub --> ...

How can I disable all views inside the layout?

For example I have: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button androi...

Undefined reference to main - collect2: ld returned 1 exit status

I'm trying to compile a program (called es3), but, when I write from terminal: gcc es3.c -o es3 it appears this message: /usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/crt1.o: In function `_start': (.text+0x18): undefined reference to `main' co...

gcc: undefined reference to

I would like to compile this. program.c #include <libavcodec/avcodec.h> int main(){ int i = avpicture_get_size(AV_PIX_FMT_RGB24,300,300); } Running this gcc -I$HOME/ffmpeg/include program.c gives error /tmp/ccxMLBme.o: In function...

PostgreSQL IF statement

How can I do such query in Postgres? IF (select count(*) from orders) > 0 THEN DELETE from orders ELSE INSERT INTO orders values (1,2,3); ...

Android Studio-No Module

I am new to Android Studio.This is my project screenshot.My project builds successfully but when i run it only Build Successful is shown. By what I understand I think where build is written in the toolbar there should be my project name.When I go to ...

Get width in pixels from element with style set with %?

I have this element: <div style="width: 100%; height: 10px;"></div> I want to get it's width in pixels. I just tried this: document.getElementById('banner-contenedor').style.width Which returns 100%. Is it possible to actually...

How to restart tomcat 6 in ubuntu

How can one restart and start Tomcat 6 on Ubuntu from the command line with a default installation?...

jquery - How to determine if a div changes its height or any css attribute?

I wanna know how to trigger an event when a div changes its height or any css attribute. I have a div with id = mainContent. I want jquery to automatically trigger an event when it changes its height. I did something like this: $("#mainContent")....

How to check if a folder exists

I am playing a bit with the new Java 7 IO features, actually I trying to receive all the xml files of a folder. But this throws an exception when the folder does not exist, how can I check if the folder exists with the new IO? public UpdateHandler(...

Passing data into "router-outlet" child components

I've got a parent component that goes to the server and fetches an object: // parent component @Component({ selector : 'node-display', template : ` <router-outlet [node]="node"></router-outlet> ` }) export class Nod...

max value of integer

In C, the integer (for 32 bit machine) is 32 bits, and it ranges from -32,768 to +32,767. In Java, the integer(long) is also 32 bits, but ranges from -2,147,483,648 to +2,147,483,647. I do not understand how the range is different in Java, even thou...

Telling gcc directly to link a library statically

It feels strange to me to use -Wl,-Bstatic in order to tell gcc which libraries I want to link with statically. After all I'm telling gcc directly all other information about linking with libraries (-Ldir, -llibname). Is it possible to tell the gcc...

What is a NullReferenceException, and how do I fix it?

I have some code and when it executes, it throws a NullReferenceException, saying: Object reference not set to an instance of an object. What does this mean, and what can I do to fix this error?...

Intellij Cannot resolve symbol on import

This problem happens intermittently for different libraries and different projects. When trying to import a library, the package will be recognized, but the class name can't be resolved. If on the import statement, I right-click -> Goto -> the...

"Unorderable types: int() < str()"

I'm trying to make a retirement calculator right now on Python. There's nothing wrong with the syntax but when I run the following program: def main(): print("Let me Retire Financial Calculator") deposit = input("Please input annual deposit ...

How can I join on a stored procedure?

I have a stored procedure that takes no parameters, and it returns two fields. The stored procedure sums up all transactions that are applied to a tenant, and it returns the balance and the id of the tenant. I want to use the record set it returns w...

How to hide image broken Icon using only CSS/HTML?

How can I hide the broken image icon? Example: I have an image with error src: <img src="Error.src"/> The solution must work in all browsers....

How to find Google's IP address?

Google is blocked in some countries. However, there are many ways to access Google, like VPN, agent, and by changing the hosts file. If I want to change the hosts file to access Google, how can I find an available IP address? Update I can't acces...

AttributeError: 'str' object has no attribute

I'm pretty new to python programming and I wanted to try my hand at a simple text adventure game, but I've immediately stumbled on a roadblock. class userInterface: def __init__(self, roomID, roomDesc, dirDesc, itemDesc): self.roomID = r...

How to remove numbers from string using Regex.Replace?

I need to use Regex.Replace to remove all numbers and signs from a string. Example input: 123- abcd33 Example output: abcd...

Getting list of items inside div using Selenium Webdriver

Say I have the following <div class="facetContainerDiv"> <div> <label class="facetLabel"> <input class="facetCheck" type="checkbox" /> </label> <label class="facetLabel"> ...

Ascending and Descending Number Order in java

I'm doing an ascending and descending order number in java and here's my code: System.out.print("Enter How Many Inputs: "); int num1 = Integer.parseInt(in.readLine()); int arr[] = new int[num1]; for (int i = 0; i<num1; i++) { System.out.prin...

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

While creating product, at the last step after retrieving for a time, Magento gives following error-: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT' What I am doing is, by capturing pr...

Laravel Soft Delete posts

in our project we must be use soft delete for each posts. in laravel document i think we can only use this feature for tables. can we use that for posts on table such as $id = Contents::find($id); $id->softDeletes(); ...

How to install APK from PC?

I want to install an APK from PC to Android device. And because of user's Android and generally technical skills, I need to do it as automatically (silently) as possible. So how do I send an APK from PC to Android and start install there?...

How to use regex in file find

I was trying to find all files dated and all files 3 days or more ago. find /home/test -name 'test.log.\d{4}-d{2}-d{2}.zip' -mtime 3 It is not listing anything. What is wrong with it?...

How do I fix the indentation of selected lines in Visual Studio

In vim I can use = to reindent badly indented lines so foo; bar; baz; becomes foo; bar; baz; Is there an equivalent keyboard-shortcut for visual studio? Where can I find a list of such shortcuts for future reference? Edit: Is there a way ...

Which variable size to use (db, dw, dd) with x86 assembly?

I am a beginner to assembly and I don't know what all the db, dw, dd, things mean. I have tried to write this little script that does 1+1, stores it in a variable and then displays the result. Here is my code so far: .386 .model flat, stdcall optio...

trying to animate a constraint in swift

I have a UITextField that I want to enlarge its width when tapped on. I set up the constraints and made sure the constraint on the left has the lower priority then the one that I am trying to animate on the right side. Here is the code that I am tryi...

How to initialize a List<T> to a given size (as opposed to capacity)?

.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization. Arrays are very easy to initialize with a default value, and by definitio...

Create an array of integers property in Objective-C

I'm having troubles creating a property of an array of integers in Objective-C. I'm not sure whether this is even possible to do in Obj-C so I'm hoping someone can help me in finding out either how to do it correctly or provide an alternative solutio...

How do I assign a port mapping to an existing Docker container?

I'm not sure if I've misunderstood something here, but it seems like it's only possible to set port mappings by creating a new container from an image. Is there a way to assign a port mapping to an existing Docker container?...

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

I am getting the error in the below sql: ORA-01858: a non-numeric character was found where a numeric was expected SELECT c.contract_num, CASE WHEN ( MAX (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')) ...

Is there a TRY CATCH command in Bash

I'm writing a shell script and need to check that a terminal app has been installed. I want to use a TRY/CATCH command to do this unless there is a neater way....

How to detect internet speed in JavaScript?

How can I create a JavaScript page that will detect the user’s internet speed and show it on the page? Something like “your internet speed is ??/?? Kb/s”....

How to get the list of all database users

I am going to get the list of all users, including Windows users and 'sa', who have access to a particular database in MS SQL Server. Basically, I would like the list to look like as what is shown in SQL Server Management Studio (i.e. the list that i...

Can an int be null in Java?

Can an int be null in Java? For example: int data = check(Node root); if ( data == null ) { // do something } else { // do something } My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the ...

Twitter bootstrap progress bar animation on page load

I have a page with several bootstrap progress bars. Setting their values initially works fine. Though I would like the progress bars to animate/transition to their specific states when a user opens the page. This JS works fine, when you click on one...

Convert Little Endian to Big Endian

I just want to ask if my method is correct to convert from little endian to big endian, just to make sure if I understand the difference. I have a number which is stored in little-endian, here are the binary and hex representations of the number: ?...

Logical XOR operator in C++?

Is there such a thing? It is the first time I encountered a practical need for it, but I don't see one listed in Stroustrup. I intend to write: // Detect when exactly one of A,B is equal to five. return (A==5) ^^ (B==5); But there is no ^^ operato...

How do you create a Swift Date object?

How do you create a date object from a date in swift xcode. eg in javascript you would do: var day = new Date('2014-05-20');...

How to programmatically modify WCF app.config endpoint address setting?

I'd like to programmatically modify my app.config file to set which service file endpoint should be used. What is the best way to do this at runtime? For reference: <endpoint address="http://mydomain/MyService.svc" binding="wsHttpBinding" b...

What is declarative programming?

I keep hearing this term tossed around in several different contexts. What is it?...

Tokenizing Error: java.util.regex.PatternSyntaxException, dangling metacharacter '*'

I am using split() to tokenize a String separated with * following this format: name*lastName*ID*school*age % name*lastName*ID*school*age % name*lastName*ID*school*age I'm reading this from a file named "entrada.al" using this code: static void l...

How to make a SIMPLE C++ Makefile

We are required to use a Makefile to pull everything together for our project, but our professor never showed us how to. I only have one file, a3driver.cpp. The driver imports a class from a location, "/user/cse232/Examples/example32.sequence.cpp". ...

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

I am having a problem converting a datetime which is in string format but I am not able to convert it using "yyyyMMdd" format. My code is: string tpoc = refSubClaim.BenefitsFolder.BenefitFolderIdNumber.ToString(); string[] tpocinfo = Regex.Split(tp...

compare differences between two tables in mysql

Same as oracle diff: how to compare two tables? except in mysql. Suppose I have two tables, t1 and t2 which are identical in layout but which may contain different data. What's the best way to diff these two tables? To be more precise, I'm trying t...

MySQL: Cloning a MySQL database on the same MySql instance

I would like to write a script which copies my current database sitedb1 to sitedb2 on the same mysql database instance. I know I can dump the sitedb1 to a sql script: mysqldump -u root -p sitedb1 >~/db_name.sql and then import it to sitedb2. I...

How do I REALLY reset the Visual Studio window layout?

I had a plugin installed in Visual Studio 2008, and it created some extra dockable windows. I have uninstalled it, and I can't get rid of the windows it created - I close them, but they always come back. They're just empty windows now, since the pl...

How do you specify a byte literal in Java?

If I have a method void f(byte b); how can I call it with a numeric argument without casting? f(0); gives an error....

Plugin with id 'com.google.gms.google-services' not found

I have followed this link to integrate ads in my app. But it shows this error: This is my build.gradle: apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' android { compileSdkVersion 24 buildToolsVersion "24.0....

How to create query parameters in Javascript?

Is there any way to create the query parameters for doing a GET request in JavaScript? Just like in Python you have urllib.urlencode(), which takes in a dictionary (or list of two tuples) and creates a string like 'var1=value1&var2=value2'....

How do I copy a 2 Dimensional array in Java?

I need to make a copy of a fairly large 2 dimensional array for a project I am working on. I have two 2D arrays: int[][]current; int[][]old; I also have two methods to do the copying. I need to copy the array because current is regularly being upd...

node and Error: EMFILE, too many open files

For some days I have searched for a working solution to an error Error: EMFILE, too many open files It seems that many people have the same problem. The usual answer involves increasing the number of file descriptors. So, I've tried this: sysctl -w...

format a number with commas and decimals in C# (asp.net MVC3)

I Need to display a number with commas and decimal point. Eg: Case 1 : Decimal number is 432324 (This does not have commas or decimal Points) Need to display it as 432,324.00 but not 432,324 Case 2 : Decimal number is 2222222.22 (This does not...

Anaconda site-packages

After installing a package in an anaconda environment, I'll like to make some changes to the code in that package. Where can I find the site-packages directory containing the installed packages? I do not find a directory /Users/username/anaconda/lib...

Pass Hidden parameters using response.sendRedirect()

How would I pass hidden parameters? I want to call a page (test.jsp) but also pass 2 hidden parameters like a post. response.sendRedirect("/content/test.jsp"); ...

JavaScript: replace last occurrence of text in a string

See my code snippet below: var list = ['one', 'two', 'three', 'four']; var str = 'one two, one three, one four, one'; for ( var i = 0; i < list.length; i++) { if (str.endsWith(list[i]) { str = str.replace(list[i], 'finish') ...

Variables as commands in bash scripts

I am writing a very simple bash script that tars a given directory, encrypts the output of that, and then splits the resultant file into multiple smaller files since the backup media don't support huge files. I don't have a lot of experience with ba...

jQuery and TinyMCE: textarea value doesn't submit

I am using jQuery and TinyMCE to submit a form, but there is a problem in serialization in that the Textarea value doesn't post. Here is the code: <form id="myForm" method="post" action="post.php"> <textarea name="question_text" id="qu...

How do I sort a list of datetime or date objects?

How do I sort a list of date and/or datetime objects? The accepted answer here isn't working for me: from datetime import datetime,date,timedelta a=[date.today(), date.today() + timedelta(days=1), date.today() - timedelta(days=1)] print a # prints...

How do I include negative decimal numbers in this regular expression?

How do I match negative numbers as well by this regular expression? This regex works fine with positive values, but I want it to also allow negative values e.g. -10, -125.5 etc. ^[0-9]\d*(\.\d+)?$ Thanks...

How to get all columns' names for all the tables in MySQL?

Is there a fast way of getting all column names from all tables in MySQL, without having to list all the tables?...

How can I set selected option selected in vue.js 2?

My component vue is like this : <template> <select class="form-control" v-model="selected" :required @change="changeLocation"> <option :selected>Choose Province</option> <option v-for="option in options...

Limit the size of a file upload (html input element)

I would like to simply limit the size of a file that a user can upload. I thought maxlength = 20000 = 20k but that doesn't seem to work at all. I am running on Rails, not PHP, but was thinking it'd be much simpler to do it client side in the HTML...

ASP.NET Core Web API Authentication

I'm struggling with how to set up authentication in my web service. The service is build with the ASP.NET Core web api. All my clients (WPF applications) should use the same credentials to call the web service operations. After some research, I c...

Compiler error: memset was not declared in this scope

I am trying to compile my C program in Ubuntu 9.10 (gcc 4.4.1). I am getting this error: Rect.cpp:344: error: ‘memset’ was not declared in this scope But the problem is I have already included in my cpp file: #include <stdio.h> #includ...

Eclipse: Java was started but returned error code=13

I just updated Java to 1.8 u25, and now I get this message every time I try to open Eclipse I have no clue what I'm doing wrong, when it comes to Eclipse. I have re-downloaded it number of times but still cannot get it to work. How could I fix thi...

How to pass extra variables in URL with WordPress

I am having trouble trying to pass an extra variable in the url to my WordPress installation. For example /news?c=123 For some reason, it works only on the website root www.example.com?c=123 but it does not work if the url contains any more inform...

What is the canonical way to trim a string in Ruby without creating a new string?

This is what I have now - which looks too verbose for the work it is doing. @title = tokens[Title].strip! || tokens[Title] if !tokens[Title].nil? Assume tokens is a array obtained by splitting a CSV line. now the functions like strip! chomp...

How to escape JSON string?

Are there any classes/functions available to be used for easy JSON escaping? I'd rather not have to write my own....

MS SQL Date Only Without Time

Question Hello All, I've had some confusion for quite some time with essentially flooring a DateTime SQL type using T-SQL. Essentially, I want to take a DateTime value of say 2008-12-1 14:30:12 and make it 2008-12-1 00:00:00. Alot of the queries ...

What is the difference between HTTP status code 200 (cache) vs status code 304?

I'm using the Google "Page Speed" plug-in for Firefox to access my web site. Some of the components on my page is indicated as HTTP status: 200 200 (cache) 304 By Google's "Page Speed". What I'm confused about is the difference between ...

What does -save-dev mean in npm install grunt --save-dev

I've just started using Grunt.js. It is pretty hard to set up and I am at the point of creating a package.json file. Following this tutorial, it says there are 3 ways to create a package.json file. The first is to do npm install grunt --save-dev B...

Resizable table columns with jQuery

This is the only jQuery plugin I could find to resize table column widths, but it does not integrate well with my table, and has unnecessary bloat (saves in cookies). Are there any other plugins for just resizing columns? (NOT datagrid plugins, pleas...

How do I insert multiple checkbox values into a table?

I cant seem to find or figure out a working solution to insert multiple checkbox values from a form into a table. The closes I have come is inserting the value of merely one checkbox value into a table. Kindly point out how I can insert multiple chec...

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

I'm trying to do an application reading pdf using pdf kit in Xcode 4.3 but it gives me the following error ld: duplicate symbol _OBJC_METACLASS_$_OverlayManager in /Users/dt4it/Library/Developer/Xcode/DerivedData/MyPdf4-bmkjglhhvneluqcbwpceiqjvdcmq...

how to use font awesome in own css?

I'm using bootstrap and Font Awesome. In a custom css class I'm working on I tried to include Font Awesome icons instead of using images. Here is my code before Font Awesome. .data .close { display: block; float: right; width: 30px; height: ...

IIS Express Windows Authentication

I'm trying to use IIS Express with VS2010 to host a silverlight application. I modified my applicationhost.config file to allow for modification of the proper configuration settings. I have the following in my web.config: <location path=""> ...

How to split a delimited string in Ruby and convert it to an array?

I have a string "1,2,3,4" and I'd like to convert it into an array: [1,2,3,4] How?...

Extracting extension from filename in Python

Is there a function to extract the extension from a filename?...

R dates "origin" must be supplied

My code: axis.Date(1,sites$date, origin="1970-01-01") Error: Error in as.Date.numeric(x) : 'origin' must be supplied Why is it asking me for the origin when I supplied it in the above code?...

What's the difference between console.dir and console.log?

In Chrome the console object defines two methods that seem to do the same thing: console.log(...) console.dir(...) I read somewhere online that dir takes a copy of the object before logging it, whereas log just passes the reference to the console,...

'^M' character at end of lines

When I run a particular SQL script in Unix environments, I'm am seeing a '^M' character at the end of each line of the SQL script as it is echoed to the command-line. I don't know on which OS the SQL script was originally created. What is causing t...

Android ListView in fragment example

Where can I find an example of using ListView in Fragment? I know that there is an example in samples, but unfortunately I could not find it. Maybe you can suggest something?...

Find multiple files and rename them in Linux

I am having files like a_dbg.txt, b_dbg.txt ... in a Suse 10 system. I want to write a bash shell script which should rename these files by removing "_dbg" from them. Google suggested me to use rename command. So I executed the command rename _dbg.t...

Loop through properties in JavaScript object with Lodash

Is it possible to loop through the properties in a JavaScript object? For instance, I have a JavaScript object defined as this: myObject.options = { property1: 'value 1', property2: 'value 2' }; Properties will get dynamically added to this ob...

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

I have a problem with Java Persistence API and Hibernate. My situation of project is: My persistence.xml file is: <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-inst...

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

I'm coming from iOS where it's easy and you simply use a UIViewController. However, in Android things seem much more complicated, with certain UIComponents for specific API Levels. I'm reading BigNerdRanch for Android (the book is roughly 2 years old...

How do you get current active/default Environment profile programmatically in Spring?

I need to code different logic based on different current Environment profile. How can you get the currently active and default profiles from Spring?...

Re-render React component when prop changes

I'm trying to separate a presentational component from a container component. I have a SitesTable and a SitesTableContainer. The container is responsible for triggering redux actions to fetch the appropriate sites based on the current user. The prob...

jquery get all input from specific form

Is there any ways to populate all of the input from certain form? let say, some thing like this: <form id="unique00"> <input type="text" name="whatever" id="whatever" value="whatever" /> <div> <input type="checkbox" name...

Get individual query parameters from Uri

I have a uri string like: http://example.com/file?a=1&b=2&c=string%20param Is there an existing function that would convert query parameter string into a dictionary same way as ASP.NET Context.Request does it. I'm writing a console app and ...

java.io.IOException: Invalid Keystore format

Does anyone know how to solve this? I tried many things, but none of them worked. And when I click more details I get this: at sun.security.provider.JavaKeyStore.engineLoad(Unknown Source) atsun.security.provider.JavaKeyStore$JKS.engineLoad(Unknown...

How do I `jsonify` a list in Flask?

Currently Flask would raise an error when jsonifying a list. I know there could be security reasons https://github.com/mitsuhiko/flask/issues/170, but I still would like to have a way to return a JSON list like the following: [ {'a': 1, 'b': 2}...

Detect when an image fails to load in Javascript

Is there a way to determine if a image path leads to an actual image, Ie, detect when an image fails to load in Javascript. For a web app, I am parsing a xml file and dynamically creating HTML images from a list of image paths. Some image paths may ...

Append key/value pair to hash with << in Ruby

In Ruby, one can append values to existing arrays using <<: a = [] a << "foo" but, can you also append key/value pairs to an existing hash? h = {} h << :key "bar" I know you can do: h[:key] = "" h[:key] << "bar" but t...

C# - Print dictionary

I have made a dictionary which contains two values a DateTime and a string. Now I want to print everything from the dictionary to a Textbox. Does anybody know how to do this. I have used this code to print the dictionary to the console: private void...

SimpleDateFormat parsing date with 'Z' literal

I am trying to parse a date that looks like this: 2010-04-05T17:16:00Z This is a valid date per http://www.ietf.org/rfc/rfc3339.txt. The 'Z' literal (quote) "imply that UTC is the preferred reference point for the specified time." If I try to ...

Closure in Java 7

What is closure? It is supposed to be included in Java 7. (Closures were discussed for inclusion in Java 7, but in the end were not included. -ed) Can anyone please provide me with some reliable references from where I can learn stuff about closures...

javascript jquery radio button click

I have 2 radio buttons and jquery running. <input type="radio" name="lom" value="1" checked> first <input type="radio" name="lom" value="2"> second Now, with a button I can set onClick to run a function. What is the way to make radio ...

How do I test if a variable does not equal either of two values?

I want to write an if/else statement that tests if the value of a text input does NOT equal either one of two different values. Like this (excuse my pseudo-English code): var test = $("#test").val(); if (test does not equal A or B){ do stuff; }...

Change bootstrap datepicker date format on select

I'm using bootstrap datepicker on a textbox. The default format of the date when you select a date is mm/dd/yyyy. Now I want to change it to dd/mm/yyyy. How can I accomplish this. Right now I'm just initializing it just like this. $('.datepicker')....

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

Java is an optional package on the latest versions of macOS. Yet once installed it appears like the JAVA_HOME environment variable is not set properly....

equivalent to push() or pop() for arrays?

I am trying to add, remove and reference items from an array I create in my main java file, but I am having trouble figuring out the correct syntax. In actionscript they have push() and pop() for adding and removing items in an array, is there an eq...

Image is not showing in browser?

<body style="background-color: paleturquoise"> <h2 style="color: red">Duke's soccer League: Home Page<br/></h2> <ul style="list-style-type: circle"> <li style="font-size: larger"><a href="league_...

How to change default text color using custom theme?

What I'm trying should be quite easy with themes, but I can't find out how to: I want all text to be white by default in my app. I created a custom theme in theme.xml: <style name="Theme" parent="@android:Theme"> </style> <style name...

QtCreator: No valid kits found

Installed just the IDE on Windows 7. I want to create a Plain C++ Project (Non-QT Project); however I get an error: No valid kits found. When I click on Options->Kits, I see the Desktop (default) kit, and it shows no errors. Am I getting the err...

Fetch: POST json data

I'm trying to POST a JSON object using fetch. From what I can understand, I need to attach a stringified object to the body of the request, e.g.: fetch("/echo/json/", { headers: { 'Accept': 'application/json', 'Content-Type': 'appli...

How do I mount a remote Linux folder in Windows through SSH?

I'm a blind student currently in a system admin/shell programming class. Although ssh works fine for executing commands like ls, pwd, etc editors do not work well with my screen reader and an ssh session. I was wondering if it is possible to mount a ...

How to enter a series of numbers automatically in Excel

I have so many records but I need to enter serial numbers automatically in Excel 2007. I have hundreds of records. Instead of entering them manually I want them to show up automatically. Please give me short example for 1 to 10....

How to change progress bar's progress color in Android

I'm using an horizontal progress bar in my Android application, and I want to change its progress color (which is Yellow by default). How can I do it using code (not XML)?...

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

I am trying to create soft links between config files containing server blocks in the sites-enabled and sites-available directories in /etc/nginx/. The command I am using is: sudo ln -s sites-available/foo.conf sites-enabled/ When I then execute:...

Docker: Multiple Dockerfiles in project

How do you organize the Dockerfiles belonging to a project when you have one Dockerfile for the database, one for the application server, and so on? Do you create some sort of hierachy in the source? A big enterprise project can't consist of only one...

Tracking changes in Windows registry

Is there a way to track changes in Windows registry? I'd like to see what changes in the registry are made during installation of various programs. ...

Database design for a survey

I need to create a survey where answers are stored in a database. I'm just wondering what would be the best way to implement this in the database, specifically the tables required. The survey contains different types of questions. For example: text f...

What is MVC and what are the advantages of it?

I found What are mvp and mvc and what is the difference but it didn't really answer this question. I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked eas...

Base64 PNG data to HTML5 canvas

I want to load a PNG image encoded in Base64 to canvas element. I have this code: <html> <head> </head> <body> <canvas id="c"></canvas> <script type="text/javascript"> var canvas = document.getElementById("...

When to use the different log levels

There are different ways to log messages, in order of fatality: FATAL ERROR WARN INFO DEBUG TRACE How do I decide when to use which? What's a good heuristic to use?...

How to push files to an emulator instance using Android Studio

How am I able to push .txt files to the emulator using Android Studio?...

Is it possible to create static classes in PHP (like in C#)?

I want to create a static class in PHP and have it behave like it does in C#, so Constructor is automatically called on the first call to the class No instantiation required Something of this sort... static class Hello { private static $gree...

How to define multiple CSS attributes in jQuery?

Is there any syntactical way in jQuery to define multiple CSS attributes without stringing everything out to the right like this: $("#message").css("width", "550px").css("height", "300px").css("font-size", "8pt"); If you have, say, 20 of these you...

Swift's guard keyword

Swift 2 introduced the guard keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates an submitTapped function: func submitTapped() { guard username.text.characters.count &...

Is log(n!) = T(n·log(n))?

I am to show that log(n!) = T(n·log(n)). A hint was given that I should show the upper bound with nn and show the lower bound with (n/2)(n/2). This does not seem all that intuitive to me. Why would that be the case? I can definitely see how to c...

How to test that no exception is thrown?

I know that one way to do it would be: @Test public void foo() { try { // execute code that you expect not to throw Exceptions. } catch(Exception e) { fail("Should not have thrown any exception"); } } Is there any clea...

Opening Android Settings programmatically

How can I open settings programmatically?...

Add carriage return to a string

I have a long string. string s1 = "'99024','99050','99070','99143','99173','99191','99201','99202','99203','99204','99211','99212','99213','99214','99215','99217','99218','99219','99221','99222','99231','99232','99238','99239','99356','99357','99371...

Disable future dates after today in Jquery Ui Datepicker

I want to disable all the future dates after today in Jquery Ui Datepicker Here is the Demo : Code : $( "#start_date" ).datepicker( { maxDate: '0', beforeShow : function() { jQuery( t...

Illegal mix of collations error in MySql

Just got this answer from a previous question and it works a treat! SELECT username, (SUM(rating)/COUNT(*)) as TheAverage, Count(*) as TheCount FROM ratings WHERE month='Aug' GROUP BY username HAVING TheCount > 4 ORDER BY TheAverage DESC, TheCou...

Printing 2D array in matrix format

I have a 2D array as follows: long[,] arr = new long[4, 4] {{ 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 }}; I want to print the values of th...

td widths, not working?

So I have this code here: <table> <tr> <td width="200px" valign="top"> <div class="left_menu"> <div class="menu_item"> <a href="#">Home</a> ...

How do I escape ampersands in batch files?

How do I escape ampersands in a batch file (or from the Windows command line) in order to use the start command to open web pages with ampersands in the URL? Double quotes will not work with start; this starts a new command-line window instead. ...

Can I specify maxlength in css?

Can I replace the maxlength attribute with something in CSS? <input type='text' id="phone_extension" maxlength="4" /> ...

diff to output only the file names

I'm looking to run a Linux command that will recursively compare two directories and output only the file names of what is different. This includes anything that is present in one directory and not the other or vice versa, and text differences....

How to dismiss the dialog with click on outside of the dialog?

I have implemented a custom dialog for my application. I want to implement that when the user clicks outside the dialog, the dialog will be dismissed. What do I have to do for this?...

Find the location of a character in string

I would like to find the location of a character in a string. Say: string = "the2quickbrownfoxeswere2tired" I would like the function to return 4 and 24 -- the character location of the 2s in string. ...

Repository access denied. access via a deployment key is read-only

After successfully cloning my repo from heroku and added another remote 1/ git clone [email protected]:[APP].git 2/ git remote add bitbucket ssh://[email protected]/[ACCOUNT]/[REPO].git 3/ git push bitbucket master I am still getting this error after...

How to fix IndexError: invalid index to scalar variable

This code generates error: IndexError: invalid index to scalar variable. at the line: results.append(RMSPE(np.expm1(y_train[testcv]), [y[1] for y in y_test])) How to fix it? import pandas as pd import numpy as np from sklearn import ensemble fro...

The opposite of Intersect()

Intersect can be used to find matches between two collections, like so: // Assign two arrays. int[] array1 = { 1, 2, 3 }; int[] array2 = { 2, 3, 4 }; // Call Intersect extension method. var intersect = array1.Intersect(array2); // Write intersection...

difference between new String[]{} and new String[] in java

I am fresher in java ,i have a doubt in java that is String array= new String[]{}; what is the use of { } here ? what is the difference between String array=new String[]; and String array=new String[]{}; when I am writing String array=new String...

Java 8 stream map on entry set

I'm trying to perform a map operation on each entry in a Map object. I need to take a prefix off the key and convert the value from one type to another. My code is taking configuration entries from a Map<String, String> and converting to a Map...

No provider for Http StaticInjectorError

I am trying to pull the data from my api, and populate it in my ionic app, but it is crashing when I enter the page the data should be populated on. Below are my two .ts files: import { Component } from '@angular/core'; import { NavController, Loa...

How to uninstall Apache with command line

So I'm trying to find a command to uninstall apache from windows that I have installed earlier with an NSIS script. Basically apache is part of a package of aplications we use for our program, and when uninstalling our program we uninstall them all....

How to get controls in WPF to fill available space?

Some WPF controls (like the Button) seem to happily consume all the available space in its' container if you don't specify the height it is to have. And some, like the ones I need to use right now, the (multiline) TextBox and the ListBox seem more w...

C#: How do you edit items and subitems in a listview?

How do you edit items and subitems in a listview? Let's say I have a listview with 3 columns,and subitems, Car Brand | Car Name | Car Year Ford | Mustang | 2000 Dodge | Charger | 2007 How would I Add items like that to listview and how...

How do you get the file size in C#?

I need a way to get the size of a file using C#, and not the size on disk. How is this possible? Currently I have this loop foreach (FileInfo file in downloadedMessageInfo.GetFiles()) { //file.Length (will this work) } Will this return the si...

When is it appropriate to use C# partial classes?

I was wondering if someone could give me an overview of why I would use them and what advantage I would gain in the process....

MVC Razor view nested foreach's model

Imagine a common scenario, this is a simpler version of what I'm coming across. I actually have a couple of layers of further nesting on mine.... But this is the scenario Theme contains List Category contains List Product contains List My Control...

Hibernate SessionFactory vs. JPA EntityManagerFactory

I am new to Hibernate and I'm not sure whether to use a Hibernate SessionFactory or a JPA EntityManagerFactory to create a Hibernate Session. What is the difference between these two? What are the pros & cons of using each of those?...

XmlDocument - load from string?

protected void Page_Load(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); try { string path = Server.MapPath("."); doc.Load(path+"whatever.xml"); } catch (Exception ex) { lblError.Text...

Difference between Console.Read() and Console.ReadLine()?

I'm new to this field and I'm very confused: what is the real difference between Console.Read() and Console.ReadLine()?...

window.location.href doesn't redirect

I know this is a question much discussed but I can't figure out why it does not work for me. This is my function: function ShowComments(){ alert("fired"); var movieShareId = document.getElementById('movieId'); //alert("found div" + movieShareId...

Any way to exit bash script, but not quitting the terminal

When I use exit command in a shell script, the script will terminate the terminal (the prompt). Is there any way to terminate a script and then staying in the terminal? My script run.sh is expected to execute by directly being sourced, or sourced fr...

'python' is not recognized as an internal or external command

So I have recently installed Python Version 2.7.5 and I have made a little loop thing with it but the problem is, when I go to cmd and type python testloop.py I get the error: 'python' is not recognized as an internal or external command I hav...

Check if a record exists in the database

I am using these lines of code to check if the record exists or not. SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn); int UserExist = (int)check_User_Name.ExecuteScalar(); ...

How can I execute a python script from an html button?

I have a number of python scripts that I have saved on my computer, out of curiosity I have created a html file that just has one button. Instead on going into the terminal and running python <path to script>, I would like to make it so when th...

Getting path relative to the current working directory?

I'm writing a console utility to do some processing on files specified on the commandline, but I've run into a problem I can't solve through Google/Stack Overflow. If a full path, including drive letter, is specified, how do I reformat that path...

How to create a connection string in asp.net c#

I am working on asp.net c# project, for connection I used: SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"); but I want to get this conn...

Transpose a range in VBA

I am Trying to Transpose a range of cells in Excel through VBA macro but I am getting some errors, mostly Error 91. I am pretty new to VBA and don't have much idea about functions either. Range(InRng).Select Set Range1 = Selection Dim DestRange As...

What is difference between functional and imperative programming languages?

Most of the mainstream languages, including object-oriented programming (OOP) languages such as C#, Visual Basic, C++, and Java were designed to primarily support imperative (procedural) programming, whereas Haskell/gofer like languages are purely fu...

How to get user name using Windows authentication in asp.net?

I want to get user name using Windows authentication Actually I implemented "Sign in as different user",when click this button Windows security will appear there we can give credentials. In that time if I give some other credential it is taking cur...

Rails: How can I set default values in ActiveRecord?

How can I set default value in ActiveRecord? I see a post from Pratik that describes an ugly, complicated chunk of code: http://m.onkey.org/2007/7/24/how-to-set-default-values-in-your-model class Item < ActiveRecord::Base def initialize_with...

How to check visibility of software keyboard in Android?

I need to do a very simple thing - find out if the software keyboard is shown. Is this possible in Android?...

Update multiple rows in same query using PostgreSQL

I'm looking to update multiple rows in PostgreSQL in one statement. Is there a way to do something like the following? UPDATE table SET column_a = 1 where column_b = '123', column_a = 2 where column_b = '345' ...

How to resize array in C++?

I need to do the equivalent of the following C# code in C++ Array.Resize(ref A, A.Length - 1); How to achieve this in C++?...

Is there a difference between PhoneGap and Cordova commands?

I just installed Phonegap for the first time and just browsed through the docs. What confuses me is the fact that some docs are using the command "phonegap" and some "cordova". Android platform guide: $ cordova create hello com.example.hello "Hello...

How can I test that a variable is more than eight characters in PowerShell?

How do test if the number of characters in $dbUserName is more than eight characters? I have been unable to locate a command or series of commands that will let me do this. I have only been able to find if the variable is null: if ($dbUserName) { ...

How to export library to Jar in Android Studio?

I have downloaded some library sources and would like to export it as a Jar file using Android Studio. Is there a way to export to jar file using Android studio ? edit: The library I want to export as jar is an Android library. It's called "Stand...

mysql_config not found when installing mysqldb python interface

I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:, python setup.py install I get the ...

How to get the Google Map based on Latitude on Longitude?

I want to display Google map in my web page based on longitude and latitude. First user want to enter longitude and latitude in two text box's. Then click submit button I have to display appropriate location in Google map.And also I want to show the ...

Capturing mobile phone traffic on Wireshark

How can I capture mobile phone traffic on Wireshark?...

Reset identity seed after deleting records in SQL Server

I have inserted records into a SQL Server database table. The table had a primary key defined and the auto increment identity seed is set to “Yes”. This is done primarily because in SQL Azure, each table has to have a primary key and identity def...

Check if int is between two numbers

Why can't do you this if you try to find out whether an int is between to numbers: if(10 < x < 20) Instead of it, you'll have to do if(10<x && x<20) which seems like a bit of overhead....

Generate a sequence of numbers in Python

How can I generate the sequence of numbers "1,2,5,6,9,10......" and so until 100 in Python? I even need the comma (',') included, but this is not the main problem. The sequence: every number from 1..100, divisible by 4 with remainder 1 or 2....

SQL Server Group By Month

I have a table which has this schema ItemID UserID Year IsPaid PaymentDate Amount 1 1 2009 0 2009-11-01 300 2 1 2009 0 2009-12-01 342 3 1 2010 0 2010-01-...

Git - Undo pushed commits

I have a project in a remote repository, synchronized with a local repository (development) and the server one (prod). I've been making some commited changes already pushed to remote and pulled from the server. Now, I want to undo those changes. So I...

Simple GUI Java calculator

I am building a simple GUI Java calculator. I have an issue finding a package or figuring out a method to do the actual calculation. So far I've figured that when I do a math operation, the number in the text box gets saved in a temporary location. ...

What is a callback function?

What is a callback function?...

Installing TensorFlow on Windows (Python 3.6.x)

I'm trying to install TensorFlow on Windows. I tried to install it with pip, but I always get the same error message: ... is not a supported wheel on this platform. I first tried it with Python 3.5.1, now I upgraded to 3.6.0b4, but it makes no di...

Invalid Host Header when ngrok tries to connect to React dev server

I'm trying to test my React application on a mobile device. I'm using ngrok to make my local server available to other devices and have gotten this working with a variety of other applications. However, when I try to connect ngrok to the React dev se...

Insert variable values in the middle of a string

In C#: If I want to create a message like this: "Hi We have these flights for you: Flight A,B,C,D. Which one do you want" where just the section in bold is dynamic and I pass its value at run time, but its left and right parts are fixed. I can creat...

Is there any native DLL export functions viewer?

Is there any free native Windows DLL export functions viewer, which shows the function name, and a list of their parameters?...

How can I enable CORS on Django REST Framework

How can I enable CORS on my Django REST Framework? the reference doesn't help much, it says that I can do by a middleware, but how can I do that?...

How to write data to a JSON file using Javascript

For example, I have a .JSON file that has the following: [{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}] What would be the javascript code to push another object {"nissan": "sentra", "color": "green"} into this .json arra...

CSS selector for a checked radio button's label

Is it possible to apply a css(3) style to a label of a checked radio button? I have the following markup: <input type="radio" id="rad" name="radio"/> <label for="rad">A Label</label> What I was hoping is that label:checked { f...

Keeping it simple and how to do multiple CTE in a query

I have this simple T-SQL query, it emits a bunch of columns from a table and also joins information from other related tables. My data model is simple. I have a scheduled event, with participants. I need to know how many participants participate in ...

Sending websocket ping/pong frame from browser

I keep reading about ping/pong messages in websockets to keep the connection alive, but I'm not sure what they are. Is it a distinct frame type? (I don't see any methods on a javascript WebSocket object in chrome related to ping-pong). Or is it jus...

How to redirect docker container logs to a single file?

I want to redirect all the logs of my docker container to single log file to analyse them. I tried docker logs container > /tmp/stdout.log 2>/tmp/stderr.log but this gives log in two different file. I already tried docker logs container &...

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetim...

Return outside function error in Python

This is the problem: Given the following program in Python, suppose that the user enters the number 4 from the keyboard. What will be the value returned? N = int(input("enter a positive integer:")) counter = 1 while (N > 0): counter = counte...

Open a URL without using a browser from a batch file

I want to open a particular URL without directly opening the browser using only a batch file. I know I can use something like: START www.google.com But I want to open a URL without using a browser. Is this possible? The reason is that I have to o...

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

How can I convert a NodeJS binary buffer into a JavaScript ArrayBuffer?...

Skip the headers when editing a csv file using Python

I am using below referred code to edit a csv using Python. Functions called in the code form upper part of the code. Problem: I want the below referred code to start editing the csv from 2nd row, I want it to exclude 1st row which contains headers....

How do I change the title of the "back" button on a Navigation Bar

Currently the left bar button default value is the title of the view that loaded the current one, in other words the view to be shown when the button is pressed (back button). I want to change the text shown on the button to something else. I tried...

What is the difference between Modal and Push segue in Storyboards?

Can someone explain to me what is the exact difference between modal and push segue? I know that when we use push the segue gets added to a stack, so when we keep using push it keeps occupying memory? Can someone please show me how these two are i...

Copy struct to struct in C

I want to copy an identical struct into another and later on use it as a comparance to the first one. The thing is that my compiler gives me a warning when Im doing like this! Should I do it in another way or am I doing this wrong: In header File: ...

Find html label associated with a given input

Let's say I have an html form. Each input/select/textarea will have a corresponding <label> with the for attribute set to the id of it's companion. In this case, I know that each input will only have a single label. Given an input element in ...

What does -XX:MaxPermSize do?

Specifically, why would it help to fix a PermGen OutOfMemoryError issue? Also, bonus points for an answer that points me to the documentation on JVM arguments......

How can I scale an entire web page with CSS?

Using Firefox, you can enlarge an entire web page by simply pressing CTRL +. What this does is proportionally enlarge the entire web page (fonts, images, etc). How can I replicate the same functionality using simply CSS? Is there something like pag...

include antiforgerytoken in ajax post ASP.NET MVC

I am having trouble with the AntiForgeryToken with ajax. I'm using ASP.NET MVC 3. I tried the solution in jQuery Ajax calls and the Html.AntiForgeryToken(). Using that solution, the token is now being passed: var data = { ... } // with token, key is...

How can I disable the default console handler, while using the java logging API?

Hi I am trying to implement the java logging in my application. I want to use two handlers. A file handler and my own console handler. Both of my handlers work fine. My logging is send to a file and to the console . My logging is also sent to the de...

DateTime group by date and hour

I have a datetime called activity_dt and the data looks like this: 2/5/2013 9:24:00 AM 2/7/2013 7:17:00 AM How do i group by date and hour?...

Import functions from another js file. Javascript

I have a question about including a file in javascript. I have a very simple example: --> index.html --> models --> course.js --> student.js course.js: function Course() { this.id = ''; this.name = ''; } A stud...

Python and pip, list all versions of a package that's available?

Given the name of a Python package that can be installed with pip, is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version for a third party libra...

How do I POST urlencoded form data with $http without jQuery?

I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS. I am trying to make an AJAX call to the server side, using $http from my Angular App. For sending the parameters, I tried the following: $http({ ...

SQL Server - NOT IN

I need to build a query that will show me records that are in Table 1, but that are not in Table 2, based on the make-model-serial number combination. I know for fact that there are 4 records that differ, but my query always comes back blank. SELE...

Doing a cleanup action just before Node.js exits

I want to tell Node.js to always do something just before it exits, for whatever reason — Ctrl+C, an exception, or any other reason. I tried this: process.on('exit', function (){ console.log('Goodbye!'); }); I started the process, killed it...

Golang append an item to a slice

Why does the slice a remain the same? Does append() generate a new slice? package main import ( "fmt" ) var a = make([]int, 7, 8) func Test(slice []int) { slice = append(slice, 100) fmt.Println(slice) } func main() { for i := 0; ...

Why ModelState.IsValid always return false in mvc

In my controller this code: [HttpPost] public ActionResult Edit(Company company, FormCollection IsCostCenters) { if (ModelState.IsValid) { Company objNewCompany = new Company(); ...

Properties private set;

I know it only allows the class to set it, but what is the point? How do I solve the problem of having readonly ids? Say I have a person class: public class Person { public string Name { get; set; } public int Id { get; privat...

Get original URL referer with PHP?

I am using $_SERVER['HTTP_REFERER']; to get the referer Url. It works as expected until the user clicks another page and the referer changes to the last page. How do I store the original referring Url?...

MVC Razor @foreach

I heard that having @foreach inside of a view is a no-no. Meaning, the view should not have any logic in it. What is the best practice on where the logic for the @foreach should be at? @foreach.. ...

Extract substring using regexp in plain bash

I'm trying to extract the time from a string using bash, and I'm having a hard time figuring it out. My string is like this: US/Central - 10:26 PM (CST) And I want to extract the 10:26 part. Anybody knows of a way of doing this only with bash - ...

WSDL validator?

Is there any online service available to validate Web Service WSDL file?...

Get most recent row for given ID

In the table below, how do I get just the most recent row with id=1 based on the signin column, and not all 3 rows? +----+---------------------+---------+ | id | signin | signout | +----+---------------------+---------+ | 1 | 2011-12-12...

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

I'm trying to setup a Amazon Linux AMI(ami-f0091d91) and have a script that runs a copy command to copy from a S3 bucket. aws --debug s3 cp s3://aws-codedeploy-us-west-2/latest/codedeploy-agent.noarch.rpm . This script works perfectly on my local...

Standard way to embed version into python package?

Is there a standard way to associate version string with a python package in such way that I could do the following? import foo print foo.version I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/majo...

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

I keep receiving this error when I do some Ajax calls... It may even be something to do with Geocoding but I really have no idea how to capture the error to display something useful to users... or even how to solve the problem as it seems to just be...

Is there a way to make Firefox ignore invalid ssl-certificates?

I am maintaining a few web applications. The development and qa environments use invalid/outdated ssl-certificates. Although it is generally a good thing, that Firefox makes me click like a dozen times to accept the certificate, this is pretty annoy...

port forwarding in windows

I have two network board in my pc: The main one has the local ip -> 192.168.1.111 The secondary ones has the local ip -> 192.168.0.200 The main one has internet connection and the second one is connected to a device with the IP 192.168.0.33, it has...

Difference between break and continue statement

Can anyone tell me the difference between break and continue statements?...

How do I catch an Ajax query post error?

I would like to catch the error and show the appropriate message if the Ajax request fails. My code is like the following, but I could not manage to catch the failing Ajax request. function getAjaxData(id) { $.post("status.ajax.php", {deviceId...

python numpy vector math

What is the numpy equivalent to euclid's 2d vector classes / operations ? ( like: euclid.Vector2 ) So far I have this. Create two vectors import numpy as np loc = np.array([100., 100.]) vel = np.array([30., 10]) loc += vel # reseting speed to a...

sorting a vector of structs

I have a vector<data> info where data is defined as: struct data{ string word; int number; }; I need to sort info by the length of the word strings. Is there a quick and simple way to do it?...

How to get href value using jQuery?

I'm trying to get href value using jQuery: <html> <head> <title>Jquery Test</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script ty...

How to change sa password in SQL Server 2008 express?

I have installed SQL Server 2008 express and logging in through windows authentication, it doesn't allow me to do anything. How do i change 'sa' password or gain full privilege in my local computers 2008 express ? I am using windows 7....

Sending email with PHP from an SMTP server

$from = "[email protected]"; $headers = "From:" . $from; echo mail ("[email protected]" ,"testmailfunction" , "Oj",$headers); I have trouble sending email in PHP. I get an error: SMTP server response: 530 SMTP authentication is required. I...

How to disable anchor "jump" when loading a page?

I think this may not be possible, will try and explain as best as I can. I have a page containing tabs (jquery powered), controlled by the following: I'm using this code, as provided by another user from a previous question. <script type="text/j...

Angular ng-click with call to a controller function not working

I need to pass a variable to another controller. I have the following code which is related to the ListCtrl : <a href="#items" data-router="article" ng-click="changeListName('metro')"> The link is going to another controller, ItemCtrl. I wa...

Resource leak: 'in' is never closed

Why does Eclipse give me the warming "Resource leak: 'in' is never closed" in the following code? public void readShapeData() { Scanner in = new Scanner(System.in); System.out.println("Enter the width of the Rectangle: "); wi...

android TextView: setting the background color dynamically doesn't work

Setting the background color programatically of an android TextView doesn't seem to work. I'm I missing something! TextView et = new TextView(activity); et.setText("350"); et.setBackgroundColor(R.color.white); I also have this file (colors.xml) in...

Appending to an empty DataFrame in Pandas?

Is it possible to append to an empty data frame that doesn't contain any indices or columns? I have tried to do this, but keep getting an empty dataframe at the end. e.g. df = pd.DataFrame() data = ['some kind of data here' --> I have checked t...

How to scroll to top of a div using jQuery?

I have a gridview inside a div.. I want to scroll to top of the div from the bottom of the div using jquery.. Any suggestion.. <div id="GridDiv"> // gridview inside.. </div> My gridview will have custom pagination generated link button...

Remove last item from array

I have the following array. var arr = [1,0,2]; I would like to remove the last element i.e. 2. I used arr.slice(-1); but it doesn't remove the value....

How to check if an element does NOT have a specific class?

How do I check if there isn't a class. For example, I know how to check to see if it has the class "test", but how do I check to see if it doesn't have the class "test"? if($(this).hasClass("test")){ } ...

Calling async method on button click

I created Windows Phone 8.1 project and I am trying to run async method GetResponse(string url) on button click and waiting for the method to finish, but method is never finishing. Here is my code: private void Button_Click(object sender, RoutedEven...

A valid provisioning profile for this executable was not found... (again)

I know this has been asked and answered multiple times but I'm tearing my hair out as none of the proposed solutions appears to work. I receive the above error, despite having a valid provisioning profile which, as far as I can tell matches the bu...

How to specify a min but no max decimal using the range data annotation attribute?

I would like to specify that a decimal field for a price must be >= 0 but I don't really want to impose a max value. Here's what I have so far...I'm not sure what the correct way to do this is. [Range(typeof(decimal), "0", "??"] public decimal Pric...

java : convert float to String and String to float

How could I convert from float to string or string to float? In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated. String valueFromTable = "25"; Float valueCalcula...

How to convert all elements in an array to integer in JavaScript?

I am getting an array after some manipulation. I need to convert all array values as integers. My sample code var result_string = 'a,b,c,d|1,2,3,4'; result = result_string.split("|"); alpha = result[0]; count = result[1]; // console.log(alpha); // ...

Best way to represent a fraction in Java?

I'm trying to work with fractions in Java. I want to implement arithmetic functions. For this, I will first require a way to normalize the functions. I know I can't add 1/6 and 1/2 until I have a common denominator. I will have to add 1/6 and 3/6...

How to fix "'System.AggregateException' occurred in mscorlib.dll"

I'm receiving an unhandled exception while debugging, and the program stops executing. The debugger doesn't show me the line so I don't know what to fix. An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll Add...

Running Facebook application on localhost

I am planning to connect to Facebook chat from my localhost. I will need to get the session key from Facebook. When I give the site URL as localhost:8080 or ip-address:8080 it does not work. I read about setting up two apps with 2 different API key...

How to animate CSS Translate

Is it possible to animate the CSS property translate via jquery? $('.myButtons').animate({"transform":"translate(50px,100px)"}) and does it work in many browsers? Demo not working: http://jsfiddle.net/ignaciocorreia/xWCVf/ UPDATE: My solutions...

Quickest way to find missing number in an array of numbers

I have an array of numbers from 1 to 100 (both inclusive). The size of the array is 100. The numbers are randomly added to the array, but there is one random empty slot in the array. What is the quickest way to find that slot as well as the number t...

Write variable to file, including name

Let's say I have the following dictionary in a small application. dict = {'one': 1, 'two': 2} What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have ...

What is a bus error?

What does the "bus error" message mean, and how does it differ from a segfault?...

curl: (6) Could not resolve host: google.com; Name or service not known

when I try to load a web page to terminal it gives curl: (6) Could not resolve host error. I have internet in my PC and trying from my home internet connection. So as I there is no any proxy involve here. [root@localhost kevin]# curl http://googl...

Get the current year in JavaScript

How do I get the current year in JavaScript?...

openssl s_client -cert: Proving a client certificate was sent to the server

Background I am stuck in a finger-pointing match with a service provider with an API protected by SSL server and client certificates. I have generated a CSR, obtained a certificate from a public CA (GoDaddy in this case) and provided the certific...

Split value from one field to two

I've got a table field membername which contains both the last name and the first name of users. Is it possible to split those into 2 fields memberfirst, memberlast? All the records have this format "Firstname Lastname" (without quotes and a space ...

How can I adjust DIV width to contents

I have a div element with style attached: .mypost { border: 1px solid Peru; font-family: arial; margin: auto; min-width: 700px; width: 700px; } I am diplaying WordPress post contents inside the DIV block but for simplicity let ...

Moving x-axis to the top of a plot in matplotlib

Based on this question about heatmaps in matplotlib, I wanted to move the x-axis titles to the top of the plot. import matplotlib.pyplot as plt import numpy as np column_labels = list('ABCD') row_labels = list('WXYZ') data = np.random.rand(4,4) fig,...

Drop shadow on a div container?

I have a searchbox with auto-suggest that pops a div up underneath it with multiple search string suggestions (like google). Is it possible to have drop shadow on the auto-suggest box with CSS or will I need a script of some sort? I tried a backgro...

What __init__ and self do in Python?

I'm learning the Python programming language and I've came across something I don't fully understand. In a method like: def method(self, blah): def __init__(?): .... .... What does self do? What is it meant to be? Is it mandato...

Mapping a JDBC ResultSet to an object

I have a user class that has 16 attributes, things such as firstname, lastname, dob, username, password etc... These are all stored in a MySQL database and when I want to retrieve users I use a ResultSet. I want to map each of the columns back to the...

How to read an external properties file in Maven

Does anyone know how to read a x.properties file in Maven. I know there are ways to use resource filtering to read a properties file and set values from that, but I want a way in my pom.xml like: <properties file="x.properties"> </propert...

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

The executable was signed with invalid entitlements. The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile.(0xE8008016). I am getting this error. please help me. I ...

Is it possible to read the value of a annotation in java?

this is my code: @Column(columnName="firstname") private String firstName; @Column(columnName="lastname") private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.fir...

How do you convert between 12 hour time and 24 hour time in PHP?

I have a time as a string, for example: $time = '5:36 pm'; I require this to be in 24 hour format (i.e. 17:36), however I don't know which functions I need to use to convert it. Please help....

Selecting multiple columns/fields in MySQL subquery

Basically, there is an attribute table and translation table - many translations for one attribute. I need to select id and value from translation for each attribute in a specified language, even if there is no translation record in that language. Ei...

In C#, how to check whether a string contains an integer?

I just want to know, whether a String variable contains a parsable positive integer value. I do NOT want to parse the value right now. Currently I am doing: int parsedId; if ( (String.IsNullOrEmpty(myStringVariable) || (!uint.TryParse(mySt...

Python math module

Whenever I try to use any of the built-in functions of Python's exponentiation and logarithms module, I get an error like this: NameError: name 'sqrt' is not defined I have tried using math.sqrt(4),sqrt(4) and sqrt(4.0), but none of them work. Th...

What is the Python equivalent of static variables inside a function?

What is the idiomatic Python equivalent of this C/C++ code? void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } specifically, how does one implement the static member at the function level, as opposed ...

Change one value based on another value in pandas

I'm trying to reprogram my Stata code into Python for speed improvements, and I was pointed in the direction of PANDAS. I am, however, having a hard time wrapping my head around how to process the data. Let's say I want to iterate over all values i...

"RangeError: Maximum call stack size exceeded" Why?

If I run Array.apply(null, new Array(1000000)).map(Math.random); on Chrome 33, I get RangeError: Maximum call stack size exceeded Why?...

How to implement static class member functions in *.cpp file?

Is it possible to implement static class member functions in *.cpp file instead of doing it in the header file ? Are all static functions always inline?...

java.net.URL read stream to byte[]

I`m trying to read an image from an URL (with the java package java.net.URL) to a byte[]. "Everything" works fine, except that the content isnt being enterely read from the stream (the image is corrupt, it doesnt contain all the image data)... The b...

How do I specify unique constraint for multiple columns in MySQL?

I have a table: table votes ( id, user, email, address, primary key(id), ); Now I want to make the columns user, email, address unique (together). How do I do this in MySql? Of course the example is just... an example. So ple...