Examples On Programing Languages

jQuery text() and newlines

I want to be able to say $(someElem).text('this\n has\n newlines); and it renders with newlines in the browser. The only workaround I have found is to set the css property 'white-space' to 'pre' on someElem. This almost works, but then I have an ...

Remove local git tags that are no longer on the remote repository

We use tags in git as part of our deployment process. From time to time, we want to clean up these tags by removing them from our remote repository. This is pretty straightforward. One user deletes the local tag and the remote tag in one set of co...

Integration Testing POSTing an entire object to Spring MVC controller

Is there a way to pass an entire form object on mock request when integration testing a spring mvc web app? All I can find is to pass each field separately as a param like this: mockMvc.perform(post("/somehwere/new").param("items[0].value","value"))...

How to Generate unique file names in C#

I have implemented an algorithm that will generate unique names for files that will save on hard drive. I'm appending DateTime: Hours,Minutes,Second and Milliseconds but still it generates duplicate name of files because im uploading multiple files a...

window.open target _self v window.location.href?

I need to redirect the user using JavaScript. Which is the preferred method? window.open("webpage.htm", "_self"); or window.location.href = "webpage.htm"; ...

Query to display all tablespaces in a database and datafiles

How to write a query to display all tablespaces in database suppose db and it's corresponding datafiles belong to user SCOTT. I can connect to SCOTT account and see it but I like to connect to sys as sysdba to see all tablespaces and datafiles belong...

How to insert a string which contains an "&"

How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database. I'm not sure if it makes a difference, but I'm using Oracle 9i....

What should main() return in C and C++?

What is the correct (most efficient) way to define the main() function in C and C++ — int main() or void main() — and why? And how about the arguments? If int main() then return 1 or return 0? There are numerous duplicates of this question, incl...

GROUP BY to combine/concat a column

I have a table as follow: ID User Activity PageURL 1 Me act1 ab 2 Me act1 cd 3 You act2 xy 4 You act2 st I want to group by User and Activity such that I end up with something like: User ...

Git On Custom SSH Port

My VPS provider recommends that I leave my SSH port to the custom port number they assign it by default (not 22). The thing is the while I know I can give the port number when create a remote config, it seems like I can't do the same when doing a gi...

Why is printing "B" dramatically slower than printing "#"?

I generated two matrices of 1000 x 1000: First Matrix: O and #. Second Matrix: O and B. Using the following code, the first matrix took 8.52 seconds to complete: Random r = new Random(); for (int i = 0; i < 1000; i++) { for (int j = 0; j &l...

How do I remove time part from JavaScript date?

I have a date '12/12/1955 12:00:00 AM' stored in a hidden column. I want to display the date without the time. How do I do this?...

How to center cell contents of a LaTeX table whose columns have fixed widths?

Consider the following piece of LaTeX code: \begin{tabular}{p{1in}p{1in}} A & B\\ C & D\\ \end{tabular} How can I make the contents of each cell aligned in the center of the cell rather than the left? Note that I want to make sure that t...

__init__ and arguments in Python

I want to understand arguments of the constructor __init__ in Python. class Num: def __init__(self,num): self.n = num def getn(self): return self.n def getone(): return 1 myObj = Num(3) print myObj.getn() RESUL...

substring of an entire column in pandas dataframe

I have a pandas dataframe "df". In this dataframe I have multiple columns, one of which I have to substring. Lets say the column name is "col". I can run a "for" loop like below and substring the column: for i in range(0,len(df)): df.iloc[i].col =...

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

I have a little "floating tool box" - a div with position:fixed; overflow:auto. Works just fine. But when scrolling inside that box (with the mouse wheel) and reaching the bottom OR top, the parent element "takes over" the "scroll request" : The doc...

How do I POST with multipart form data using fetch?

I am fetching a URL like this: fetch(url, { mode: 'no-cors', method: method || null, headers: { 'Accept': 'application/json, application/xml, text/plain, text/html, *.*', 'Content-Type': 'multipart/form-data' }, body: JSON.stringif...

Hive load CSV with commas in quoted fields

I am trying to load a CSV file into a Hive table like so: CREATE TABLE mytable ( num1 INT, text1 STRING, num2 INT, text2 STRING ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ","; LOAD DATA LOCAL INPATH '/data.csv' OVERWRITE INTO TABLE mytable; ...

Difference between one-to-many and many-to-one relationship

What is the real difference between one-to-many and many-to-one relationship? It is only reversed, kind of? I can't find any 'good-and-easy-to-understand' tutorial about this topic other than this one: SQL for Beginners: Part 3 - Database Relationsh...

Invalid application of sizeof to incomplete type with a struct

I have a struct where I put all the information about the players. That's my struct: struct player{ int startingCapital; int currentCapital; int startingPosition; int currentPosition; int activePlayer; int canPlay; }; And...

Throwing multiple exceptions in a method of an interface in java

I wanted to ask that how to mention this in my interface public class find(int x) throws A_Exception, B_Exception{ ---- ---- --- } i want to say that i can mention One exception in an interface but how to mention in my interface that my method wi...

How to find out which processes are using swap space in Linux?

Under Linux, how do I find out which process is using the swap space more?...

How to get arguments with flags in Bash

I know that I can easily get positioned parameters like this in bash: $0 or $1 I want to be able to use flag options like this to specify for what each parameter is used: mysql -u user -h host What is the best way to get -u param value and -h pa...

Placing/Overlapping(z-index) a view above another view in android

I have a linear layout which consists of imageview and textview , one below another in a linear layout. <LinearLayout android:orientation="horizontal" ... > <ImageView android:id="@+id/thumbnail" android:layout_weight="0.8" ...

How to find tags with only certain attributes - BeautifulSoup

How would I, using BeautifulSoup, search for tags containing ONLY the attributes I search for? For example, I want to find all <td valign="top"> tags. The following code: raw_card_data = soup.fetch('td', {'valign':re.compile('top')}) gets ...

Difference between "or" and || in Ruby?

What's the difference between the or and || operators in Ruby? Or is it just preference?...

How to center text vertically with a large font-awesome icon?

Lets say I have a bootstrap button with a font-awesome icon and some text: <div> <i class='icon icon-2x icon-camera'></i> hello world </div> How do I make text appear vertically centered? Text is aligned with the bo...

Why powershell does not run Angular commands?

I have started to learn Angular but I note that powershell in Windows gives me an error whenever I make an angular command like: ng new new-app or ng serve this is the error what I got: ng : File C:\Users\< username >\AppData\Roaming\npm...

Python For loop get index

I am writing a simple Python for loop to prnt the current character in a string. However, I could not get the index of the character. Here is what I have, does anyone know a good way to get the current index of the character in the loop? loopme = '...

How to set the component size with GridLayout? Is there a better way?

I am working on a larger GUI with Java and I am becoming angry on Layout Managers. I have a "Settings-Panel" with a variable number of JComponents in it (Labels, Buttons, JSpinners, JSliders,...). I just want the following: JLabel <-> JComponen...

LINQ order by null column where order is ascending and nulls should be last

I'm trying to sort a list of products by their price. The result set needs to list products by price from low to high by the column LowestPrice. However, this column is nullable. I can sort the list in descending order like so: var products = fr...

ant warning: "'includeantruntime' was not set"

I receive the following warning: [javac] build.xml:9: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds What does this mean?...

npm install won't install devDependencies

On windows for some reason when I run npm install it won't install devDependencies. AFAIK it should. If I run npm install --dev devDependencies are installed. I don't understand why npm install doesn't install devDependencies too, but installs only d...

Calling a JavaScript function returned from an Ajax response

I have a system where I send an Ajax command, which returns a script block with a function in it. After this data is correctly inserted in the DIV, I want to be able to call this function to perform the required actions. Is this possible?...

Merging 2 branches together in GIT

I've only just started to use GIT and think its wonderful, however I'm a little confused over what the merge command does. Let us say we have a working project in the branch "A". I go home and make changes to this branch and save it as "B". Another...

Inner join with count() on three tables

Simple and fast question, i have those tables: //table people | pe_id | pe_name | | 1 | Foo | | 2 | Bar | //orders table | ord_id | pe_id | ord_title | | 1 | 1 | First order | | 2 | 2 | Order two | | 3 | 2 | Third ...

Excel VBA Open a Folder

Using 2010 Excel VBA - I'm just trying to open a folder through a sub. What am I doing wrong here? VBA Sub openFolder() Dim preFolder As String, theFolder As String, fullPath as String theFolder = Left(Range("T12").Value, 8) preFolder ...

Git push requires username and password

I cloned a Git repository from my GitHub account to my PC. I want to work with both my PC and laptop, but with one GitHub account. When I try to push to or pull from GitHub using my PC, it requires a username and password, but not when I'm using th...

What is a pre-revprop-change hook in SVN, and how do I create it?

I wanted to edit a log comment in the repository browser and received an error message that no pre-revprop-change hook exists for the repository. Besides having a scary name, what is a pre-revprop-change hook, and how do I create it?...

How to run SUDO command in WinSCP to transfer files from Windows to linux

I am trying to use WinSCP to transfer files over to a Linux Instance from Windows. Im using private key for my instance to login to Amazon instance using ec2-user. However ec2-user does not have access to write to the Linux instance How do i sudo...

How to do the equivalent of pass by reference for primitives in Java

This Java code: public class XYZ { public static void main(){ int toyNumber = 5; XYZ temp = new XYZ(); temp.play(toyNumber); System.out.println("Toy number in main " + toyNumber); } void pla...

How to redirect single url in nginx?

I'm in the process of reorganizing url structure. I need to setup redirect rules for specific urls - I'm using NGINX. Basically Something like this: http://example.com/issue1 --> http://example.com/shop/issues/custom_issue_name1 http://exampl...

Get the size of a 2D array

Okay, so I have a 2D array z[50][50] and z's size is therefore 50 * 50, but if I say z.length I only get 50 back. How do I get the real size of a 2D array?...

Bash command line and input limit

Is there some sort of character limit imposed in bash (or other shells) for how long an input can be? If so, what is that character limit? I.e. Is it possible to write a command in bash that is too long for the command line to execute? If there is n...

How can I add a vertical scrollbar to my div automatically?

I want to add a vertical scrollbar to my <div>. I've tried overflow: auto, but it is not working. I've tested my code in Firefox and Chrome. I'm pasting the div style code here: float: left; width: 1000px; overflow: auto; ...

Pandas Merging 101

How to perform a (INNER| (LEFT|RIGHT|FULL) OUTER) JOIN with pandas? How do I add NaNs for missing rows after merge? How do I get rid of NaNs after merging? Can I merge on the index? How do I merge multiple DataFrames? Cross join with pandas? merge? ...

How to recognize vehicle license / number plate (ANPR) from an image?

I have a web site that allows users to upload images of cars and I would like to put a privacy filter in place to detect registration plates on the vehicle and blur them. The blurring is not a problem but is there a library or component (open source...

Execute jar file with multiple classpath libraries from command prompt

I have a Maven project which generates a jar file and copies all dependencies to target/lib folder. I want to execute this project on client's machine (windows). So, I copied myproject.jar to C:\xyz folder and all dependencies to C:\xyz\lib folder....

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

I want to capture the Ctrl+C (SIGINT) signal sent from the console and print out some partial run totals. Is this possible in Golang? Note: When I first posted the question I was confused about Ctrl+C being SIGTERM instead of SIGINT....

PHP 7: Missing VCRUNTIME140.dll

I have an error when I start PHP 7 on Windows. When I run php on the command line, it returns a message box with system error: The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling the program to fi...

Parsing Json rest api response in C#

I am trying to pull a value from a rest api json response using C#. I have the following code: client.BaseUrl = "https://api.cloud.appcelerator.com"; request.Resource = "/v1/chats/create.json?key=" + cac.AppCode.ToString(); request.Method = Method....

Where is GACUTIL for .net Framework 4.0 in windows 7?

i've made an assembly in the .net framework that I intend to publish to the GAC but I can't find the gacutil utlity. I've been googling a while and I've found a lot of suggestions, but nothing works: Copy the assemby to %window%\assemby [DOES NOT ...

How to get the Android Emulator's IP address?

I want to get the currently running Android Emulator's IP address through code. How can it be achieved?...

How to get htaccess to work on MAMP

I am trying to get the .htaccess working in MAMP. The content of the .htaccess is a simple redirect line but it does not work. I am trying to manipulate URLs of a WordPress page, so I added the .htaccess file in my theme folder, but it is not workin...

Getting last day of the month in a given string date

My input string date is as below: String date = "1/13/2012"; I am getting the month as below: SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); Date convertedDate = dateFormat.parse(date); String month = new SimpleDateFormat("MM")...

How can I get nth element from a list?

How can I access a list by index in Haskell, analog to this C code? int a[] = { 34, 45, 56 }; return a[1]; ...

How do I validate a date in rails?

I want to validate a date in my model in Ruby on Rails, however, the day, month and year values are already converted into an incorrect date by the time they reach my model. For example, if I enter February 31st 2009 in my view, when I use Model.new...

libstdc++.so.6: cannot open shared object file: No such file or directory

I want to run Cilkscreen command with a cilk++ program but I'v got this error /usr/local/cilk/bin/../lib32/pinbin: error while loading shared libraries: libstdc++.so.6: cannot open shared object file: No such file or directory Can you help...

macro for Hide rows in excel 2010

I'm kinda new to programming in VBA. I read some stuff on the internet but I couldnt find what I need or couldnt get it working. My problem: in worksheet 'sheet 1' in cell B6 a value is given for how many years a project will be exploited. in workshe...

Eclipse error: 'Failed to create the Java Virtual Machine'

I am getting this error message when I start Eclipse Helios on Windows 7: Failed to create the Java Virtual Machine My eclipse.ini looks as follows: -startup plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar -vm P:\Programs\jdk1.6\bin...

Powershell get ipv4 address into a variable

Is there an easy way in powershell 3.0 Windows 7 to get the local computer's ipv4 address into a variable?...

Getting request payload from POST request in Java servlet

I have a javascript library that is sending a POST request to my Java servlet, but in the doPost method, I can't seem to get the contents of the request payload. In chrome Developer Tools, all the content is in the Request Payload section in the head...

Are vectors passed to functions by value or by reference in C++

I'm coding in C++. If I have some function void foo(vector<int> test) and I call it in my program, will the vector be passed by value or reference? I'm unsure because I know vectors and arrays are similar and that a function like void bar(int t...

Getting content/message from HttpResponseMessage

I'm trying to get content of HttpResponseMessage. It should be: {"message":"Action '' does not exist!","success":false}, but I don't know, how to get it out of HttpResponseMessage. HttpClient httpClient = new HttpClient(); HttpResponseMessage respon...

move a virtual machine from one vCenter to another vCenter

I have the following problem: There two separate vCenters (ESXi). They cannot see each other or communicate in any way. I can create a Clone of a VM in vCenter1 but then I want to move that Clone in vCenter2. Is there a way that I can copy the Clon...

Retrieving subfolders names in S3 bucket from boto3

Using boto3, I can access my AWS S3 bucket: s3 = boto3.resource('s3') bucket = s3.Bucket('my-bucket-name') Now, the bucket contains folder first-level, which itself contains several sub-folders named with a timestamp, for instance 1456753904534. ...

Finding Android SDK on Mac and adding to PATH

I have installed Android Studio on my MacBook Air (OS Version 10.11 El Capitan) and have successfully written a small "hello, world" app and installed on device (Nexus 7) and ran on AVD. All I want to do now is be able to build the app and install i...

Oracle SQL: Use sequence in insert with Select Statement

Basically I want to run the following query: INSERT INTO historical_car_stats (historical_car_stats_id, year, month, make, model, region, avg_msrp, count) SELECT my_seq.nextval, '2010', '12', 'ALL', 'ALL', region, sum(a...

Remove special symbols and extra spaces and replace with underscore using the replace method

I want to remove all special characters and spaces from a string and replace with an underscore. The string is var str = "hello world & hello universe"; I have this now which replaces only spaces: str.replace(/\s/g, "_"); The resu...

Changing ViewPager to enable infinite page scrolling

Jon Willis has posted on how to enable an infinite scrolling with his code. In there he said that he made some changes in the ViewPager class int the android support library. Which changes have been made and how is it possible to "recompile" the libr...

How to make a simple popup box in Visual C#?

When I click a button, I want a box to popup on the screen and display a simple message. Nothing fancy really. How would I do that?...

In Java, how to find if first character in a string is upper case without regex

In Java, find if the first character in a string is upper case without using regular expressions....

How to export SQL Server 2005 query to CSV

I want to export some SQL Server 2005 data to CSV format (comma-separated with quotes). I can think of a lot of complicated ways to do it, but I want to do it the right way. I've looked at bcp, but I can't figure out how to put the quotes around the ...

How do I align a number like this in C?

I need to align a series of numbers in C with printf() like this example: -------1 -------5 ------50 -----100 ----1000 Of course, there are numbers between all those but it's not relevant for the issue at hand... Oh, consider the dashes as spaces,...

How do I kill a VMware virtual machine that won't die?

I've got a virtual machine running on a server that I can't stop or reboot - I can't log onto it anymore and I can't stop it using the VMware server console. There are other VM's running so rebooting the host is out of the question. Is there any oth...

C++11 rvalues and move semantics confusion (return statement)

I'm trying to understand rvalue references and move semantics of C++11. What is the difference between these examples, and which of them is going to do no vector copy? First example std::vector<int> return_vector(void) { std::vector<int&...

Convert this string to datetime

Possible Duplicate: PHP: Convert uncommon date format to timestamp in most efficient manner possible? How to convert this string to datetime format? 06/Oct/2011:19:00:02 I tried this but it doesn't work. $s = '06/Oct/2011:19:00:02'; $da...

Javascript to export html table to Excel

I need to export the html table in my page to an Excel when user clicks 'Export' button. Now, I found a solution here on stack overflow that works in Firefox. Export dynamic html table to excel in javascript in firefox browser Now, it doesn't handl...

Why I get 'list' object has no attribute 'items'?

Using Python 2.7, I have this list: qs = [{u'a': 15L, u'b': 9L, u'a': 16L}] I'd like to extract values out of it. i.e. [15, 9, 16] So I tried: result_list = [int(v) for k,v in qs.items()] But instead, I get this error: Traceback (most recen...

Convert PEM traditional private key to PKCS8 private key

I've been given a PEM file with a certificate and pub/private keys. Specifically it includes the headers -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- -----BEGIN RSA ...

Multiple conditions in a C 'for' loop

I came across this piece of code. I generally use '&&' or '||' to separate multiple conditions in a for loop, but this code uses commas to do that. Surprisingly, if I change the order of the conditions the output varies. #include<stdio.h...

Load a UIView from nib in Swift

Here is my Objective-C code which I'm using to load a nib for my customised UIView: -(id)init{ NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"myXib" owner:self options:nil]; return [subviewArray objectAtIndex:0]; } What is...

jquery datatables hide column

Is there a way with the jquery datatables plugin to hide (and show) a table column? I figured out how to reload the table data: using fnClearTable and fnAddData. But my issue is that in one of my views for the table (e.g. a hidden mode) I don't wan...

Maven dependencies are failing with a 501 error

Recently Maven build jobs running in Jenkins are failing with the below exception saying that they couldn't pull dependencies from Maven Central and should use HTTPS. I'm not sure how to change the requests from HTTP to HTTPS. Could someone guide me ...

Impact of Xcode build options "Enable bitcode" Yes/No

Yesterday I recognized a ton of warnings regarding the parse.com library: URGENT: all bitcode will be dropped because '[path]/Parse.framework/Parse(PFAnalytics.o)' was built without bitcode. You must rebuild it with bitcode enabled (Xcode settin...

Can Python test the membership of multiple values in a list?

I want to test if two or more values have membership on a list, but I'm getting an unexpected result: >>> 'a','b' in ['b', 'a', 'foo', 'bar'] ('a', True) So, Can Python test the membership of multiple values at once in a list? What does t...

How to run a PowerShell script without displaying a window?

How is it possible to run a PowerShell script without displaying a window or any other sign to the user? In other words, the script should run quietly in the background without any sign to the user. Extra credit for an answer that does not use thir...

SQL Server Insert if not exists

I want to insert data into my table, but insert only data that doesn't already exist in my database. Here is my code: ALTER PROCEDURE [dbo].[EmailsRecebidosInsert] (@_DE nvarchar(50), @_ASSUNTO nvarchar(50), @_DATA nvarchar(30) ) AS BEGIN ...

Add a Progress Bar in WebView

I am trying to add a progress/loading bar to my application that uses WebView. I am confused on how to implement a progress bar that appears every time a link is clicked. Current code: public class CULearnBrowser extends Activity { WebView web...

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

Sometimes and especially very often when developing a web-application Chrome doesn't allow you to visit certain sites and throwing certificate/HSTS error. I've found that typing badidea (more recently thisisunsafe) in Chrome window will tell Chrome t...

What's the difference between using "let" and "var"?

ECMAScript 6 introduced the let statement. I've heard that it's described as a local variable, but I'm still not quite sure how it behaves differently than the var keyword. What are the differences?. When should let be used instead of var?...

Initialize a byte array to a certain value, other than the default null?

I'm busy rewriting an old project that was done in C++, to C#. My task is to rewrite the program so that it functions as close to the original as possible. During a bunch of file-handling the previous developer who wrote this program creates a str...

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...

Python Pandas : pivot table with aggfunc = count unique distinct

df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']}) X Y Z 0 X1 Y2 Z3 1 X1 Y1 Z1 2 X1 Y1 Z1 3 X1 Y1 Z2 g=df2.groupby('X') pd.pivot_table(g, values='X', rows='Y', cols='Z...

Access to Image from origin 'null' has been blocked by CORS policy

I have JavaScript application in OpenLayers 3, and my base layer is created from local tiles. I work only in my computer so I do not know why I have CORS error. var newLayer = new ol.layer.Tile({ source: new ol.source.OSM({ url: 'E:/...

Do not want scientific notation on plot axis

I regularly do all kinds of scatter plots in R using the plot command. Sometimes both, sometimes only one of the plot axes is labelled in scientific notation. I do not understand when R makes the decision to switch to scientific notation. Surprising...

How to add number of days to today's date?

I need to be able to add 1, 2 , 5 or 10 days to today's date using jQuery....

How can I specify the schema to run an sql file against in the Postgresql command line

I run scripts against my database like this... psql -d myDataBase -a -f myInsertFile.sql The only problem is I want to be able to specify in this command what schema to run the script against. I could call set search_path='my_schema_01' but the f...

ASP.NET MVC - Set custom IIdentity or IPrincipal

I need to do something fairly simple: in my ASP.NET MVC application, I want to set a custom IIdentity / IPrincipal. Whichever is easier / more suitable. I want to extend the default so that I can call something like User.Identity.Id and User.Identity...

How to lock specific cells but allow filtering and sorting

I'm using the following code to lock the content of certain cells Sub LockCell(ws As Worksheet, strCellRng As String) With ws .Unprotect .Cells.Locked = False .Range(strCellRng).Locked = True .Protect Contents:=True, AllowFormattingCel...

Importing CSV data using PHP/MySQL

I'm having a bit of a problem trying to import data from a CSV and have a couple of questions on it that I haven't managed to solve myself yet. First off here's my code to help put things in perspective (tidied it up a bit, removing CSS and DB conne...

How to order events bound with jQuery

Lets say I have a web app which has a page that may contain 4 script blocks - the script I write may be found in one of those blocks, but I do not know which one, that is handled by the controller. I bind some onclick events to a button, but I find...

How do I create a HTTP Client Request with a cookie?

I've got a node.js Connect server that checks the request's cookies. To test it within node, I need a way to write a client request and attach a cookie to it. I understand that HTTP Requests have the 'cookie' header for this, but I'm not sure how t...

How do I check out a specific version of a submodule using 'git submodule'?

How would I go about adding a Git submodule for a specific tag or commit?...

Calling a class method raises a TypeError in Python

I don't understand how classes are used. The following code gives me an error when I try to use the class. class MyStuff: def average(a, b, c): # Get the average of three numbers result = a + b + c result = result / 3 ret...

How to pass a type as a method parameter in Java

In Java, how can you pass a type as a parameter (or declare as a variable)? I don't want to pass an instance of the type but the type itself (eg. int, String, etc). In C#, I can do this: private void foo(Type t) { if (t == typeof(String)) { ...

What does the "@" symbol do in Powershell?

I've seen the @ symbol used in PowerShell to initialise arrays. What exactly does the @ symbol denote and where can I read more about it?...

Asp.net - Add blank item at top of dropdownlist

Why is the dropdown not showing my blank item first? Here is what I have drpList.Items.Add(New ListItem("", "")) With drpList .DataSource = myController.GetList(userid) .DataTextField = "Name" .DataValueField = "ID" .DataBind() End ...

Maven 3 warnings about build.plugins.plugin.version

Since I updated to Maven 3 I get the following warning messages at each build : How can I get rid of these warnings? [INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for proj:id:...

How do I keep the screen on in my App?

For my Android app I never want the phone to lock or the back light to turn off...

Pretty Printing JSON with React

I'm using ReactJS and part of my app requires pretty printed JSON. I get some JSON like: { "foo": 1, "bar": 2 }, and if I run that through JSON.stringify(obj, null, 4) in the browser console, it pretty prints, but when I use it in this react snipp...

How to get value in the session in jQuery

I'm a beginner in jQuery. I want to set the values in an HTML page and I have to get them in another HTML page. Here is the piece of code I am trying now: To set the value in session: $.session.set(userName, $("#uname").val()); To get the valu...

How to upload files in asp.net core?

How to upload files or images using Asp.net MVC 6 with some model data? Example, I have a form like this; <form> <input type="file"> <input type="text" placeholder="Image name..."> <input type="text" placeholder="Ima...

Google Chrome display JSON AJAX response as tree and not as a plain text

I cannot find an answer to this one: My AJAX calls return JSON data. In Google Chrome Developer Tools > Resources > XHR when I click on the resource on the left and then on the Content tab I see the JSON string as a string and not as a tree as Fireb...

What is the difference between #include <filename> and #include "filename"?

In the C and C++ programming languages, what is the difference between using angle brackets and using quotes in an include statement, as follows? #include <filename> #include "filename" ...

Converting string to byte array in C#

I'm converting something from VB into C#. Having a problem with the syntax of this statement: if ((searchResult.Properties["user"].Count > 0)) { profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]); } I the...

How to convert milliseconds to "hh:mm:ss" format?

I'm confused. After stumbling upon this thread, I tried to figure out how to format a countdown timer that had the format hh:mm:ss. Here's my attempt - //hh:mm:ss String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), Time...

String replace a Backslash

How can I do a string replace of a back slash. Input Source String: sSource = "http://www.example.com\/value"; In the above String I want to replace "\/" with a "/"; Expected ouput after replace: sSource = "http://www.example.com/value"; I ge...

IIS Express gives Access Denied error when debugging ASP.NET MVC

I have created an ASP.NET MVC 3 project, and am using IIS Express as the web server when developing. When I try to debug, I get the error message below. How can this be solved? Server Error in '/' Application. Access is denied. Descriptio...

How to get a list of images on docker registry v2

I'm using docker registry v1 and I'm interested in migrating to the newer version, v2. But I need some way to get a list of images present on registry; for example with registry v1 I can execute a GET request to http://myregistry:5000/v1/search? and ...

Draw Circle using css alone

Is it possible to draw circle using css only which can work on most of the browsers (IE,Mozilla,Safari) ?...

add new row in gridview after binding C#, ASP.net

I want to add a new blank row to the gridview after binding as seen in the picture when clicking the link button below. The textboxes inside the gridview should remain the same if there is any data entered in it. just want to add one row. please he...

Delete an element in a JSON object

I am trying to loop through a list of objects deleting an element from each object. Each object is a new line. I am trying to then save the new file as is without the element contained within the objects. I know this is probably a simple task but I c...

XSLT getting last element

I am trying to find the last element in my xml, which looks like: <list> <element name="A" /> <element name="B" > <element name="C" /> <element name=...

SET NAMES utf8 in MySQL?

I often see something similar to this below in PHP scripts using MySQL query("SET NAMES utf8"); I have never had to do this for any project yet so I have a couple basic questions about it. Is this something that is done with PDO only? If it...

This action could not be completed. Try Again (-22421)

I am trying to upload an Apple TV App to the App Store for testing purposes, but I got the issue: This Action could not be completed. Try Again (-22421) as in the below image: So what can I do?...

Convert integer to string Jinja

I have an integer {% set curYear = 2013 %} In {% if %} statement I have to compare it with some string. I can't set curYear to string at the beginning because I have to decrement it in loop. How can I convert it?...

Open a local HTML file using window.open in Chrome

I want to open a local HTML file through Javascript using: window.open ("file://C:/Users/wins/Desktop/exclusiveWordpress.html","mywindow"); But it is opening a new window with a blank page as we used to get when URL is not specified. How do I achi...

Is there any sizeof-like method in Java?

Is there any built-in method in Java to find the size of any datatype? Is there any way to find size?...

How do I save a String to a text file using Java?

In Java, I have text from a text field in a String variable called "text". How can I save the contents of the "text" variable to a file?...

JPA getSingleResult() or null

I have an insertOrUpdate method which inserts an Entity when it doesn't exist or update it if it does. To enable this, I have to findByIdAndForeignKey, if it returned null insert if not then update. The problem is how do I check if it exists? So I tr...

What’s the best way to check if a file exists in C++? (cross platform)

I have read the answers for What's the best way to check if a file exists in C? (cross platform), but I'm wondering if there is a better way to do this using standard c++ libs? Preferably without trying to open the file at all. Both stat and access...

How can I unstage my files again after making a local commit?

I have executed the following command git add <foo.java> git commit -m "add the foo.java file" How can I delete my local commit now and unstage foo.java? If I type git reset --hard, I found that it reverts my modified foo.java to the origin...

HTML form input tag name element array with JavaScript

This is a two part question. Someone answered a similar question the other day (which also contained info about this type of array in PHP), but I cannot find it. 1.) First off, what is the correct terminology for an array created on the end of the ...

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("...

Swift presentViewController

I programatically have multiple View Controllers in an iOS Swift Project. I do not have the storyboards and would like to avoid them if possible. Is there a way to switch to another viewcontroller.swift file (We will call it view2.swift) and have it ...

Can't import my own modules in Python

I'm having a hard time understanding how module importing works in Python (I've never done it in any other language before either). Let's say I have: myapp/__init__.py myapp/myapp/myapp.py myapp/myapp/SomeObject.py myapp/tests/TestCase.py Now I'm...

Difference between window.location.href and top.location.href

Can Anyone tell me the difference between window.location.href and top.location.href ? And also where to use which one. And which one will be better when redirecting after an ajax call in mvc?...

Laravel - Pass more than one variable to view

I have this site and one of its pages creates a simple list of people from the database. I need to add one specific person to a variable I can access. How do I modify the return $view->with('persons', $persons); line to also pass the $ms variable...

Codeigniter : calling a method of one controller from other

I have two controllers a and b. I would like to call a method of controller a from a method of controller b. Could anyone help explain how I can achieve this?...

IOError: [Errno 13] Permission denied

I have this piece of code to create a .json file to store python data. When i run it in my server i get this error: IOError: [Errno 13] Permission denied: 'juliodantas2015.json' at line with open(output_file, 'wb') as fp: Python code: fich_input=...

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Long ago, I installed 32-bit Oracle SQL Developer 2.1 on a Windows XP (32-bit) machine. I have since moved to Windows 7 (64-bit) and copied the SQL Developer 2.1 from the old machine onto the new one. When I try to run sqldeveloper.exe, I get the fo...

How would you make a comma-separated string from a list of strings?

What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's'...

Where does the iPhone Simulator store its data?

I have a SQLite DB that I'm using to store app data, and I could do with taking a look inside it to debug a problem I'm having - but where does the iPhone Simulator store its data, typically?...

Find a file in python

I have a file that may be in a different place on each user's machine. Is there a way to implement a search for the file? A way that I can pass the file's name and the directory tree to search in?...

Counting unique values in a column in pandas dataframe like in Qlik?

If I have a table like this: df = pd.DataFrame({ 'hID': [101, 102, 103, 101, 102, 104, 105, 101], 'dID': [10, 11, 12, 10, 11, 10, 12, 10], 'uID': ['James', 'Henry', 'Abe', 'James', 'Henry', 'Brian', 'Claude', 'James'], ...

PHP page redirect

Can PHP make a redirect call after executing a function? I am creating a function on the completion of which I want it to redirect to a file located in the same root folder. Can it be done? if (...) { // I am using echo here. } else if ($_SESS...

Copy file from source directory to binary directory using CMake

I'm trying to create a simple project on CLion. It uses CMake (I'm new here) to generate Makefiles to build project (or some sort of it) All I need to is transfer some non-project file (some sort of resource file) to binary directory each time when ...

Git submodule update

I'm not clear on what the following means (from the Git submodule update documentation): ...will make the submodules HEAD be detached, unless --rebase or --merge is specified... How does --rebase/--merge change things? My main use case is to h...

How connect Postgres to localhost server using pgAdmin on Ubuntu?

I installed Postgres with this command sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev Using psql --version on terminal I get psql (PostgreSQL) 9.3.4 then I installed pgadmin with sudo apt-get install pgadmin3 La...

What is the difference between bindParam and bindValue?

What is the difference between PDOStatement::bindParam() and PDOStatement::bindValue()?...

How can I select all options of multi-select select box on click?

This is my HTML <select name="countries" id="countries" MULTIPLE size="8"> <option value="UK">UK</option> <option value="US">US</option> <option value="Canada">Canada</option> <option value="F...

How to set DateTime to null

Using C#. I have a string dateTimeEnd. If the string is in right format, I wish to generate a DateTime and assign it to eventCustom.DateTimeEnd of type public Nullable<System.DateTime> DateTimeEnd { get; set; } If dateTimeEnd is null or em...

Handling the window closing event with WPF / MVVM Light Toolkit

I'd like to handle the Closing event (when a user clicks the upper right 'X' button) of my window in order to eventually display a confirm message or/and cancel the closing. I know how to do this in the code-behind: subscribe to the Closing event of...

SQL Server find and replace specific word in all rows of specific column

I have a table TblKit that has columns Id and Number. Id is primary key of type int and Number is varchar(50). The data in the table looks like this: Id Number --- ------ 1 KIT001 2 KIT002 3 DMB001 4 DM002 5 KIT003 I...

switch case statement error: case expressions must be constant expression

My switch-case statement works perfectly fine yesterday. But when I run the code earlier this morning eclipse gave me an error underlining the case statements in color red and says: case expressions must be constant expression, it is constant I don't...

shorthand c++ if else statement

So I'm just curious if there is a short hand statement to this: if(number < 0 ) bigInt.sign = 0; else bigInt.sign = 1; I see all these short hand statements for if a < b and such. I'm not sure on how to do it properly and would like som...

Can you get the number of lines of code from a GitHub repository?

In a GitHub repository you can see “language statistics”, which displays the percentage of the project that’s written in a language. It doesn’t, however, display how many lines of code the project consists of. Often, I want to quickly get an ...

Spring get current ApplicationContext

I am using Spring MVC for my web application. My beans are written in "spring-servlet.xml" file Now I have a class MyClass and i want to access this class using spring bean In the spring-servlet.xml i have written following <bean id="myClass" c...

html5 input for money/currency

I seem unable to work out what to use for accepting monetary values on a form. I have tried... <input type="number" min="0" max="10000" step="1" name="Broker_Fees" id="broker_fees" required="required"> But that then won't allow for pence en...

Token based authentication in Web API without any user interface

I am developing a REST API in ASP.Net Web API. My API will be only accessible via non-browser based clients. I need to implement security for my API so I decided to go with Token based authentication. I have a fair understanding of token based authen...

Eclipse java debugging: source not found

While debugging a java app in eclipse I receive a "Source not found" error in two cases: Stepping in to a file in a different project which is already imported Stepping in to a file in an installed maven repository The files are there, but eclips...

In Oracle, is it possible to INSERT or UPDATE a record through a view?

In Oracle, is it possible to INSERT or UPDATE a record (a row) through a view?...

Increase JVM max heap size for Eclipse

I am trying to increase the max heap size for my Eclipse. I have tried specifying in eclipse.ini or through the command line, but are not working. My max heap size has the exact same limit before (running jconsole) and after (System.out.println(jav...

CSS3 transition on click using pure CSS

I'm trying to get an image (a plus symbol) to rotate 45 degrees to create a cross symbol. I have so far managed to achieve this using the code below but its working on hover, I wanted to have it rotate on click. Is there a simple way of doing so us...

on change event for file input element

I have 4 file inputs that I want them trigger upload proccess when their value is changed. I mean when you select a picture and click open on select image dialog, the script to upload the picture be triggered. I've used onchange event but I think thi...

What is the difference between Document style and RPC style communication?

Can somebody explain to me the differences between Document and RPC style webservices? Apart from JAX-RPC, the next version is JAX-WS, which supports both Document and RPC styles. I also understand document style webservices are meant for Asynchrono...

How to handle change of checkbox using jQuery?

I have some code <input type="checkbox" id="chk" value="value" /> <label for="chk">Value </label> <br/> <input type="button" id="But1" value="set value" /> <br /> <input type="button" id="But2" value="read chec...

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

I have created tables in MySQL Workbench as shown below : ORDRE table: CREATE TABLE Ordre ( OrdreID INT NOT NULL, OrdreDato DATE DEFAULT NULL, KundeID INT DEFAULT NULL, CONSTRAINT Ordre_pk PRIMARY KEY (OrdreID), CONSTRAINT Ordre_fk F...

MVVM: Tutorial from start to finish?

I'm a C#/Windows Forms programmer with more than 5 years experience. I've been investigating WPF using the MVVM (Model-View-ViewModel) design pattern. I have searched the Internet for tutorials. I have even watched the entirety of Jason Dolinger's aw...

XML Carriage return encoding

I was looking to represent a carriage return within an xml node. I have tried a whitespace preserve, hex entity with no luck- and a \n. viewing via a browser. Example <Quote> Alas, poor Yorick! I knew him </Quote> Thanks....

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 ...

Forking / Multi-Threaded Processes | Bash

I would like to make a section of my code more efficient. I'm thinking of making it fork off into multiple processes and have them execute 50/100 times at once, instead of just once. For example (pseudo): for line in file; do foo; foo2; foo3; don...

Skip to next iteration in loop vba

I am trying to create a simple conditional loop that will go to the next iteration if a condition is true. The code I have so far is: For i = 2 To 24 Level = Cells(i, 4) Return = Cells(i, 5) If Return = 0 And Level = 0 Then 'Go t...

How to add "active" class to wp_nav_menu() current menu item (simple way)

I am creating custom Wordpress theme using a starter theme _Underscores. I am also using Bootstrap as a front-end framework. I would like to modify wp_nav_menu so that it assigns current menu item class="active" instead of class="current-menu-item" ...

How to stop a function

For example: def main(): if something == True: player() elif something_else == True: computer() def player(): # do something here check_winner() # check something computer() # let the computer do something def...

How to pass arguments to Shell Script through docker run

I am new to the docker world. I have to invoke a shell script that takes command line arguments through a docker container. Ex: My shell script looks like: #!bin/bash echo $1 Dockerfile looks like this: FROM ubuntu:14.04 COPY ./file.sh / CMD /bin...

Make: how to continue after a command fails?

The command $ make all gives errors such as rm: cannot remove '.lambda': No such file or directory so it stops. I want it to ignore the rm-not-found-errors. How can I force-make? Makefile all: make clean make .lambda make .l...

How to use/install gcc on Mac OS X 10.8 / Xcode 4.4

I have install Mountain Lion (Mac OS X 10.8) and now gcc doesn't seem to be available anymore. I've also installed Xcode 4.4 so there is no more /Developer directory. I need gcc both for mac ports and for ruby gems (that have native extensions). D...

How to avoid scientific notation for large numbers in JavaScript?

JavaScript converts a large INT to scientific notation when the number becomes large. How can I prevent this from happening?...

Is it possible to center text in select box?

I tried this: http://jsfiddle.net/ilyaD/KGcC3/ HTML: <select name="state" class="ddList"> <option value="">(please select a state)</option> <option class="lt" value="--">none</option> <option class="lt" ...

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

I'm porting a webapp from Tomcat 7 to another server with Tomcat 7 but with Java 8. Tomcat starts successfully but in log catalina.out I get: org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15 at o...

jQuery validation plugin: accept only alphabetical characters?

I'd like to use jQuery's validation plugin to validate a field that only accepts alphabetical characters, but there doesn't seem to be a defined rule for it. I've searched google but I've found nothing useful. Any ideas? Appreciate your help....

How do I concatenate strings and variables in PowerShell?

Suppose I have the following snippet: $assoc = New-Object PSObject -Property @{ Id = 42 Name = "Slim Shady" Owner = "Eminem" } Write-Host $assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner...

Twitter Bootstrap add active class to li

Using twitter bootstrap, and I need to initiate active class to the li portion of the main nav. Automagically. We use php not ruby. Sample nav : <ul class="nav"> <li><a href="/">Home</a></li> <li><a hr...

html select scroll bar

how do you add a scroll bar to the html select box? is there any javascript library that emulate this behavior? or is there anyway to redesign, the interface I have 2 select box, items can be shifted to the right select box via >> & << Fi...

How do I get the Git commit count?

I'd like to get the number of commits of my Git repository, a bit like SVN revision numbers. The goal is to use it as a unique, incrementing build number. I currently do like that, on Unix/Cygwin/msysGit: git log --pretty=format:'' | wc -l But I...

How do I get the path and name of the file that is currently executing?

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. For example, let's say I have three files. Using execfile: script_1.py calls script_2.py. In turn, script_2.py cal...

Best way to retrieve variable values from a text file?

Referring on this question, I have a similar -but not the same- problem.. On my way, I'll have some text file, structured like: var_a: 'home' var_b: 'car' var_c: 15.5 And I need that python read the file and then create a variable named var_a wit...

PySpark: multiple conditions in when clause

I would like to modify the cell values of a dataframe column (Age) where currently it is blank and I would only do it if another column (Survived) has the value 0 for the corresponding row where it is blank for Age. If it is 1 in the Survived column...

OS X cp command in Terminal - No such file or directory

this might be one of those days my brain just does not work, or i'm incredibly dumb. i've been trying to copy files (which are actually directories .app, .bundle, etc.) but consistently get an error 'No such file or directory'. i've tried every possi...

How do I center a Bootstrap div with a 'spanX' class?

I use bootstrap and am trying to center a div(span7) like that: <div class="row-fluid"> <div id="main" class="span7"> Lorem ipsum dolor sit amet </div> </div> my css code is: #main{ margin:0px auto; } ...

How to have Ellipsis effect on Text

I'm having a long text in my app and I need to truncate it and add three dots to the end. How can I do that in React Native Text element? Thanks...

Putting GridView data in a DataTable

I'm trying to save a GridView to a DataTable. I have code which should in theory do it but I keep getting this error: Column 0 doesn't exist Here is my code: protected void Button1_Click(object sender, EventArgs e) { DataTable dt...

Convert RGB to Black & White in OpenCV

I would like to know how to convert an RGB image into a black & white (binary) image. After conversion, how can I save the modified image to disk?...

the getSource() and getActionCommand()

What is getSource? and what does it return? and what is getActionCommand() and what does it return?? I am getting confused between these two can anyone give or differentiate them to me? what's the use of getSource and getActionCommand() in UI's? sp...

How can I remove 3 characters at the end of a string in php?

How can I remove 3 characters at the end of a string in php? "abcabcabc" would become "abcabc"!...

How to get a context in a recycler view adapter

I'm trying to use picasso library to be able to load url to imageView, but I'm not able to get the context to use the picasso library correctly. public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> { private List&l...

Converting any object to a byte array in java

I have an object of type X which I want to convert into byte array before sending it to store in S3. Can anybody tell me how to do this? I appreciate your help....

Simulating Button click in javascript

So what i want to do is when i click on a button, it will pass this click event to another element in webpage, or you can say it will create a new click event in another element. Below is my code, it does not work, please let me know what is wrong wi...

View more than one project/solution in Visual Studio

I am new to visual studio and I am experimenting around with some Windows Services. I have created two solutions and I would like to view both of them at once. Without having to click file->recent projects to switch back and forth. Ideally this coul...

Python, TypeError: unhashable type: 'list'

i'm reciving the following error in my program: Traceback: Traceback (most recent call last): File "C:\Python33\Archive\PythonGrafos\Alpha.py", line 126, in <module> menugrafos() File "C:\Python33\Archive\PythonGrafos\Alpha.py", line 97, in me...

error: Your local changes to the following files would be overwritten by checkout

This question is similar to this one, but more specific. I have a project with two branches: staging and beta. I develop on staging, and use the master branch to fix bugs. So if I'm working on staging and I see an error, I change to master branch: gi...

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

I would like install R on my laptop Mac OS X version 10.7.3 I downloaded the last version and I double click on it and it was installed, when i start up I get the following error, I searched in internet but I could not solve the problem, any help wo...

How do you import classes in JSP?

I am a complete JSP beginner. I am trying to use a java.util.List in a JSP page. What do I need to do to use classes other than ones in java.lang?...

Quicksort: Choosing the pivot

When implementing Quicksort, one of the things you have to do is to choose a pivot. But when I look at pseudocode like the one below, it is not clear how I should choose the pivot. First element of list? Something else? function quicksort(array) ...

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I have replaced every occurrence of compile by implementation in my project's build.gradle, but I'm still getting this warning : I tried to look for "compile " in the whole project but no match was found. So what could be the cause?...

How to generate the JPA entity Metamodel?

In the spirit of type safety associated with the CriteriaQuery JPA 2.0 also has an API to support Metamodel representation of entities. Is anyone aware of a fully functional implementation of this API (to generate the Metamodel as opposed to creati...

How can I know if a process is running?

When I get a reference to a System.Diagnostics.Process, how can I know if a process is currently running?...

How do I use typedef and typedef enum in C?

Consider: #define MAXROW 20 #define MAXCOL 60 typedef State Grid[MAXROW+2] [MAXCOL+2] typedef enum state {DEAD,ALIVE} State How do I use typedef and typedef enum in C? What does this part of the code do?...

How do I position a div relative to the mouse pointer using jQuery?

Suppose I have one link in my page and I want that when I place my mouse just over the link, a div will show there according to mouse x,y. How can I accomplish this using jQuery?...

Saving an image in OpenCV

I am new to OpenCV, and trying to capture an image, and then save it to a file. I am posting the code for your reference, below. The jpg file is being saved, but it is black. // Capture the Image from the webcam CvCapture *pCapturedImage = cvCreate...

How do I set the background color of Excel cells using VBA?

As part of a VBA program, I have to set the background colors of certain cells to green, yellow or red, based on their values (basically a health monitor where green is okay, yellow is borderline and red is dangerous). I know how to set the values o...

PermissionError: [Errno 13] Permission denied

I'm getting this error : Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter\__init__.py", line 1538, in __call__ return self.func(*args) File "C:/Users/Marc/Documents/Programmation/Python/Llamachat/Llamach...

How to declare a global variable in php?

I have code something like this: <? $a="localhost"; function body(){ global $a; echo $a; } function head(){ global $a; echo $a; } function footer(){ global $a; echo $a; ...

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

I made some Java 1.6-Oracle11g-JDBC (using OJDBC 6) code (below). I am getting an exception - java.sql.SQLException: Missing IN or OUT parameter at index:: 1 Why is this happening and how do I fix it ? My output is- create CREATE TABLE employee(emp...

What is null in Java?

What is null? Is null an instance of anything? What set does null belong to? How is it represented in the memory?...

Print a list of space-separated elements in Python 3

I have a list L of elements, say natural numbers. I want to print them in one line with a single space as a separator. But I don't want a space after the last element of the list (or before the first). In Python 2, this can easily be done with the...

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

We have created a custom windows service. The deployment package is done in InstallShield and the installation prompts for the user name and password for the service Log On account. We have had no issues at all installing on various Windows 7 (Profe...

Java error: Comparison method violates its general contract

I saw many questions about this, and tried to solve the problem, but after one hour of googling and a lots of trial & error, I still can't fix it. I hope some of you catch the problem. This is what I get: java.lang.IllegalArgumentException: Com...

How to return a value from pthread threads in C?

I'am new to C and would like to play with threads a bit. I would like to return some value from a thread using pthread_exit() My code is as follows: #include <pthread.h> #include <stdio.h> void *myThread() { int ret = 42; pthread...

How is a CSS "display: table-column" supposed to work?

Given the following HTML and CSS, I see absolutely nothing in my browser (Chrome and IE latest at time of writing). Everything collapses down to 0x0 px. Why? <!DOCTYPE html> <html> <head> <style type="text/css"> s...

T-SQL to list all the user mappings with database roles/permissions for a Login

I am looking for a t-sql script which can list the databases and and the respective roles/privileges mapped for a particular user. Using SQL Server 2008 R2....

Is there a Python equivalent of the C# null-coalescing operator?

In C# there's a null-coalescing operator (written as ??) that allows for easy (short) null checking during assignment: string s = null; var other = s ?? "some default value"; Is there a python equivalent? I know that I can do: s = None other = s...

JavaScript getElementByID() not working

Why does refButton get null in the following JavaScript code? <html> <head> <title></title> <script type="text/javascript"> var refButton = document.getElementById("btnButton"); refButton.onclic...

Bootstrap 4 - Inline List?

I migrated a site from Bootstrap 4 alpha 6 to Bootstrap 4 Beta 1. <ul class="nav navbar-nav list-inline"> <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li> <...

Public class is inaccessible due to its protection level

I have the following classes: namespace Bla.Bla { public abstract class ClassA { public virtual void Setup(string thing) { } public abstract bool IsThingValid(); public abstract void ReadThings();...

How do I remove trailing whitespace using a regular expression?

I want to remove trailing white spaces and tabs from my code without removing empty lines. I tried: \s+$ and: ([^\n]*)\s+\r\n But they all removed empty lines too. I guess \s matches end-of-line characters too. UPDATE (2016): Nowadays I a...

How to re-sign the ipa file?

How do I sign the .ipa file with a provisioning profile after I generate an IPA like the following with a different provision profile? I would like to sign the IPA with an ad-hoc provisioning profile for beta testing, and then re-sign the exact IPA w...

Toggle display:none style with JavaScript

I want to change the style (second line below) to remove the display: none; part when the user clicks on the "Show All Tags" link. If the user clicks the "Show All Tags" link again, I need the display: none; text added back in to the "style..." state...

No 'Access-Control-Allow-Origin' header is present on the requested resource error

I'm trying to fetch the feed of a news website. Thought I'd use google's feed API to convert the feedburner feed into json. The following url will return 10 posts from the feed, in json format. http://ajax.googleapis.com/ajax/services/feed/load?v=1.0...

String strip() for JavaScript?

What's a clean and efficient JavaScript implementation to strip leading and trailing spaces from a string? For example: " dog" "dog " " dog " " dog " all get turned into "dog"...

Can I grep only the first n lines of a file?

I have very long log files, is it possible to ask grep to only search the first 10 lines?...

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

This is my code: int size = 100000000; double sizeInMegabytes = (size * 8.0) / 1024.0 / 1024.0; //762 mb double[] randomNumbers = new double[size]; Exception: Exception of type 'System.OutOfMemoryException' was thrown. I have 4GB memory on this m...

Spark - SELECT WHERE or filtering?

What's the difference between selecting with a where clause and filtering in Spark? Are there any use cases in which one is more appropriate than the other one? When do I use DataFrame newdf = df.select(df.col("*")).where(df.col("somecol").leq(10...

Running unittest with typical test directory structure

The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own test directory: new_project/ antigravity/ antigravity.py test/ test_antigravity.py setup.py etc...

How to remove "onclick" with JQuery?

PHP code: <a id="a$id" onclick="check($id,1)" href="javascript:void(0)" class="black">Qualify</a> I want to remove the onclick="check($id,1) so the link cannot be clicked or "check($id,1) won't be fired. How can I do it with JQuery?...

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I am trying to deploy my web project and I keep getting this error: Line 1: <%@ Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Language=“C#” %> I looked at this post: Parser Error: Server Error in '/...

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

I want to create new divs as the page loads. These divs will appear as an ordered group which changes depending upon external data from a JSON file. I will need to do this with a for loop because there are over 100 divs needed. So, I need to be able...

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

I downloaded Postman for Linux (from https://www.getpostman.com/apps), unpacked .tar.gz file into ~/bin/postman and then tried to execute ~/bin/postman/Postman/Postman. Unfortunately it resulted with following error: A JavaScript error occurred in t...

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

I'm trying to insert information in a partition table, but I don't know what I'm doing wrong! Show me this error: ORA-14400: inserted partition key does not map to any partition" The table dba_tab_partitions shows this informations below: 1 PDIA_...

How to overcome "datetime.datetime not JSON serializable"?

I have a basic dict as follows: sample = {} sample['title'] = "String" sample['somedate'] = somedatetimehere When I try to do jsonify(sample) I get: TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable What can ...

Converting bytes to megabytes

I've seen three ways of doing conversion from bytes to megabytes: megabytes=bytes/1000000 megabytes=bytes/1024/1024 megabytes=bytes/1024/1000 Ok, I think #3 is totally wrong but I have seen it. I think #2 is right, but I am looking for some resp...

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...

Split string into array of characters?

How is it possible to split a VBA string into an array of characters? I tried Split(my_string, "") but this didn't work....

What is logits, softmax and softmax_cross_entropy_with_logits?

I was going through the tensorflow API docs here. In the tensorflow documentation, they used a keyword called logits. What is it? In a lot of methods in the API docs it is written like tf.nn.softmax(logits, name=None) If what is written is those l...

What's the difference between tilde(~) and caret(^) in package.json?

After I upgraded to the latest stable node and npm, I tried npm install moment --save. It saves the entry in the package.json with the caret ^ prefix. Previously, it was a tilde ~ prefix. Why are these changes made in npm? What is the difference bet...

What is the difference between functional and non-functional requirements?

What is the difference between functional and non-functional requirements in the context of designing a software system? Give examples for each case....

Print Pdf in C#

I'm new to c#. I was looking all over the net for tutorials on how to print pdf, but couldn't find one. Then I thought, is it possible to read it using itextpdf, like mentioned here Reading PDF content with itextsharp dll in VB.NET or C# then prin...

Assign command output to variable in batch file

I'm trying to assign the output of a command to a variable - as in, I'm trying to set the current flash version to a variable. I know this is wrong, but this is what I've tried: set var=reg query hklm\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion&g...

Get the (last part of) current directory name in C#

I need to get the last part of current directory, for example from /Users/smcho/filegen_from_directory/AIRPassthrough, I need to get AIRPassthrough. With python, I can get it with this code. import os.path path = "/Users/smcho/filegen_from_direc...

Converting NSData to NSString in Objective c

I want to convert NSData to NSString..What is the best way to do this? I am using this code but the final string returns null NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); When I see consol...

How do I monitor all incoming http requests?

I need to monitor my application from incoming http POST and GET requests originating from outside and sometimes inside the machine. Is this possible? Been using fiddler but this only does outgoing not incoming (from outside the machine) or have I...

generate random double numbers in c++

How to generate random numbers between two doubles in c++ , these numbers should look like xxxxx,yyyyy ....

How do I combine 2 javascript variables into a string

I would like to join a js variable together with another to create another variable name... so it would be look like; for (i=1;i<=2;i++){ var marker = new google.maps.Marker({ position:"myLatlng"+i, map: map, title:"title"+i, icon: "image"+i...

Declare and initialize a Dictionary in Typescript

Given the following code interface IPerson { firstName: string; lastName: string; } var persons: { [id: string]: IPerson; } = { "p1": { firstName: "F1", lastName: "L1" }, "p2": { firstName: "F2" } }; Why isn't the initialization rejec...

Is there a cross-domain iframe height auto-resizer that works?

I tried a few solutions but wasn't successful. I'm wondering if there is a solution out there preferably with an easy-to-follow tutorial....

how to use getSharedPreferences in android

I have an application in which I have to implement a "Login" activity. I have these components: EditText username EditText password Button Login Button Cancel I want that my application to remember the login details of the user once the user has ...

Split a string using C++11

What would be easiest method to split a string using c++11? I've seen the method used by this post, but I feel that there ought to be a less verbose way of doing it using the new standard. Edit: I would like to have a vector<string> as a resu...

Shell script variable not empty (-z option)

How to make sure a variable is not empty with the -z option ? errorstatus="notnull" if [ !-z $errorstatus ] then echo "string is not null" fi It returns the error : ./test: line 2: [: !-z: unary operator expected ...

How to auto adjust the <div> height according to content in it?

I have a <div> which needs to be auto adjusted according to the content in it. How can I do this? Right now my content is coming out of the <div> The class I have used for the div is as follows box-centerside { background:url("../ima...

how to run the command mvn eclipse:eclipse

I'm following these instructions, but having problems with running commands like mvn eclipse:eclipse. How and where shall I run the command? My setup: Windows 7 32bit Eclipse Java EE IDE for Web Developers. Version: Juno Service Release 2 Build i...

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

I am running the following code- import json addrsfile = open("C:\\Users\file.json", "r") addrJson = json.loads(addrsfile.read()) addrsfile.close() if addrJson: print("yes") But giving me following error- Traceback (most recent call last):...

Replace only text inside a div using jquery

I have a div like: <div id="one"> <div class="first"></div> "Hi I am text" <div class="second"></div> <div class="third"></div> </div> I am trying to change only the text ...

Import MySQL database into a MS SQL Server

I have a .sql file from a MySQL dump containing tables, definitions and data to be inserted in these tables. How can I convert this database represented in the dump file to a MS SQL Server database?...

How to analyze information from a Java core dump?

If a process crashes and leaves a core dump or I create one with gcore then how can I analyze it? I'd like to be able to use jmap, jstack, jstat etc and also to see values of all variables. This way I can find the reasons for a crashed or frozen ...

How do I find out which DOM element has the focus?

I would like to find out, in JavaScript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how? The reason I was looking for this: I'm trying to make keys like th...

ERROR 1067 (42000): Invalid default value for 'created_at'

When I tried to alter the table it showed the error: ERROR 1067 (42000): Invalid default value for 'created_at' I googled for this error but all I found was as if they tried to alter the timestamp so it occurred. However here I am trying to add a ...

Javascript switch vs. if...else if...else

Guys I have a couple of questions: Is there a performance difference in JavaScript between a switch statement and an if...else? If so why? Is the behavior of switch and if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari) ...

What does -1 mean in numpy reshape?

A numpy matrix can be reshaped into a vector using reshape function with parameter -1. But I don't know what -1 means here. For example: a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]]) b = numpy.reshape(a, -1) The result of b is: matrix([[1, 2, 3...

Replace last occurrence of character in string

Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?...

How can I count the occurrences of a string within a file?

Just take this code as an example. Pretending it is an HTML/text file, if I would like to know the total number of times that echo appears, how can I do it using bash? new_user() { echo "Preparing to add a new user..." sleep 2 adduser ...

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

Here is my code: import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; logIn(username: string, password: string) { const url = 'http://server.com/index.php'; const body = JSON.stringify({username: username, ...

Loop through array of values with Arrow Function

Lets say I have: var someValues = [1, 'abc', 3, 'sss']; How can I use an arrow function to loop through each and perform an operation on each value?...

Adding an HTTP Header to the request in a servlet filter

I'm integrating with an existing servlet that pulls some properties out of the HTTP header. Basically, I'm implementing an interface that doesn't have access to the actual request, it just has access to a map of k->v for the HTTP headers. I need to...

Should have subtitle controller already set Mediaplayer error Android

Whenever I play a media, it shows a warning in DDMS Should have subtitle controller already set MY CODE: private void start() { mediaPlayer.start(); mediaPlayer.setOnCompletionListener(new OnCompletionListener() { @Override ...

How to rebase local branch onto remote master

I have a cloned project from a master branch from remote repository remote_repo. I create a new branch and I commit to that branch. Other programmers pushed to remote_repo to the master branch. I need now to rebase my local branch RB onto remote_repo...

How to integrate SAP Crystal Reports in Visual Studio 2017

Is it possible to use the report designer in the current release of Visual Studio 2017? The SAP crystal report wiki for visual studio integration only states: "RC build currently not supported - Tested opening existing app and it works". I ...

MySQL show current connection info

I am in a MySQL terminal session but I don't know what server I am connected to, or what database I am connected to. Is there a MySQL command that will tell me the host, port, and username and database I am using now?...

How to open Android Device Monitor in latest Android Studio 3.1

Recently I updated my android studio, after the update, I am unable to find android device monitor option in the tools section. In the previous update it was there in tools->android->android device monitor. But now in the updated version, it is not p...

Hibernate error - QuerySyntaxException: users is not mapped [from users]

I'm trying to get a list of all the users from "users" table and I get the following error: org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users] org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPe...

How do I use StringUtils in Java?

I'm a beginner in Java. I want to use StringUtils.replace but Eclipse outputs "StringUtils cannot be resolved". I tried import java.lang.*;, but it doesn't work....

UL list style not applying

I've got a stylesheet that will not, for whatever reason, apply list-style-type to a UL element. I'm using YUI's Grid CSS with their reset-fonts-grid.css file, which I know strips that out as part of the CSS reset. After calling YUI, I call the styl...

jQuery UI themes and HTML tables

Is there any way to theme an HTML table (CSS) with using the jQuery CSS themes? All of my components look like they belong together except for my HTML table which looks different....

PHP: How to handle <![CDATA[ with SimpleXMLElement?

I noticed that when using SimpleXMLElement on a document that contains those CDATA tags, the content is always NULL. How do I fix this? Also, sorry for spamming about XML here. I have been trying to get an XML based script to work for several hours ...

Android ListView headers

I have ListView that has some kind of events on it. Events are sorted by day, and I would like to have header with date on it for every day, and then events listen below. Here is how I populate that list: ArrayList<TwoText> crs = new ArrayLis...

How do I choose grid and block dimensions for CUDA kernels?

This is a question about how to determine the CUDA grid, block and thread sizes. This is an additional question to the one posted here. Following this link, the answer from talonmies contains a code snippet (see below). I don't understand the commen...

Python Pandas - Missing required dependencies ['numpy'] 1

Since yesterday I've had this error when I try to import packages on anaconda : ImportError: Missing required dependencies ['numpy'] I have tried un-installing Anaconda and Python, switching to Python 2.7 but nothing works it's still the same error...

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

In Firefox 3, the answer is 6 per domain: as soon as a 7th XmlHttpRequest (on any tab) to the same domain is fired, it is queued until one of the other 6 finish. What are the numbers for the other major browsers? Also, are there ways around these l...

CodeIgniter - Correct way to link to another page in a view

I was wondering if someone could tell me the correct way to link to another page from within a view. Is there a function for this or is it just the usual about Cheers,...

New warnings in iOS 9: "all bitcode will be dropped"

I have this new warning about the Google Framework in my app: (null): URGENT: all bitcode will be dropped because '/Users/myname/Library/Mobile Documents/com~apple~CloudDocs/foldername/appname/GoogleMobileAds.framework/GoogleMobileAds(GADSlot...

When should I use Kruskal as opposed to Prim (and vice versa)?

I was wondering when one should use Prim's algorithm and when Kruskal's to find the minimum spanning tree? They both have easy logics, same worst cases, and only difference is implementation which might involve a bit different data structures. So wha...

Copy table from one database to another

I've just created an empty database on my machine. I now wish to copy a table from our server database to this local database. What sql commands do I need to run to do this? I wish to create the new table, copy data from the old table and insert it ...

jQuery autocomplete with callback ajax json

I'm trying to find a way to use jQuery autocomplete with callback source getting data via an ajax json object list from the server. Could anybody give some directions? I googled it but couldn't find a complete solution....

C# Convert List<string> to Dictionary<string, string>

This may seem an odd thing to want to do but ignoring that, is there a nice concise way of converting a List to Dictionary where each Key Value Pair in the Dictionary is just each string in the List. i.e. List = string1, string2, string3 Dictionary ...

How to create EditText with cross(x) button at end of it?

Is there any widget like EditText which contains a cross button, or is there any property for EditText by which it is created automatically? I want the cross button to delete whatever text written in EditText....

Concat strings by & and + in VB.Net

Is there any difference between & and + operators while concatenating string? if yes, then what is difference? And if No, then why below code generating exception? Example: Dim s, s1, t As String Dim i As Integer s1 = "Hello" i...

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

They are algorithms for the young generation garbage collection. The second one (UseParNewGC) gets activated automatically with the concurrent tenured generation garbage collection (see Java Concurrent and Parallel GC) but, is there a difference be...

How to disable back swipe gesture in UINavigationController on iOS 7

In iOS 7 Apple added a new default navigation behavior. You can swipe from the left edge of the screen to go back on the navigation stack. But in my app, this behavior conflicts with my custom left menu. So, is it possible to disable this new gesture...

How can I convert a DateTime to the number of seconds since 1970?

I'm trying to convert a C# DateTime variable to Unix time, ie, the number of seconds since Jan 1st, 1970. It looks like a DateTime is actually implemented as the number of 'ticks' since Jan 1st, 0001. My current thought is to subtract Jan 1st, 1970...

Creating a dictionary from a CSV file

I am in the process of trying to write a python script that will take input from a CSV file and then push it into a dictionary format (I am using Python 3.x). I use the code below to read in the CSV file and that works: import csv reader = csv.rea...

Should I put input elements inside a label element?

Is there a best practice concerning the nesting of label and input HTML elements? classic way: <label for="myinput">My Text</label> <input type="text" id="myinput" /> or <label for="myinput">My Text <input type="tex...

remove first element from array and return the array minus the first element

_x000D_ _x000D_ var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_ _x000D_ //removes the first element of the array, and returns that element._x000D_ alert(myarray.shift());_x000D_ //alerts "item 1"_x000D_ _x000D_ //removes the last eleme...

Class has no member named

I have a problem with accessing a function from a class with the class object in my main function. I am just trying to make the object for the class and use that object to access the function inside that class's .cpp file. I keep getting an error and...

File size exceeds configured limit (2560000), code insight features not available

I am trying to work on a large Javascript file in Jetbrains WebStorm 8 and I am getting a message at the top of the editing window that says: File size exceeds configured limit (2560000). Code insight features not available. How can I increase ...

Which characters are valid in CSS class names/selectors?

What characters/symbols are allowed within the CSS class selectors? I know that the following characters are invalid, but what characters are valid? ~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` # ...

How to show imageView full screen on imageView click?

I am getting images from url and showing it on the imageView. This functionality is working properly. But I want that when I click on that image, then it must be full screen. So how to achieve this functionality? I know I am missing something. Please...

How to import a module in Python with importlib.import_module

I'm trying to use importlib.import_module in Python 2.7.2 and run into the strange error. Consider the following dir structure: a | + - __init__.py - b | + - __init__.py - c.py a/b/__init__.py has the ...

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

I received one of these errors. Error: unexpected symbol in "<my code>" Error: unexpected input in "<my code>" Error: unexpected string constant in "<my code>" Error: unexpected numeric constant in "<my code>" Erro...

Jquery how to find an Object by attribute in an Array

Given I have an array of "purpose" objects: //array of purpose objects: var purposeObjects = [ {purpose: "daily"}, {purpose: "weekly"}, {purpose: "monthly"} ]; (for simplicity i am omitting other attributes) Now I want to have a metho...

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

How fix Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object? // Service angular.module('admin.services', ['ngResource']) // GET TASK LIST ACTIVITY .factory('get...

How to determine the longest increasing subsequence using dynamic programming?

I have a set of integers. I want to find the longest increasing subsequence of that set using dynamic programming....

How to center images on a web page for all screen sizes

I'm having a problem with my HTML. I've searched all over the internet, but still no real answer. I have a website with some images, and I want them to be in the middle. Now, on my screen they're in the middle, but that's because I've put them there...

Send HTML in email via PHP

How can I send an HTML-formatted email with pictures using PHP? I want to have a page with some settings and HTML output which is sent via email to an address. What should I do? The main problem is to attach files. How can I do that?...

setInterval in a React app

I'm still fairly new at React, but I've been grinding along slowly and I've encountered something I'm stuck on. I am trying to build a "timer" component in React, and to be honest I don't know if I'm doing this right (or efficiently). In my code be...

How to zip a whole folder using PHP

I have found here at stackoveflow some codes on how to ZIP a specific file, but how about a specific folder? Folder/ index.html picture.jpg important.txt inside in My Folder, there are files. after zipping the My Folder, i also want to delete ...

Removing multiple files from a Git repo that have already been deleted from disk

I have a Git repo that I have deleted four files from using rm (not git rm), and my Git status looks like this: # deleted: file1.txt # deleted: file2.txt # deleted: file3.txt # deleted: file4.txt How do I remove these files...

How to comment/uncomment in HTML code

Often while coding view templates in html, my habit of adding some helpful comments causes lots of time-consuming effort while testing. Consider this code... <!-- Here starts the sidebar --> <div id="sidebar"> .... </div> <!--...

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see isset($_GET['something']) ? $_GET['something'] : '' I understand normal iss...

How to display PDF file in HTML?

I have an auto generated PDF file by itext and I need to display that PDF file in HTML. My question is: How to display a local PDF file in HTML using pdf.js? Should that PDF file be generated by some standards?...

Check if an array contains any element of another array in JavaScript

I have a target array ["apple","banana","orange"], and I want to check if other arrays contain any one of the target array elements. For example: ["apple","grape"] //returns true; ["apple","banana","pineapple"] //returns true; ["grape", "pineap...

Adding an onclick event to a div element

I saw a few similar topics which did help but I have specific problem and didn't manage to solve it alone so if anyone can help out I would appreciate it I want to add onclick event to a div element. HTML: <div id="thumb0" class="thumbs" oncl...

Xcode Product -> Archive disabled

I have been archiving for ad hoc distribution fine for many months and suddenly today I cannot do so as the Archive menu item is disabled. I have not changed anything. I went through the provisioning setup for the project and it looks ok. My Ad Hoc ...

Google API for location, based on user IP address

I am looking for a way to get the user's current location (city) based on is IP address using the Google Maps APIs. Something similar to http://freegeoip.net/json but only using the Google Maps APIs. Is this possible?...

Private vs Protected - Visibility Good-Practice Concern

I've been searching and I know the theoretic difference. public - Any class/function may access the method/property. protected - Only this class and any subclasses may access the method/property. private - Only this class may access the method/prop...

How to import jquery using ES6 syntax?

I'm writing a new app using (JavaScript) ES6 syntax through babel transpiler and the preset-es2015 plugins, as well as semantic-ui for the style. index.js import * as stylesheet from '../assets/styles/app.scss'; import * as jquery2 from '../dist/s...

What are the advantages and disadvantages of recursion?

With respect to using recursion over non-recursive methods in sorting algorithms or, for that matter, any algorithm what are its pros and cons?...

How do I get Maven to use the correct repositories?

I have just checked out some projects and need to build them, however I installed Maven quite some time ago (6 months maybe?) and really haven't used it since - the pom.xml for the project I have doesn't have this "http://repo1.maven.org/myurlhere" a...

CSS: how to add white space before element's content?

None of the following code works : p:before { content: " "; } p:before { content: "&nbsp;"; } How do I add white space before element's content ? Note: I need to color the border-left and the margin-left for semantic use and use the space as...

Opening A Specific File With A Batch File?

I'm would like to know how I can open a specific file using a specific program with a batch file. So far, my batch file can open the program, but I'm not sure how to open a file with that program. @echo off start wgnuplot.exe ...

How to embed new Youtube's live video permanent URL?

I stream live on youtube a lot and since yesterday I experience a weird thing: I embedded the livestream URL in my site. it was youtube.com/embed/ABCDE (normal embed link). That link used to show the current livestream and not a specific video. for ...

How to copy an object by value, not by reference

I want to make a copy of an object, then after some logic, re-assign the original object the value of the copy. example: User userCopy = //make a copy foreach(...) { user.Age = 1; user.ID = -1; UserDao.Update(user) user = userCopy; } ...

Plotting time-series with Date labels on x-axis

I know that this question might be a cliche, but I'm having hard time doing it. I've data set in the following format: Date Visits 11/1/2010 696537 11/2/2010 718748 11/3/2010 799355 11/4/2010 ...

how to resolve DTS_E_OLEDBERROR. in ssis

In an ssis package consists of data flow task,contains OLEDB source and OLDB Target ..provider is sql native client..This used to run fine ..but now got an error as shown below.. Please tell me how to resolve it ?changing it to ado.net? OS :wind...

Correct use of transactions in SQL Server

I have 2 commands and need both of them executed correctly or none of them executed. So I think I need a transaction, but I don't know how to use it correctly. What's the problem with the following script? BEGIN TRANSACTION [Tran1] INSERT INTO [Te...

How do I ALTER a PostgreSQL table and make a column unique?

I have a table in PostgreSQL where the schema looks like this: CREATE TABLE "foo_table" ( "id" serial NOT NULL PRIMARY KEY, "permalink" varchar(200) NOT NULL, "text" varchar(512) NOT NULL, "timestamp" timestamp with time zone NOT NUL...

Python: how to capture image from webcam on click using OpenCV

I want to capture and save a number of images from my webcam using OpenCV. This is my code currently: import cv2 camera = cv2.VideoCapture(0) for i in range(10): return_value, image = camera.read() cv2.imwrite('opencv'+str(i)+'.png', image)...

How to parse XML using shellscript?

I would like to know what would be the best way to parse an XML file using shellscript ? Should one do it by hand ? Does third tiers library exist ? If you already made it if you could let me know how did you manage to do it...

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

I am testing an html webpage and it is failing to load a local jquery.json-2.4.0.js. I am testing the html page locally from chrome. When the page loaded I get a net::ERR_FILE_NOT_FOUND. Why is it unable to load the file? This file has been moved f...

How do you convert a byte array to a hexadecimal string, and vice versa?

How can you convert a byte array to a hexadecimal string, and vice versa?...

Navigate to another page with a button in angular 2

I am trying to navigate to a another page by clicking a button but it fails to work. What could be the problem. I am now learning angular 2 and it's a bit tough for me now. //Routes/Path in a folder call AdminBoard export const AdminRoutes: Routes...

WSDL validator?

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

How do I scroll to an element within an overflowed Div?

I have 20 list items inside of a div that can only show 5 at a time. What is a good way to scroll to item #10, and then item #20? I know the height of all the items. The scrollTo plugin does this, but its source is not super easy to understand witho...

How to implement private method in ES6 class with Traceur

I use Traceur Compiler to have advantage with ES6 features now. I want to implement this stuff from ES5: function Animal() { var self = this, sayHi; sayHi = function() { self.hi(); }; this.hi = function() {/* ......

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

After accepting to update the project to new version of gradle I get this error: Error:Execution failed for task ':app:processDebugManifest'. Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0-alpha1) from [com....

unable to install pg gem

I tried using gem install pg but it doesn't seem to work. gem install pg gives this error Temporarily enhancing PATH to include DevKit... Building native extensions. This could take a while... ERROR: Error installing pg: ERROR: Failed to ...

How to Get enum item name from its value

I declared a enum type as this, enum WeekEnum { Mon = 0; Tue = 1; Wed = 2; Thu = 3; Fri = 4; Sat = 5; Sun = 6; }; How can I get the item name "Mon, Tue, etc" when I already have the item value "0, 1, etc." I already have a function as this Log(T...

What is the use of the @Temporal annotation in Hibernate?

The Hibernate Documentation has the information below for the @Temporal annotation: In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data you might want to describe the expected precision in databa...

Set textarea width to 100% in bootstrap modal

Was trying all possible ways, but never succeeded: <div style="float: right"> <button type="button" value="Decline" class="btn btn-danger" data-toggle="modal" data-target="#declineModal">Decline</button> </div>...

Redis strings vs Redis hashes to represent JSON: efficiency?

I want to store a JSON payload into redis. There's really 2 ways I can do this: One using a simple string keys and values. key:user, value:payload (the entire JSON blob which can be 100-200 KB) SET user:1 payload Using hashes HSET user:1 username...

How to do integer division in javascript (Getting division answer in int not float)?

Is there any function in Javascript that lets you do integer division, I mean getting division answer in int, not in floating point number. var x = 455/10; // Now x is 45.5 // Expected x to be 45 But I want x to be 45. I am trying to eliminate las...

Given an RGB value, how do I create a tint (or shade)?

Given an RGB value, like 168, 0, 255, how do I create tints (make it lighter) and shades (make it darker) of the color?...

How do I parse a string into a number with Dart?

I would like to parse strings like "1" or "32.23" into integers and doubles. How can I do this with Dart?...

ActionBarActivity cannot resolve a symbol

In my android Studio, Compiler is not able to locate ActionBarActivity. Because of it, I am getting many errors. The compiler is not able to import the ActionBarActivity and ActionBar class. These are the lines where compiler is throwing error: imp...

How to add header data in XMLHttpRequest when using formdata?

I'm trying to implement a file upload API, given here : Mediafire file Upload I am successfully able to upload the Post data & Get data, but have no clue how to send the x-filename attribute, which is meant to be Header data as given in API gui...

How do I make the return type of a method generic?

Is there a way to make this method generic so I can return a string, bool, int, or double? Right now, it's returning a string, but if it's able find "true" or "false" as the configuration value, I'd like to return a bool for example. public sta...

How to run an application as "run as administrator" from the command prompt?

I have a batch file called test.bat. I am calling the below instructions in the test.bat file: start /min powershell.exe %sysdrive%\testScripts\testscript1.ps1 When I run this through the command prompt, my testscript is running successfully. I wa...

Why is __init__() always called after __new__()?

I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern. However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can any...

How to JUnit test that two List<E> contain the same elements in the same order?

Context I am writing a simple JUnit test for the MyObject class. A MyObject can be created from a static factory method that takes a varargs of String. MyObject.ofComponents("Uno", "Dos", "Tres"); At any time during the existence of MyObject, cl...

How to submit a form with JavaScript by clicking a link?

Instead of a submit button I have a link: <form> <a href="#"> submit </a> </form> Can I make it submit the form when it is clicked?...

How to get the size of a range in Excel

Using VBA, is it possible to get the size of a given range in terms of pixels or units? (I don't care which unit as I am only using it to relate to other measurements with the same unit). Thanks....

Kotlin Android start new Activity

I want to start another activity on Android but I get this error: Please specify constructor invocation; classifier 'Page2' does not have a companion object after instantiating the Intent class. What should I do to correct the error? My code: ...

Error #2032: Stream Error

I am using an .swf file which takes data from an XML file to run. I have added this swf file into my dot net web application in an iframe. But when I run the application, flash gives the error: ERROR #2032 Stream Error Any ideas on how to solve...

Could not find an implementation of the query pattern

In my silverlight application I am trying to create a database connection using LINQ. First I add a new LINQ to SQL class, and drag my table called "tblPersoon" into it. Then in my service file I try to execute the following query: [OperationContra...

flow 2 columns of text automatically with CSS

I have the code similar to the following: <p>This is paragraph 1. Lorem ipsum ... </p> <p>This is paragraph 2. Lorem ipsum ... </p> <p>This is paragraph 3. Lorem ipsum ... </p> <p>This is paragraph 4. Lorem ...

How to validate white spaces/empty spaces? [Angular 2]

I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?...

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I am trying to send a POST request to a servlet. Request is sent via jQuery in this way: var productCategory = new Object(); productCategory.idProductCategory = 1; productCategory.description = "Descrizione2"; newCategory(productCategory); where n...

Saving timestamp in mysql table using php

I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table. How can I store the...

Using sed to split a string with a delimiter

I have a string in the following format: string1:string2:string3:string4:string5 I'm trying to use sed to split the string on : and print each sub-string on a new line. Here is what I'm doing: cat ~/Desktop/myfile.txt | sed s/:/\\n/ This prints...

How to convert an OrderedDict into a regular dict in python3

I am struggling with the following problem: I want to convert an OrderedDict like this: OrderedDict([('method', 'constant'), ('data', '1.225')]) into a regular dict like this: {'method': 'constant', 'data':1.225} because I have to store it as s...

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

I'm trying to run a basic and very simple code in python. from PIL import Image import pytesseract im = Image.open("sample1.jpg") text = pytesseract.image_to_string(im, lang = 'eng') print(text) This is what it looks like, I have actually inst...

Selenium C# WebDriver: Wait until element is present

I want to make sure that an element is present before the webdriver starts doing stuff. I'm trying to get something like this to work: WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5)); wait.Until(By.Id("login")); I'm m...

How to Set OnClick attribute with value containing function in ie8?

My goal is to change the onclick attribute of a link. I can do it successfully, but the resulting link doesn't work in ie8. It does work in ff3. For example, this works in Firefox 3, but not IE8. Why? <p><a id="bar" href="#" onclick="temp(...

How do you run a command for each line of a file?

For example, right now I'm using the following to change a couple of files whose Unix paths I wrote to a file: cat file.txt | while read in; do chmod 755 "$in"; done Is there a more elegant, safer way?...

A beginner's guide to SQL database design

Do you know a good source to learn how to design SQL solutions? Beyond the basic language syntax, I'm looking for something to help me understand: What tables to build and how to link them How to design for different scales (small client APP to a ...

phpinfo() - is there an easy way for seeing it?

Each time I want to see the phpinfo(); I have to: Create a info.php file; Write phpinfo(); in it. Go to the browser and type my "thisproject.dev/info.php" I'm on Ubuntu. Isn't there a more practical way to see phpinfo in the browser?...

collapse cell in jupyter notebook

I am using ipython Jupyter notebook. Let's say I defined a function that occupies a lot of space on my screen. Is there a way to collapse the cell? I want the function to remain executed and callable, yet I want to hide / collapse the cell in order...

How can you represent inheritance in a database?

I'm thinking about how to represent a complex structure in a SQL Server database. Consider an application that needs to store details of a family of objects, which share some attributes, but have many others not common. For example, a commercial ins...

Giving height to table and row in Bootstrap

I am using Bootstrap 3 , i am trying to give height to table and row, but nothing is working for me . I tried setting line-height and other properties of table, how can I increase height? <style> div#description { background-color...

How to calculate the CPU usage of a process by PID in Linux from C?

I want to programmatically [in C] calculate CPU usage % for a given process ID in Linux. How can we get the realtime CPU usage % for a given process? To make it further clear: I should be able to determine the CPU usage for the provided processid...

How do I detect a click outside an element?

I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area. Is something like this possible with jQuery? $("#menuscontainer").click...

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

I have some vanilla javascript code that takes a string input, splits the string into characters, and then matches those characters to a key on an object. DNATranscriber = { "G":"C", "C": "G", "T": "A", "A": "U" } function toRna(sequ...

How to call a shell script from python code?

How to call a shell script from python code?...

Dead simple example of using Multiprocessing Queue, Pool and Locking

I tried to read the documentation at http://docs.python.org/dev/library/multiprocessing.html but I'm still struggling with multiprocessing Queue, Pool and Locking. And for now I was able to build the example below. Regarding Queue and Pool, I'm not...

Execution failed for task ':app:compileDebugAidl': aidl is missing

I installed Android Studio on my computer. I created a new project but that got me the error below. What can I do? Error:Execution failed for task ':app:compileDebugAidl'. > aidl is missing My Android Studio version is 1.1.0. This is my build....

Coarse-grained vs fine-grained

What is the difference between coarse-grained and fine-grained? I have searched these terms on Google, but I couldn't find what they mean....

how to find array size in angularjs

How to find array size in AngularJS <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller=&quo...

How to set the java.library.path from Eclipse

How can I set the java.library.path for a whole Eclipse Project? I'm using a Java library that relies on OS specific files and need to find a .dll/ .so/ .jnilib. But the Application always exits with an error message that those files are not found on...

Java: how do I get a class literal from a generic type?

Typically, I've seen people use the class literal like this: Class<Foo> cls = Foo.class; But what if the type is generic, e.g. List? This works fine, but has a warning since List should be parameterized: Class<List> cls = List.class ...

Combine two OR-queries with AND in Mongoose

I want to combine two OR-queries with AND in Monoose, like in this SQL statement: SELECT * FROM ... WHERE (a = 1 OR b = 1) AND (c=1 OR d=1) I tried this in a NodeJS module which only gets the model object from the main application: /********** Ma...

JSON character encoding

My Java web application submits an AJAX request that returns JSON such: {'value': 'aériennes'} When 'aériennes' is displayed in the webpage, it appears as 'a?riennes', so I guess there's some kind of character encoding problem. The AJAX response...

Dealing with timestamps in R

I have multiple lists of measurements. In each list have the timestramp formated as a string ("2009-12-24 21:00:07.0") and I know that each measurement in the list is separated by 5 seconds. I want to combine all data into a huge data.frame in R. Aft...

Scroll to the top of the page after render in react.js

I have a problem, which I have no ideas, how to solve. In my react component I display a long list of data and few links at the bottom. After clicking on any of this links I fill in the list with new collection of the links and need to scroll to the ...

How to copy Outlook mail message into excel using VBA or Macros

I'm a newbie in VBA and Macros. If someone helps me with VBA code and macros, it will be helpful. Daily I'll receive around 50-60 mails with one standard subject: "Task Completed". I have created a rule to all those mail to move to a specific folder...

Substring in excel

I have a set of data that shown below on excel. R/V(208,0,32) YR/V(255,156,0) Y/V(255,217,0) R/S(184,28,16) YR/S(216,128,0) Y/S(209,171,0) R/B(255,88,80) YR/B(255,168,40) Y/B(255,216,40) And I want to separate the data in ea...

Eclipse - debugger doesn't stop at breakpoint

I am trying to trouble shoot a JUnit. In the source code, I have set break point in two places: 1) in a line where a static member is initialized 2) the first line of one of the test cases. The debugger stops in the static field initializing line. B...

How to detect scroll direction

I want to run a function when someone scrolls down on an element. Something like this: $('div').scrollDown(function(){ alert('down') }); $('div').scrollUp(function(){ alert('up') }); But those functions don't exist. Is there a solution to this p...

Change value in a cell based on value in another cell

Searched for this but could not find a way to do it. I would like to be able to transform a value in one cell to another value in a different cell like this: When cells in Column A contain Y set same number cells in Column B to Male or when cells...

Java java.sql.SQLException: Invalid column index on preparing statement

my code below query the database for a set of rows based on user input. I have tried and tested the query inside of SQL Developer and it works perfectly fine returning the correct rows. And example of an input is : 2013-01-22 But for some reason ins...

Changing column names of a data frame

I have a data frame called "newprice" (see below) and I want to change the column names in my program in R. > newprice Chang. Chang. Chang. 1 100 36 136 2 120 -33 87 3 150 14 164 In fact this i...

Difference between string object and string literal

What is the difference between String str = new String("abc"); and String str = "abc"; ...

Proper way to assert type of variable in Python

In using a function, I wish to ensure that the type of the variables are as expected. How to do it right? Here is an example fake function trying to do just this before going on with its role: def my_print(begin, text, end): """Print 'text' in ...

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...

How can I pass a list as a command-line argument with argparse?

I am trying to pass a list as an argument to a command line program. Is there an argparse option to pass a list as option? parser.add_argument('-l', '--list', type=list, action='store', dest='list', ...

Append TimeStamp to a File Name

I have come across this problem several times in which I would like to have multiple versions of the same file in the same directory. The way I have been doing it using C# is by adding a time stamp to the file name with something like this DateTime.N...

Command to collapse all sections of code?

In Visual Studio is there a command to collapse/expand all the sections of code in a file?...

Formatting Decimal places in R

I have a number, for example 1.128347132904321674821 that I would like to show as only two decimal places when output to screen (or written to a file). How does one do that? x <- 1.128347132904321674821 EDIT: The use of: options(digits=2) ...

ENOENT, no such file or directory

I'm getting this error from my node app: ENOENT, no such file or directory '~/Desktop/MyApp/newversion/partials/navigation.jade' I know the file is there because when I try to open the file using the exact copied and pasted path, it works. I also ...

Outlets cannot be connected to repeating content iOS

I have just created an app and have started hooking up @IBOutlet's to the storyboard. I am connecting some of them to labels in a UITableViewCell Prototype Cell with a Basic Style. When I connect it though I get this error in the Storyboard: The ...

@try - catch block in Objective-C

Why doesn't @try block work? It crashed the app, but it was supposed to be caught by the @try block. NSString* test = [NSString stringWithString:@"ss"]; @try { [test characterAtIndex:6]; } @catch (NSException * e) { NSLog(@"Exception: ...

An established connection was aborted by the software in your host machine

[2011-04-11 13:27:36 - ddmlib]An established connection was aborted by the software in your host machine java.io.IOException: An established connection was aborted by the software in your host machine at sun.nio.ch.SocketDispatcher.write0(Native...

Return datetime object of previous month

If only timedelta had a month argument in it's constructor. So what's the simplest way to do this? EDIT: I wasn't thinking too hard about this as was pointed out below. Really what I wanted was any day in the last month because eventually I'm goin...

Check input value length

I have a problem with input checking. I don't want to send the request if the input length is less than 3. My form: <form method='post' action=''> Albuma nosaukums: # # this is the input --><input id='titleeee' type='text' name'albu...

Disable browser cache for entire ASP.NET website

I am looking for a method to disable the browser cache for an entire ASP.NET MVC Website I found the following method: Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.Cache.SetNoStore(); And also a meta tag method (i...

How to split a string in Ruby and get all items except the first one?

String is ex="test1, test2, test3, test4, test5" when I use ex.split(",").first it returns "test1" Now I want to get the remaining items, i.e. `"test2, test3, test4, test5". If I use ex.split(",").last it returns only "test5" How to g...

Enabling the OpenSSL in XAMPP

I spent three hours but I did not find anything; I'm unable to connect to a SSL enabled server. I want to list what i did: First checked my PHP extensions directory was in order; extension wasn't there, php_openssl.dll Then I opened my php.ini file...

How to select all instances of selected region in Sublime Text

Is there a shortcut key or single-step menu option to find and select all instances of a highlighted selection in Sublime Text?...

Confused about stdin, stdout and stderr?

I am rather confused with the purpose of these three files. If my understanding is correct, stdin is the file in which a program writes into its requests to run a task in the process, stdout is the file into which the kernel writes its output and the...

Identify duplicate values in a list in Python

Is it possible to get which values are duplicates in a list using python? I have a list of items: mylist = [20, 30, 25, 20] I know the best way of removing the duplicates is set(mylist), but is it possible to know what values are being duplic...

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

I'm using Matplotlib to plot a histogram. Using tips from my previous question: Matplotlib - label each bin, I've more or less go the kinks worked out. There's one final issue - previously - the x-axis label ("Time (in milliseconds)") was being rend...

Check if PHP-page is accessed from an iOS device

I have a simple PHP webpage, and would like to return different content depending if it's accessed from an iPhone/iPad or from a web brower. How can I do that?...

HTML5 and frameborder

I have an iframe on an HTML5 document. when I validate I am getting an error telling me that the attribute on the iframe frameBorder is obsolete and to use CSS instead. I have this attribute frameBorder="0" here because it was the only way I could f...

How to use a filter in a controller?

I have written a filter function which will return data based on the argument you are passing. I want the same functionality in my controller. Is it possible to reuse the filter function in a controller? This is what I've tried so far: function my...

Onclick event to remove default value in a text input field

I have an input field: <input name="Name" value="Enter Your Name"> How would I get it to remove the pre-defined text (Enter Your Name) when the user clicks the box. As far as I am aware Javascript is the best way to do this. If that wrong p...

How to clear memory to prevent "out of memory error" in excel vba?

I am running VBA code on a large spreadsheet. How do I clear the memory between procedures/calls to prevent an "out of memory" issue occurring? Thanks...

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 to format current time using a yyyyMMddHHmmss format?

I'm trying to format the current time using this format yyyyMMddHHmmss. t := time.Now() fmt.Println(t.Format("yyyyMMddHHmmss")) That is outputting: yyyyMMddHHmmss Any suggestions?...

Javascript - Track mouse position

I am hoping to track the position of the mouse cursor, periodically every t mseconds. So essentially, when a page loads - this tracker should start and for (say) every 100 ms, I should get the new value of posX and posY and print it out in the form. ...

Powershell v3 Invoke-WebRequest HTTPS error

Using Powershell v3's Invoke-WebRequest and Invoke-RestMethod I have succesfully used the POST method to post a json file to a https website. The command I'm using is $cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(...

Get Specific Columns Using “With()” Function in Laravel Eloquent

I have two tables, User and Post. One User can have many posts and one post belongs to only one user. In my User model I have a hasMany relation... public function post(){ return $this->hasmany('post'); } And in my post model I have a bel...

Changing variable names with Python for loops

I was just wondering if anyone knew of a way to change variable names based off of a for loop for something like this: for i in range(3) group+i=self.getGroup(selected, header+i) so that the names of the variables change to accomodate the dat...

How to clear a chart from a canvas so that hover events cannot be triggered?

I'm using Chartjs to display a Line Chart and this works fine: // get line chart canvas var targetCanvas = document.getElementById('chartCanvas').getContext('2d'); // draw line chart var chart = new Chart(targetCanvas).Line(chartData); But the pr...

MySQL INNER JOIN Alias

Does anyone know how I can do an inner joins and alias values within so they won't overwrite each other? It might look more clear if you see my code: SELECT home, away, g.network, g.date_start FROM game g INNER JOIN team t ON ( ...

Eclipse - java.lang.ClassNotFoundException

When trying to start my JUnit-Test out of Eclipse, I get a "ClassNotFoundException". When running "mvn test" from console - everything works fine. Also, there are no problems reported in Eclipse. My project structure is the following: parent proje...

Why do we need middleware for async flow in Redux?

According to the docs, "Without middleware, Redux store only supports synchronous data flow". I don't understand why this is the case. Why can't the container component call the async API, and then dispatch the actions? For example, imagine a simpl...

Move a view up only when the keyboard covers an input field

I am trying to build an input screen for the iPhone. The screen has a number of input fields. Most of them on the top of the screen, but two fields are at the bottom. When the user tries to edit the text on the bottom of the screen, the keyboard wil...

T-SQL substring - separating first and last name

I have a column which has FirstName and LastName together. I'm writing a report to separate the FirstName And LastName. How do I get the FirstName and LastName separated in T-SQL?...

How can I make a div stick to the top of the screen once it's been scrolled to?

I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place and scrolls with the page....

Parse string to DateTime in C#

I have date and time in a string formatted like that one: "2011-03-21 13:26" //year-month-day hour:minute How can I parse it to System.DateTime? I want to use functions like DateTime.Parse() or DateTime.ParseExact() if possible, to be able to spe...

Add zero-padding to a string

How do I add "0" padding to a string so that my string length is always 4? Example If input "1", 3 padding is added = 0001 If input "25", 2 padding is added = 0025 If input "301", 1 padding is added = 0301 If input "4501", 0 padding is added = 4501...

How to write JUnit test with Spring Autowire?

Here are the files that I use: component.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframew...

PHP: Update multiple MySQL fields in single query

I am basically just trying to update multiple values in my table. What would be the best way to go about this? Here is the current code: $postsPerPage = $_POST['postsPerPage']; $style = $_POST['style']; mysql_connect ("localhost", "user", "pass") o...

scrollTop animation without jquery

I'm trying to make an animated "scroll to top" effect without using jQuery. In jQuery, I usually use this code: $('#go-to-top').click(function(){ $('html,body').animate({ scrollTop: 0 }, 400); return false; }); How do I animate scro...

Cookies vs. sessions

I started using PHP a couple of months ago. For the sake of creating a login system for my website, I read about cookies and sessions and their differences (cookies are stored in the user's browser and sessions on the server). At that time, I preferr...

m2e error in MavenArchiver.getManifest()

I am seeing an error in my STS and am not sure how to debug it. Searching around I only see vague references to the error and no solutions. The error is: org.apache.maven.archiver.MavenArchiver.getManifest(org.apache.maven.project.MavenProject, ...

ValueError: could not convert string to float: id

I'm running the following python script: #!/usr/bin/python import os,sys from scipy import stats import numpy as np f=open('data2.txt', 'r').readlines() N=len(f)-1 for i in range(0,N): w=f[i].split() l1=w[1:8] l2=w[8:15] list1=[flo...

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

When I tried to reset my adb the following error occurs: [2011-09-14 09:34:06 - DeviceMonitor]Adb connection Error:An existing connection was forcibly closed by the remote host [2011-09-14 09:34:07 - DeviceMonitor]Connection attempts: 1 I am just ...

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...

how to use json file in html code

I have json file mydata.json, and in this file is some json-encoded data. I want obtain this data in file index.html and process this data in JavaScript. But a don't know how to connect.json file in .html file? Tell me please. Here is my json file...

What are type hints in Python 3.5?

One of the most talked-about features in Python 3.5 is type hints. An example of type hints is mentioned in this article and this one while also mentioning to use type hints responsibly. Can someone explain more about them and when they should be use...

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

There is an online HTTP directory that I have access to. I have tried to download all sub-directories and files via wget. But, the problem is that when wget downloads sub-directories it downloads the index.html file which contains the list of files i...

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

I was working on my Spring boot app project and noticed that, sometimes there is a connection time out error to my Database on another server(SQL Server). This happens specially when I try to do some script migration with FlyWay but it works after s...

Error Handler - Exit Sub vs. End Sub

Why would I want to get out of an Error Handler (after handling) with an Exit Sub instead of just letting it go to the End Sub? I'm sure it's simple. I just don't understand. Thanks for any help. Example: Public Sub SubA() On Error Goto ProcErro...

How can I write variables inside the tasks file in ansible

I have this play.yml --- - hosts: 127.0.0.1 connection: local sudo: false tasks: - include: apache.yml My Apache look like this: vars: url: czxcxz - name: Download apache shell: wget {{url}} This is giving me error. If I re...

PHP Composer behind http proxy

I use composer on a network where the only way to access the internet is using HTTP or socks proxy. I have http_proxy and https_proxy environment variables. When compose tries to access HTTPS URLs I get this: file could not be downloaded: failed to...

How to initialize List<String> object in Java?

I can not initialize a List as in the following code: List<String> supplierNames = new List<String>(); supplierNames.add("sup1"); supplierNames.add("sup2"); supplierNames.add("sup3"); System.out.println(supplierNames.get(1)); I face th...

How can I update my ADT in Eclipse?

I have tried to update my Eclipse. Currently I have till 2.2 Android SDK in my Eclipse. Yesterday I have updated my Eclipse like this: Eclipse -> window -> Android SDK Manager -> I have checked two check-boxes from list. Tools -> Android SDK Tools a...

Using curl POST with variables defined in bash script functions

When I echo I get this, which runs when I enter it into the terminal curl -i \ -H "Accept: application/json" \ -H "Content-Type:application/json" \ -X POST --data '{"account":{"email":"[email protected]","screenName":"akdgdtk","type":"NIKE","password...

how to replace an entire column on Pandas.DataFrame

I would like to replace an entire column on a Pandas DataFrame with another column taken from another DataFrame, an example will clarify what I am looking for import pandas as pd dic = {'A': [1, 4, 1, 4], 'B': [9, 2, 5, 3], 'C': [0, 0, 5, 3]} df = pd...

What does ENABLE_BITCODE do in xcode 7?

I have a problem with the embedded bitcode term. What is embedded bitcode? When to enable, ENABLE_BITCODE in new Xcode? What happens to the binary when enabled, ENABLE_BITCODE in Xcode 7? ...

How to split a string into a list?

I want my Python function to split a sentence (input) and store each word in a list. My current code splits the sentence, but does not store the words as a list. How do I do that? def split_line(text): # split the text words = text.split() ...

Converting serial port data to TCP/IP in a Linux environment

I need to get data from the serial port of a Linux system and convert it to TCP/IP to send to a server. Is this difficult to do? I have some basic programming experience, but not much experience with Linux. Is there an open source application that do...

How do I add a delay in a JavaScript loop?

I would like to add a delay/sleep inside a while loop: I tried it like this: alert('hi'); for(var start = 1; start < 10; start++) { setTimeout(function () { alert('hello'); }, 3000); } Only the first scenario is true: after showing al...

How to turn off word wrapping in HTML?

I feel silly for not being able to figure this out, but how do I turn off wordwrap? the css word-wrap property can be forced on with break-word, but cannot be forced off (only can be left alone with normal value). How do I force word wrap off?...

Cannot ignore .idea/workspace.xml - keeps popping up

Using PHPStorm, I am trying to ignore the workspace.xml which pops up every-time I try to make a git commit. My .gitignore looks like: /.idea/ .idea/workspace.xml Because at a point the file was committed, I've also executed: git rm --cached .id...

How to measure time in milliseconds using ANSI C?

Using only ANSI C, is there any way to measure time with milliseconds precision or more? I was browsing time.h but I only found second precision functions....

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

The app is crashing when I'm trying to open a file. It works below Android Nougat, but on Android Nougat it crashes. It only crashes when I try to open a file from the SD card, not from the system partition. Some permission problem? Sample code: Fi...

Linq select to new object

I have a linq query var x = (from t in types select t).GroupBy(g =>g.Type) which groups objects by their type, as a result I want to have single new object containing all of the grouped objects and their count. Something like this: type1, 30 ...

What are the differences between using the terminal on a mac vs linux?

I've been using Ubuntu for the last four years. I have a basic knowledge of shell commands and I prefer working in a terminal rather than using a GUI. Recently I've started using a Mac. I've tried a few terminal commands (that I use on Ubuntu) in ...

How to redirect the output of the time command to a file in Linux?

Just a little question about timing programs on Linux: the time command allows to measure the execution time of a program: [ed@lbox200 ~]$ time sleep 1 real 0m1.004s user 0m0.000s sys 0m0.004s Which works fine. But if I try to redirect ...

jQuery: Handle fallback for failed AJAX Request

Can jQuery provide a fallback for failed AJAX calls? This is my try: function update() { var requestOK = false; $.getJSON(url, function(){ alert('request successful'); requestOK = true; }); if (!requestOK) { ...

How do you change Background for a Button MouseOver in WPF?

I have a button on my page with this XAML: <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="50" Height="50" HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0...

How to copy text to the client's clipboard using jQuery?

The workflow is simple: You click inside a textarea. The text is copied to the client's clipboard. Display notice to the user. How do you do it?...

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Is there any way to dynamically create and display 'n' Labels with 'n' corresponding Textboxs when we know value of 'n' after for example, clicking "Display" button. Let me know if anything make you don't understand my question. Thank you! I am wor...

How do I get a background location update every n minutes in my iOS application?

I'm looking for a way to get a background location update every n minutes in my iOS application. I'm using iOS 4.3 and the solution should work for non-jailbroken iPhones. I tried / considered following options: CLLocationManager startUpdatingLoc...

How to restore default perspective settings in Eclipse IDE

I was playing around with perspectives, such as the Customizing perspective ,I've closed too many windows, and even menu is not visible now . and now would now like to restore the Perspective back to its original state. How do I do this?...

C++ callback using class member

I know this has been asked so many times, and because of that it's difficult to dig through the cruft and find a simple example of what works. I've got this, it's simple and it works for MyClass... #include <iostream> using std::cout; using s...

What does "#pragma comment" mean?

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

How to change the background-color of jumbrotron?

I want to know how to change the background-color of 'jumbotron' class, it has a default background-color #eee in bootstrap.css. I tried to override by erasing this and giving the attribute none,none !important, transparent into my custom css and s...

Android - How to regenerate R class?

Possible Duplicate: Developing for Android in Eclipse: R.java not generating I have imported a project into my Eclipse IDE, but it's giving me an error since R file is not generated automatically. How can I edit the R file so that it matc...

FileProvider - IllegalArgumentException: Failed to find configured root

I'm trying to take a picture with camera, but I'm getting the following error: FATAL EXCEPTION: main Process: com.example.marek.myapplication, PID: 6747 java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulat...

Freemarker iterating over hashmap keys

Freemarker has two collection datatypes, lists and hashmaps Is there a way to iterate over hashmap keys just as we do with lists? So if I have a var with data lets say: user : { name : "user" email : "[email protected]" homepage : "http:/...

How to include() all PHP files from a directory?

In PHP can I include a directory of scripts? i.e. Instead of: include('classes/Class1.php'); include('classes/Class2.php'); is there something like: include('classes/*'); Couldn't seem to find a good way of including a collection of about 10 s...

Creating a copy of a database in PostgreSQL

What's the correct way to copy entire database (its structure and data) to a new one in pgAdmin?...

What's default HTML/CSS link color?

I need its code representation, like #FFFFFF....

How to make div background color transparent in CSS

I'm not using CSS3. So I can't use opacity or filter attributes. Without using these attributes how can I make the background-color transparent of a div? It should be kind of the text box example in this link. Here the text box background color is tr...

How to show progress dialog in Android?

I want to show ProgressDialog when I click on Login button and it takes time to move to another page. How can I do this?...

HTTP Status 404 - The requested resource (/) is not available

I integrated Tomcat 7 in Eclipse. When I start it using Eclipse, it shows that Tomcat is up and running, but when I go to http://localhost:8080 in my browser, it gives me following error: HTTP Status 404 - / type Status report message /...

Get User Selected Range

How can I get a range of cells selected via user mouse input for further processing using VBA?...

How can building a heap be O(n) time complexity?

Can someone help explain how can building a heap be O(n) complexity? Inserting an item into a heap is O(log n), and the insert is repeated n/2 times (the remainder are leaves, and can't violate the heap property). So, this means the complexity shou...

ASP.NET MVC get textbox input value

I have a textbox input and some radio buttons. For example my textbox input HTML looks like that: <input type="text" name="IP" id="IP" /> Once user clicks a button on a web page I want to pass data to my controller: <input type="button" ...

Perform Segue programmatically and pass parameters to the destination view

in my app I've a button that performs a segue programmatically: - (void)myButtonMethod { //execute segue programmatically [self performSegueWithIdentifier: @"MySegue" sender: self]; } I would like to know if there is a way to reference the...

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

A long time ago I have read an article (I believe a blog entry) which put me on the "right" track on naming objects: Be very very scrupulous about naming things in your program. For example if my application was (as a typical business app) handling ...

HTTP Basic: Access denied fatal: Authentication failed

I use GitLab Community Edition 9.1.3 2e4e522 on Windows 10 Pro x64. With Git client. Error Cloning into 'project_name'... remote: HTTP Basic: Access denied fatal: Authentication failed for 'http://[email protected]/my_user_name/project_name....

Multiline text in JLabel

How can I make the text of a JLabel extend onto another line?...

Use Ant for running program with command line arguments

My program getting command line arguments. How can I pass it when I use Ant?...

Should Jquery code go in header or footer?

Where is the best place to put Jquery code (or separate Jquery file)? Will pages load faster if I put it in the footer?...

Redirect to Action in another controller

I have two controllers, both called AccountController. One of them, lets call it Controller A, is in an Area called Admin and the other, lets call it Controller B, is not in any Area (I guess that means it's in the default Area?). Controller B has ...

setTimeout in for-loop does not print consecutive values

I have this script: for (var i = 1; i <= 2; i++) { setTimeout(function() { alert(i) }, 100); } But 3 is alerted both times, instead of 1 then 2. Is there a way to pass i, without writing the function as a string?...

CodeIgniter: Create new helper?

I need to loop lot of arrays in different ways and display it in a page. The arrays are generated by a module class. I know that its better not to include functions on 'views' and I want to know where to insert the functions file. I know I can 'exte...