Examples On Programing Languages

Get all unique values in a JavaScript array (remove duplicates)

I have an array of numbers that I need to make sure are unique. I found the code snippet below on the internet and it works great until the array has a zero in it. I found this other script here on Stack Overflow that looks almost exactly like it, bu...

How can I implement a tree in Python?

I am trying to construct a General tree. Are there any built-in data structures in Python to implement it?...

Send JSON data with jQuery

Why code below sent data as City=Moscow&Age=25 instead of JSON format? var arr = {City:'Moscow', Age:25}; $.ajax( { url: "Ajax.ashx", type: "POST", data: arr, dataType: 'json', async: false, suc...

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I am quite confused. I should be able to set <meta http-equiv="X-UA-Compatible" content="IE=edge" /> and IE8 and IE9 should render the page using the latest rendering engine. However, I just tested it, and if Compatibility Mode is turned on...

Saving and Reading Bitmaps/Images from Internal memory in Android

What I want to do, is to save an image to the internal memory of the phone (Not The SD Card). How can I do it? I have got the image directly from the camera to the image view in my app its all working fine. Now what I want is to save this image fr...

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I'm trying to use JSTL, but I get the following error: Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core" How is this caused and how can I solve it? ...

What properties can I use with event.target?

I need to identify elements from which events are fired. Using event.target gets the respective element. What properties can I use from there? href id nodeName I cannot find a whole lot of info on it, even on the jQuery pages, so here is ...

Gson: Is there an easier way to serialize a map

This link from the Gson project seems to indicate that I would have to do something like the following for serializing a typed Map to JSON: public static class NumberTypeAdapter implements JsonSerializer<Number>, JsonDeserializer<...

Task vs Thread differences

I'm new to parallel programming. There are two classes available in .NET: Task and Thread. So, my questions are: What is the difference between those classes? When is it better to use Thread over Task (and vice-versa)? ...

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

Just upgraded an ASP.NET MVC4 project to use Unity.WebApi version 5.0.0.0 and it requires System.Web.Http v 5.0.0.0 as per the following error: Assembly 'Unity.WebApi, Version=5.1.0.0, Culture=neutral, PublicKeyToken=43da31bc42a85347' uses 'System.We...

How to remove special characters from a string?

I want to remove special characters like: - + ^ . : , from an String using Java....

Are multi-line strings allowed in JSON?

Is it possible to have multi-line strings in JSON? It's mostly for visual comfort so I suppose I can just turn word wrap on in my editor, but I'm just kinda curious. I'm writing some data files in JSON format and would like to have some really long s...

Displaying a message in iOS which has the same functionality as Toast in Android

I need to know if there is any method in iOS which behaves like Toast messages in Android. That is, I need to display a message which is dismissed automatically after few seconds. This is similar to the functionality of the Toast class in the Androi...

How to sort a HashMap in Java

How are we able to sort a HashMap<key, ArrayList>? I want to sort on the basis of a value in the ArrayList....

Can anyone explain python's relative imports?

I can't for the life of me get python's relative imports to work. I have created a simple example of where it does not function: The directory structure is: /__init__.py /start.py /parent.py /sub/__init__.py /sub/relative.py /start.py contains ju...

how to File.listFiles in alphabetical order?

I've got code as below: class ListPageXMLFiles implements FileFilter { @Override public boolean accept(File pathname) { DebugLog.i("ListPageXMLFiles", "pathname is " + pathname); String regex = ".*pa...

How to remove white space characters from a string in SQL Server

I'm trying to remove white spaces from a string in SQL but LTRIM and RTRIM functions don't seem to work? Column: [ProductAlternateKey] [nvarchar](25) COLLATE Latin1_General_CS_AS NULL Query: select REPLACE(ProductAlternateKey, ' ', '@'), ...

Trim to remove white space

jQuery trim not working. I wrote the following command to remove white space. Whats wrong in it? var str = $('input').val(); str = jquery.trim(str); console.log(str); Fiddle example....

javascript popup alert on link click

I need a javascript 'OK'/'Cancel' alert once I click on a link. I have the alert code: <script type="text/javascript"> <!-- var answer = confirm ("Please click on OK to continue.") if (!answer) window.location="http://www.continue.com" // ...

Windows equivalent of OS X Keychain?

Is there an equivalent of the OS X Keychain, used to store user passwords, in Windows? I would use it to save the user's password for a web service that my (desktop) software uses. From the answers to this related question (Protecting user passwords...

What is "stdafx.h" used for in Visual Studio?

A file named stdafx.h is automatically generated when I start a project in Visual Studio 2010. I need to make a cross-platform C++ library, so I don't/can't use this header file. What is stdafx.h used for? Is it OK that I just remove this header fil...

StringUtils.isBlank() vs String.isEmpty()

I ran into some code that has the following: String foo = getvalue("foo"); if (StringUtils.isBlank(foo)) doStuff(); else doOtherStuff(); This appears to be functionally equivalent to the following: String foo = getvalue("foo"); if (foo.i...

jQuery $.cookie is not a function

I am trying to set a cookie using jQuery: $.cookie("testCookie", "hello"); alert($.cookie("testCookie")); But when I load my page, I receive the error "$.cookie is not a function". Here is what I know: I have downloaded the jQuery cookie plugin ...

Optimistic vs. Pessimistic locking

I understand the differences between optimistic and pessimistic locking. Now could someone explain to me when I would use either one in general? And does the answer to this question change depending on whether or not I'm using a stored procedure to...

Python: read all text file lines in loop

I want to read huge text file line by line (and stop if a line with "str" found). How to check, if file-end is reached? fn = 't.log' f = open(fn, 'r') while not _is_eof(f): ## how to check that end is reached? s = f.readline() print s if...

clear data inside text file in c++

I am programming on C++. In my code I create a text file, write data to the file and reading from the file using stream, after I finish the sequence I desire I wish to clear all the data inside the txt file. Can someone tell me the command to clear t...

HTML - How to do a Confirmation popup to a Submit button and then send the request?

I am learning web development using Django and have some problems in where to put the code taking chage of whether to submit the request in the HTML code. Eg. There is webpage containing a form(a blog) to be filled by the user, and upon click on the...

Why does an onclick property set with setAttribute fail to work in IE?

Ran into this problem today, posting in case someone else has the same issue. var execBtn = document.createElement('input'); execBtn.setAttribute("type", "button"); execBtn.setAttribute("id", "execBtn"); execBtn.setAttribute("value", "Execute"); exe...

AND/OR in Python?

I know that the and and or expressions exist in python, but is there any and/or expression? Or some way to combine them in order to produce the same effect as a and/or expression? my code looks something like this: if input=="a": if "a"...

Javascript change font color

I need to change the font color. I have the following: var clr="green"; <font color=clr>' + onlineff + ' </font> The font color does not change to green. Just wondering how this could be fixed....

Django - iterate number in for loop of a template

I have the following for loop in my django template displaying days. I wonder, whether it's possible to iterate a number (in the below case i) in a loop. Or do I have to store it in the database and then query it in form of days.day_number? {% for d...

How do I drag and drop files into an application?

I've seen this done in Borland's Turbo C++ environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?...

Converting HTML to Excel?

I know that Excel is capable of opening HTML files directly. But the content of the file will still be HTML. Is there any way I can change the contents of the file from HTML to XLS or XLSX?...

jQuery Validate - Enable validation for hidden fields

In the new version of jQuery validation plugin 1.9 by default validation of hidden fields ignored. I'm using CKEditor for textarea input field and it hides the field and replace it with iframe. The field is there, but validation disabled for hidden f...

Convert date to day name e.g. Mon, Tue, Wed

I have a variable that outputs the date in the following format: 201308131830 Which is 2013 - Aug - 13 - 18:30 I am using this to retrieve the day name but it is getting the wrong days: $dayname = date('D', strtotime($longdate)); Any idea what...

Delete files older than 3 months old in a directory using .NET

I would like to know (using C#) how I can delete files in a certain directory older than 3 months, but I guess the date period could be flexible. Just to be clear: I am looking for files that are older than 90 days, in other words files created les...

How do I save a stream to a file in C#?

I have a StreamReader object that I initialized with a stream, now I want to save this stream to disk (the stream may be a .gif or .jpg or .pdf). Existing Code: StreamReader sr = new StreamReader(myOtherObject.InputStream); I need to save this t...

Unnamed/anonymous namespaces vs. static functions

A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so: namespace { int cannotAccessOutsideThisFile() { ... } } // namespace You would think that such a feature would be useless -- since you can't specify the name of...

Pass multiple complex objects to a post/put Web API method

Can some please help me to know how to pass multiple objects from a C# console app to Web API controller as shown below? using (var httpClient = new System.Net.Http.HttpClient()) { httpClient.BaseAddress = new Uri(ConfigurationManager.AppSetting...

What does "where T : class, new()" mean?

Can you please explain to me what where T : class, new() means in the following line of code? void Add<T>(T item) where T : class, new(); ...

Android: how to refresh ListView contents?

My ListView is using an extension of BaseAdapter, I can not get it to refresh properly. When I refresh, it appears that the old data draws on top of the new data, until a scroll event happens. The old rows draw on top of the new rows, but the old r...

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

In the application I work on, we have several different places a user can print from. In all these cases we are using the same workflow of opening a new window(or tab), writing whatever we need to print to the document of the new window, and then we...

How to read a list of files from a folder using PHP?

I want to read a list the names of files in a folder in a web page using php. is there any simple script to acheive it?...

How to get the file extension in PHP?

I wish to get the file extension of an image I am uploading, but I just get an array back. $userfile_name = $_FILES['image']['name']; $userfile_extn = explode(".", strtolower($_FILES['image']['name'])); Is there a way to just get the extension it...

Fatal error: Class 'Illuminate\Foundation\Application' not found

I am getting following error when I open my site which is made using laravel 5 Fatal error: Class 'Illuminate\Foundation\Application' not found in C:\cms\bootstrap\app.php on line 14 I have tried removing vendor folder and composer.lock file an...

How to create an integer array in Python?

It should not be so hard. I mean in C, int a[10]; is all you need. How to create an array of all zeros for a random size. I know the zeros() function in NumPy but there must be an easy way built-in, not another module....

Query to select data between two dates with the format m/d/yyyy

I am facing problem when i'm trying to select records from a table between two dates. m using the following query select * from xxx where dates between '10/10/2012' and '10/12/2012' this query works for me but when the dates are in format like 1/...

How can I get enum possible values in a MySQL database?

I want to populate my dropdowns with enum possible values from a DB automatically. Is this possible in MySQL?...

hardcoded string "row three", should use @string resource

I'm a beginner android developer , I was trying to run this Linear Layout in eclipse : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" ...

Convert string to title case with JavaScript

Is there a simple way to convert a string to title case? E.g. john smith becomes John Smith. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner....

Android Center text on canvas

I'm trying to display a text using the code below. The problem is that the text is not centered horizontally. When I set the coordinates for drawText, it sets the bottom of the text at this position. I would like the text to be drawn so that the text...

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

I have a byte array highlighted below, how do I insert it into a SQL Server database Varbinary column? byte[] arraytoinsert = new byte[10]{0,1,2,3,4,5,6,7,8,9}; string sql = string.format ( "INSERT INTO mssqltable (varbinarycolumn) VAL...

Responsive css background images

I have a website (g-floors.eu) and I want to make the background (in css I have defined a bg-image for the content) also responsive. Unfortunately I really don't have any idea on how to do this except for one thing that I can think of but it's quite ...

Display all post meta keys and meta values of the same post ID in wordpress

I'm trying to display post meta values and post meta keys, If only one value is to be display I can used the simple function get_post_meta() but what I need now is to post all post meta data with the same post_id. I tried using foreach loop but nothi...

Converting Integers to Roman Numerals - Java

This is a homework assignment I am having trouble with. I need to make an integer to Roman Numeral converter using a method. Later, I must then use the program to write out 1 to 3999 in Roman numerals, so hardcoding is out. My code below is very bar...

Can't install any package with node npm

I'm trying to install some node packages through npm, but it won't go. I've already tried to install/unistall/update node, but nothing seems to work. I'm using ubuntu 12.04 - Here is how i'm trying to install packages: npm install underscore npm h...

How can I find a specific file from a Linux terminal?

I am trying to find where index.html is located on my linux server, and was wondering if there was a command to do that. Very new to linux and appreciate any help I can get....

Show dialog from fragment?

I have some fragments that need to show a regular dialog. On these dialogs the user can choose a yes/no answer, and then the fragment should behave accordingly. Now, the Fragment class doesn't have an onCreateDialog() method to override, so I guess ...

Safely override C++ virtual functions

I have a base class with a virtual function and I want to override that function in a derived class. Is there some way to make the compiler check if the function I declared in the derived class actually overrides a function in the base class? I would...

How to join a slice of strings into a single string?

package main import ( "fmt" "strings" ) func main() { reg := [...]string {"a","b","c"} fmt.Println(strings.Join(reg,",")) } gives me an error of: prog.go:10: cannot use reg (type [3]string) as type []string in argument to strings.Join Is th...

Reset the Value of a Select Box

I'm trying to reset the value of two select fields, structured like this, <select> <option></option> <option></option> <option></option> </select> <select> <option></option> ...

How to store an output of shell script to a variable in Unix?

i have a shell script "script.sh" which gives output as "success" or "Failed" when i execute in unix window. Now i want to store the output of script.sh into a unix command variable. say $a = {output of script.sh}...

How do I get currency exchange rates via an API such as Google Finance?

Now, I did find the Google Finance API and started looking through that but I found a lot of info about portfolios, transactions, positions & other stuff I know nothing about. Am I looking at the wrong docs? What do I need to do to get a feed o...

Resize command prompt through commands

I want to resize the command prompt window in a batch file, is it possible to set a height and width through something I can just add in the batch file?...

Android soft keyboard covers EditText field

Is there a way to make the screen scroll to allow the text field to be seen?...

How to place object files in separate subdirectory

I'm having trouble with trying to use make to place object files in a separate subdirectory, probably a very basic technique. I have tried to use the information in this page: http://www.gnu.org/software/hello/manual/make/Prerequisite-Types.html#Prer...

Padding In bootstrap

Im using bootstrap: <div id="main" class="container" role="main"> <div class="row"> <div class="span6"> <h2>Welcome</h2> <p>Hello and welcome to my website.</p> </div> <d...

Docker - Container is not running

I'm completely a newbie to docker. I tried to start a exited container like follows, I listed down all available containers using docker ps -a. It listed the following: I entered the following commands to start the container which is in the exited...

WPF Label Foreground Color

I have 2 Labels in a StackPanel and set a Foreground color to both of them... The second one shows as black, when it shouldn't. <StackPanel HorizontalAlignment="Right" Orientation="Horizontal" Grid.Column="4" Grid.Row="0" Width="Auto" Margin="0...

Drop data frame columns by name

I have a number of columns that I would like to remove from a data frame. I know that we can delete them individually using something like: df$x <- NULL But I was hoping to do this with fewer commands. Also, I know that I could drop columns us...

How to update values in a specific row in a Python Pandas DataFrame?

With the nice indexing methods in Pandas I have no problems extracting data in various ways. On the other hand I am still confused about how to change data in an existing DataFrame. In the following code I have two DataFrames and my goal is to upda...

How to minify php page html output?

I am looking for a php script or class that can minify my php page html output like google page speed does. How can I do this?...

keycode 13 is for which key

Which is the key on the keyboard having the keycode as 13? switch(key) { case 37: $.keynav.goLeft(); break; case 38: $.keynav.goUp(); break; case 39: $.keynav.goRight(); break; case 40: $.keynav.goDown(); ...

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

What is the difference in behavior of [MaxLength] and [StringLength] attributes? As far as I can tell (with the exception that [MaxLength] can validate the maximum length of an array) these are identical and somewhat redundant?...

How does String substring work in Swift

I've been updating some of my old code and answers with Swift 3 but when I got to Swift Strings and Indexing with substrings things got confusing. Specifically I was trying the following: let str = "Hello, playground" let prefixRange = str.startIn...

Changing the page title with Jquery

How to make dynamic changing <title> tag with jquery? example: adding 3 > symbols one by one > title >> title >>> title ...

Undefined reference to vtable

When building my C++ program, I'm getting the error message undefined reference to 'vtable... What is the cause of this problem? How do I fix it? It so happens that I'm getting the error for the following code (The class in question is CGam...

Row count where data exists

I need to count the total number of rows that have data. I want to be able to use this on multiple sheets with different amounts of data rows. I cannot figure out generic code that will count the number of rows from A1-A100 or A1-A300. I am tryin...

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

I'm having the following error: 11/Ago/2011 14:04:48 org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.pa...

How to force Sequential Javascript Execution?

I've only found rather complicated answers involving classes, event handlers and callbacks (which seem to me to be a somewhat sledgehammer approach). I think callbacks may be useful but I cant seem to apply these in the simplest context. See this exa...

Press enter in textbox to and execute button command

I want to execute the code behind my Search Button by pressing Enter. I have the Accept Button property to my search button. However, when i place my button as NOT visible my search doesn't execute. I want to be able to press Enter within my text b...

How to inject JPA EntityManager using spring

Is it possible to have Spring inject the JPA entityManager object into my DAO class without extending JpaDaoSupport? If yes, does Spring manage the transaction in this case? I'm trying to keep my Spring configuration as simple as possible: <bean...

Text Editor For Linux (Besides Vi)?

Let me preface this question by saying I use TextMate on Mac OSX for my text needs and I am in love with it. Anything comparable on the Linux platform? I'll mostly use it for coding python/ruby. Doing a google search yielded outdated answers. Edi...

Cannot connect to Database server (mysql workbench)

Could you help me solve this problem ? When I try to click "query database" under database menu in Mysql workbench. it gives me an error: Cannot Connect to Database Server Your connection attempt failed for user 'root' from your host to server at ...

Is there an "if -then - else " statement in XPath?

It seems with all the rich amount of function in xpath that you could do an "if" . However , my engine keeps insisting "there is no such function" , and I hardly find any documentation on the web (I found some dubious sources , but the syntax they ha...

How to implement a queue using two stacks?

Suppose we have two stacks and no other temporary variable. Is to possible to "construct" a queue data structure using only the two stacks?...

How to force Docker for a clean build of an image

I have build a Docker image from a Docker file using the below command. $ docker build -t u12_core -f u12_core . When I am trying to rebuild it with the same command, it's using the build cache like: Step 1 : FROM ubuntu:12.04 ---> eb965dfb09...

Eclipse - Unable to install breakpoint due to missing line number attributes

I am getting this strange error in Eclipse while trying to set a breakpoint. Unable to insert breakpoint Absent Line Number Information I ticked the checkbox from Compiler options but no luck....

Conditional Logic on Pandas DataFrame

How to apply conditional logic to a Pandas DataFrame. See DataFrame shown below, data desired_output 0 1 False 1 2 False 2 3 True 3 4 True My original data is show in the 'data' column and...

Regular expression for checking if capital letters are found consecutively in a string?

I want to know the regexp for the following case: The string should contain only alphabetic letters. It must start with a capital letter followed by small letter. Then it can be small letters or capital letters. ^[A-Z][a-z][A-Za-z]*$ But the stri...

Groovy executing shell commands

Groovy adds the execute method to String to make executing shells fairly easy; println "ls".execute().text but if an error happens, then there is no resulting output. Is there an easy way to get both the standard error and standard out? (other t...

How do I use vim registers?

I only know of one instance using registers is via CtrlR* whereby I paste text from a clipboard. What are other uses of registers? How to use them? Everything you know about VI registers (let's focus on vi 7.2) -- share with us....

What are the benefits to marking a field as `readonly` in C#?

What are the benefits of having a member variable declared as read only? Is it just protecting against someone changing its value during the lifecycle of the class or does using this keyword result in any speed or efficiency improvements?...

Making the Android emulator run faster

The Android emulator is a bit sluggish. For some devices, like the Motorola Droid and the Nexus One, the app runs faster in the actual device than the emulator. This is a problem when testing games and visual effects. How do you make the emulator ru...

What's the difference between using CGFloat and float?

I tend to use CGFloat all over the place, but I wonder if I get a senseless "performance hit" with this. CGFloat seems to be something "heavier" than float, right? At which points should I use CGFloat, and what makes really the difference?...

Setting table row height

I have this code: <table class="topics" > <tr> <td style="white-space: nowrap; padding: 0 5px 0 0; color:#3A5572; font-weight: bold;">Test</td> <td style="padding: 0 4px 0 0;">1.0</td> ...

Split function in oracle to comma separated values with automatic sequence

Need Split function which will take two parameters, string to split and delimiter to split the string and return a table with columns Id and Data.And how to call Split function which will return a table with columns Id and Data. Id column will contai...

Differences between Ant and Maven

Could someone tell me the differences between Ant and Maven? I have never used either. I understand that they are used to automate the building of Java projects, but I do not know where to start from....

How to align checkboxes and their labels consistently cross-browsers

This is one of the minor CSS problems that plagues me constantly. How do folks around Stack Overflow vertically align checkboxes and their labels consistently cross-browser? Whenever I align them correctly in Safari (usually using vertical-align: b...

Open an image using URI in Android's default gallery image viewer

I have extracted image uri, now I would like to open image with Android's default image viewer. Or even better, user could choose what program to use to open the image. Something like File Explorers offer you if you try to open a file....

React - How to force a function component to render?

I have a function component, and I want to force it to re-render. How can I do so? Since there's no instance this, I cannot call this.forceUpdate()....

Count number of lines in a git repository

How would I count the total number of lines present in all the files in a git repository? git ls-files gives me a list of files tracked by git. I'm looking for a command to cat all those files. Something like git ls-files | [cat all these files] |...

Setting selected values for ng-options bound select elements

Fiddle with the relevant code: http://jsfiddle.net/gFCzV/7/ I'm trying to set the selected value of a drop down that is bound to a child collection of an object referenced in an ng-repeat. I don't know how to set the selected option since I can't ...

Get protocol, domain, and port from URL

I need to extract the full protocol, domain, and port from a given URL. For example: https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer >>> https://localhost:8181 ...

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

I am using docker for the first time and I was trying to implement this - https://docs.docker.com/get-started/part2/#tag-the-image At one stage I was trying to connect with localhost by this command - $ curl http://localhost:4000 which showed this e...

How to set ChartJS Y axis title?

I am using Chartjs for showing diagrams and I need to set title of y axis, but there are no information about it in documentation. I need y axis to be set like on picture, or on top of y axis so someone could now what is that parameter I have lo...

Animate scroll to ID on page load

Im tring to animate the scroll to a particular ID on page load. I have done lots of research and came across this: $("html, body").animate({ scrollTop: $('#title1').height() }, 1000); but this seems to start from the ID and animate to the top of t...

Capture event onclose browser

How I can capture event, close browser window, in jQuery or javascript ?...

What are pipe and tap methods in Angular tutorial?

I'm following the tutorial at https://angular.io, and I'm having trouble finding documentation; specifically for the methods pipe and tap. I can't find anything on https://angular.io or http://reactivex.io/rxjs/. My understanding is that pipe and...

How to remove all of the data in a table using Django

I have two questions: How do I delete a table in Django? How do I remove all the data in the table? This is my code, which is not successful: Reporter.objects.delete() ...

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

I am trying to run the following code in android URLConnection l_connection = null; // Create connection uzip=new UnZipData(mContext); l_url = new URL(serverurl); if ("https".equals(l_url.getProtocol())) { ...

Android and setting width and height programmatically in dp units

I'm doing: button.setLayoutParams(new GridView.LayoutParams(65, 65)); According to the docs the units for the width and height (both 65 in the above) are "pixels". How do you force this to be device independent pixels, or "dp"?...

How to activate "Share" button in android app?

i want to add "Share" button to my android app. Like that I added "Share" button, but button is not active. I click, but nothing happens. My code in MainActivity.java: private ShareActionProvider mShareActionProvider; @Override public boolean...

VBA for clear value in specific range of cell and protected cell from being wash away formula

I have data from like A1:Z50 but I want to delete only A5:X50 using VBA (I think it will be a lot faster than dragging the whole cell or using clickA5+shift+clickX50+delete). How can I do this ? And then, how to lock the cell to prevent it from gett...

What does EntityManager.flush do and why do I need to use it?

I have an EJB where I am saving an object to the database. In an example I have seen, once this data is saved (EntityManager.persist) there is a call to EntityManager.flush(); Why do I need to do this? The object I am saving is not attached and no...

Git commit with no commit message

How can I commit changes without specifying commit message? Why is it required by default?...

Bootstrap 3: Scroll bars

I am using Bootstrap 3 and have a list of subjects inside a side nav. The sidenav is long and I would like to make it that there is a scrollbar inside of the sidenav that displays 8 elements before having to scroll down. Here is my code below: <...

Selenium and xPath - locating a link by containing text

I'm trying to use xPath to find an element containing a piece of text, but I can't get it to work.... WebElement searchItemByText = driver.findElement(By.xpath("//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text()='Some text')]")); If...

python exception message capturing

import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHan...

How to check if a particular service is running on Ubuntu

I do not know the service's name, but would like to stop the service by checking its status. For example, if I want to check if the PostgreSQL service is running or not, but I don't know the service's name, then how could I check its status? I kno...

Text size and different android screen sizes

I know, it was discussed already 1000 times, but I can't adjust the text size for different screen sizes. I try to use 'sp' as size units in my custom style: <style name="CustumButtonStyle" parent="@android:style/Widget.Button"> ... &l...

What's the difference between a Future and a Promise?

What's the difference between Future and Promise? They both act like a placeholder for future results, but where is the main difference?...

Hidden property of a button in HTML

I am trying to show three buttons on one button click. Before a button click all three buttons are hidden. I set the hidden property and I am also calling a function on a button click. The problem is that when I load the page all buttons are visible....

Toggle visibility property of div

I have an HTML 5 video in a div. I then have a custom play button - that works fine. And I have the video's visibility set to hidden on load and visible when the play button is clicked, how do I return it to hidden when the play button is clicked aga...

Android WebView, how to handle redirects in app instead of opening a browser

So right now in my app the URL I'm accessing has a redirect, and when this happens the WebView will open a new browser, instead of staying in my app. Is there a way I can change the settings so the View will redirect to the URL like normal, but stay ...

Displaying splash screen for longer than default seconds

Is it possible to display the Default.png for a specified number of seconds? I have a client that wants the splash screen displayed for longer than its current time. They would like it displayed for 2 - 3 seconds....

Adding a column to a dataframe in R

I have the following dataframe (df) start end 1 14379 32094 2 151884 174367 3 438422 449382 4 618123 621256 5 698271 714321 6 973394 975857 7 980508 982372 8 994539 994661 9 1055151 1058824 . . . . . ....

What is considered a good response time for a dynamic, personalized web application?

For a complex web application that includes dynamic content and personalization, what is a good response time from the server (so excluding network latency and browser rendering time)? I'm thinking about sites like Facebook, Amazon, MyYahoo, etc. A...

Calculating the angle between the line defined by two points

I'm currently developing a simple 2D game for Android. I have a stationary object that's situated in the center of the screen and I'm trying to get that object to rotate and point to the area on the screen that the user touches. I have the constant...

Visualizing decision tree in scikit-learn

I am trying to design a simple Decision Tree using scikit-learn in Python (I am using Anaconda's Ipython Notebook with Python 2.7.3 on Windows OS) and visualize it as follows: from pandas import read_csv, DataFrame from sklearn import tree from os i...

How to pass payload via JSON file for curl?

I can successfully create a place via curl executing the following command: $ curl -vX POST https://server/api/v1/places.json -d " auth_token=B8dsbz4HExMskqUa6Qhn& \ place[name]=Fuelstation Central& \ place[city]=Grossbeeren& \ p...

Using RegEx in SQL Server

I'm looking how to replace/encode text using RegEx based on RegEx settings/params below: RegEx.IgnoreCase = True RegEx.Global = True RegEx.Pattern = "[^a-z\d\s.]+" I have seen some examples on RegEx, but confused as to how to apply it...

Apache Proxy: No protocol handler was valid

I am trying to proxy a subdirectory to another server. My httpd.conf: RewriteEngine On ProxyPreserveHost On RewriteRule .*subdir/ https://anotherserver/subdir/ [P] The problem is that Apache is always logging this: AH01144: No protocol handler wa...

Error: request entity too large

I'm receiving the following error with express: Error: request entity too large at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15) at json (/Use...

How to resolve the error on 'react-native start'

I just installed node.js & cli installed node.js installed react-native-cli npm -g react-native-cli And created a 'new project'. react-native init new_project and inside that 'new_project' directory, I tired to see if metro bundler works ...

Javascript extends class

What is the right/best way to extend a javascript class so Class B inherits everything from the class A (class B extends A)?...

Should you commit .gitignore into the Git repos?

Do you think it is a good practice to commit .gitignore into a Git repo? Some people don't like it, but I think it is good as you can track the file's history. Isn't it?...

How to convert Blob to File in JavaScript

I need to upload an image to NodeJS server to some directory. I am using connect-busboy node module for that. I had the dataURL of the image that I converted to blob using the following code: dataURLToBlob: function(dataURL) { var BASE64_MARKER...

Add resources, config files to your jar using gradle

How do I add config files or any other resources into my jar using gradle? My project structure: src/main/java/com/perseus/.. --- Java packages (source files) src/main/java/config/*.xml --- Spring config files Expected jar structure: ...

Is there a way to use shell_exec without waiting for the command to complete?

I have a process intensive task that I would like to run in the background. The user clicks on a page, the PHP script runs, and finally, based on some conditions, if required, then it has to run a shell script, E.G.: shell_exec('php measurePerforma...

Change first commit of project with Git?

I want to change something in the first commit of my project with out losing all subsequent commits. Is there any way to do this? I accidentally listed my raw email in a comment within the source code, and I'd like to change it as I'm getting spamme...

How do you convert WSDLs to Java classes using Eclipse?

I have a WSDL file (or, more precisely, its URL). I need to convert it to Java classes. I also need to provide tests for the web service it describes. I'm new to web services, so could someone tell me how to convert WSDLs to Java? I use Eclipse JEE...

Unix ls command: show full path when using options

I often use this list command in Unix (AIX / KSH): ls -Artl It displays the files as this: -rw-r--r-- 1 myuser mygroup 0 Apr 2 11:59 test1.txt -rw-r--r-- 1 myuser mygroup 0 Apr 2 11:59 test2.txt I would like to modify the command such a way...

Slack clean all messages (~8K) in a channel

We currently have a Slack channel with ~8K messages all comes from Jenkins integration. Is there any programmatic way to delete all messages from that channel? The web interface can only delete 100 messages at a time....

How to enable zoom controls and pinch zoom in a WebView?

The default Browser app for Android shows zoom controls when you're scrolling and also allows for pinch zooming. How can I enable this feature for my own Webview? I've tried: webSettings.setBuiltInZoomControls(true); webSettings.setSupportZoom(tru...

Git resolve conflict using --ours/--theirs for all files

Is there a way to resolve conflict for all files using checkout --ours and --theirs? I know that you can do it for individual files but couldn't find a way to do it for all....

Angular2 - Radio Button Binding

I want to use radio button in a form using Angular 2 Options : <br/> 1 : <input name="options" ng-control="options" type="radio" value="1" [(ng-model)]="model.options" ><br/> 2 : <input name="options" ng-control="options" ty...

Application.WorksheetFunction.Match method

I have seen a lot of Topics to the "unable to get the match property of the Worksheetfunction class" problem. But I can't get my code fixed. Why isn't this code work? rowNum = Application.WorksheetFunction.Match(aNumber, Sheet5.Range("B16:B615"), 0...

builder for HashMap

Guava provides us with great factory methods for Java types, such as Maps.newHashMap(). But are there also builders for java Maps? HashMap<String,Integer> m = Maps.BuildHashMap. put("a",1). put("b",2). build(); ...

AVD Manager - No system image installed for this target

Possible Duplicate: Unable to create Android Virtual Device The CPU/ABI field in Android New AVD popup window shows "No system image installed for this target". How do I fix this?...

Why is vertical-align:text-top; not working in CSS

I want to align some text to the top of a div. It seems that vertical-align: text-top; should do the trick, but it doesn't work. The other things that I have done, such as putting the divs into columns and displaying a dashed border (so I can see whe...

Android camera intent

I need to push an intent to default camera application to make it take a photo, save it and return an URI. Is there any way to do this?...

Blurring an image via CSS?

On many smartphones (Samsung Galaxy II being an example) when you browse through a photo gallery, its blurred copy is laid out in the background. Can this be achieved by CSS dynamically (ie. without the copy of the photo being prepared upfront saved)...

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

Is there a standard way in .NET/C# to convert a datetime object to ISO 8601 format yyyy-mm-dd hh:mm:ss? Or do I need to do some string manipulation to get the date string?...

recursion versus iteration

Is it correct to say that everywhere recursion is used a for loop could be used? And if recursion is usually slower what is the technical reason for ever using it over for loop iteration? And if it is always possible to convert an recursion into a f...

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

I have the following 'set recordset' line that I cannot get working. The parameters seem correct according to all available help I can find on the subject. The error displays : "Run-time error '3061'. Too few parameters. Expected 1." Here is t...

Entity Framework change connection at runtime

I have a web API project which references my model and DAL assemblies. The user is presented with a login screen, where he can select different databases. I build the connection string as follows: public void Connect(Database database) { ...

Binding select element to object in Angular

I'd like to bind a select element to a list of objects -- which is easy enough: @Component({ selector: 'myApp', template: `<h1>My Application</h1> <select [(ngModel)]="selectedValue"> <option...

Spring-Security-Oauth2: Full authentication is required to access this resource

I am trying to use spring-security-oauth2.0 with Java based configuration. My configuration is done, but when i deploy application on tomcat and hit the /oauth/token url for access token, Oauth generate the follwoing error: <oauth> <error...

Python - Join with newline

In the Python console, when I type: >>> "\n".join(['I', 'would', 'expect', 'multiple', 'lines']) Gives: 'I\nwould\nexpect\nmultiple\nlines' Though I'd expect to see such an output: I would expect multiple lines What am I missing her...

Build the full path filename in Python

I need to pass a file path name to a module. How do I build the file path from a directory name, base filename, and a file format string? The directory may or may not exist at the time of call. For example: dir_name='/home/me/dev/my_reports' base...

How to access static resources when mapping a global front controller servlet on /*

I've mapped the Spring MVC dispatcher as a global front controller servlet on /*. <servlet> <servlet-name>home</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-cl...

How to convert Django Model object to dict with its fields and values?

How does one convert a Django Model object to a dict with all of its fields? All ideally includes foreign keys and fields with editable=False. Let me elaborate. Let's say I have a Django model like the following: from django.db import models class...

Calling multiple JavaScript functions on a button click

How to call multiple functions on button click event? Here is my button, <asp:LinkButton ID="LbSearch" runat="server" CssClass="regular" onclick="LbSearch_Click" OnClientClick="return validateView();ShowDiv1();"> But my ...

How to reset a select element with jQuery

I have <select id="baba"> <option>select something</option> <option value="1">something 1</option> <option value=2">something 2</option> </select> Using jQuery, what would be the easiest (less to wri...

How to connect to SQL Server from command prompt with Windows authentication

How can I connect to SQL Server from command prompt using Windows authentication? This command Sqlcmd -u username -p password assumes a username & password for the SQL Server already setup Alternatively how can I setup a user account from c...

How to create module-wide variables in Python?

Is there a way to set up a global variable inside of a module? When I tried to do it the most obvious way as appears below, the Python interpreter said the variable __DBNAME__ did not exist. ... __DBNAME__ = None def initDB(name): if not __DBNA...

string encoding and decoding?

Here are my attempts with error messages. What am I doing wrong? string.decode("ascii", "ignore") UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 37: ordinal not in range(128) string.encode('utf-8', "ignore") ...

Simple conversion between java.util.Date and XMLGregorianCalendar

I'm looking for a simple method of converting between java.util.Date and javax.xml.datatype.XMLGregorianCalendar in both directions. Here is the code that I'm using now: import java.util.GregorianCalendar; import javax.xml.datatype.DatatypeConfi...

How to store standard error in a variable

Let's say I have a script like the following: useless.sh echo "This Is Error" 1>&2 echo "This Is Output" And I have another shell script: alsoUseless.sh ./useless.sh | sed 's/Output/Useless/' I want to capture "This Is Error", or any ...

Display current time in 12 hour format with AM/PM

Currently the time displayed as 13:35 PM However I want to display as 12 hour format with AM/PM, i.e 1:35 PM instead of 13:35 PM The current code is as below private static final int FOR_HOURS = 3600000; private static final int FOR_MIN = 60000; ...

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I have been trying to build a code using maven. But I am stuck with an error. The code is available on this github repo. google-play-crawler My system configurations as shown by maven is followning: Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe...

How can I select from list of values in Oracle

I am referring to this stackoverflow answer: How can I select from list of values in SQL Server How could something similar be done in Oracle? I've seen the other answers on this page that use UNION and although this method technically works, it's no...

Address already in use: JVM_Bind java

Some times whenever I restart the application, which is built on Java Struts Mysql and Jboss 4.05 Version I get the error as Address already in use: JVM_Bind Only fix that i know is to restart the machine and try again, it will work. Else Some time...

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

I just updated Python to 2.6.4 on my Mac. I installed from the dmg package. The binary did not seem to correctly set my Python path, so I added '/usr/local/lib/python2.6/site-packages' in .bash_profile >>> pprint.pprint(sys.path) ['', '...

How to style HTML5 range input to have different color before and after slider?

I want the left side to be green and the right side to be gray. As pictured above would be PERFECT. Preferably a pure CSS solution (only need to worry about WebKit). Is such a thing possible?...

A function to convert null to string

I want to create a function to convert any null value e.g. from a database to an empty string. I know there are methods such as if value != null ?? value : String.Empty but is there a way to pass null to a method e.g. public string nullToString(stri...

Return index of greatest value in an array

I have this: var arr = [0, 21, 22, 7]; What's the best way to return the index of the highest value into another variable?...

Writing Unicode text to a text file?

I'm pulling data out of a Google doc, processing it, and writing it to a file (that eventually I will paste into a Wordpress page). It has some non-ASCII symbols. How can I convert these safely to symbols that can be used in HTML source? Currently...

cannot import name patterns

Before I wrote in urls.py, my code... everything worked perfectly. Now I have problems - can't go to my site. "cannot import name patterns" My urls.py is: from django.conf.urls import patterns, include, url They said what error is somewhere here....

How to install Python MySQLdb module using pip?

How can I install the MySQLdb module for Python using pip?...

What is the best way to use a HashMap in C++?

I know that STL has a HashMap API, but I cannot find any good and thorough documentation with good examples regarding this. Any good examples will be appreciated....

How to preSelect an html dropdown list with php?

I am trying to get the option selected using PHP, but I ran out of ideas! Below is the code I have tried until now: <select> <option value="1">Yes</options> <option value="2">No</options> <option value="3">Fine&...

Is it better to use std::memcpy() or std::copy() in terms to performance?

Is it better to use memcpy as shown below or is it better to use std::copy() in terms to performance? Why? char *bits = NULL; ... bits = new (std::nothrow) char[((int *) copyMe->bits)[0]]; if (bits == NULL) { cout << "ERROR Not enough ...

How to run a maven created jar file using just the command line

I need some help trying to run the following maven project using the command line: https://github.com/sarxos/webcam-capture, the webcam-capture-qrcode example is the one I'm trying to run. I have it running using an the Eciplse IDE but need to move ...

Thymeleaf using path variables to th:href

Here's my code, where I'm iterating through: <tr th:each="category : ${categories}"> <td th:text="${category.idCategory}"></td> <td th:text="${category.name}"></td> <td> <a th:href="@{'/...

How to randomize Excel rows

How can I randomize lots of rows in Excel? For example I have an excel sheet with data in 3 rows. 1 A dataA 2 B dataB 3 C dataC I want to randomize the row order. For example 2 B dataB 1 A dataA 3 C dataC I could make a new column and fill it ...

Upload Image using POST form data in Python-requests

I'm working with wechat APIs ... here I've to upload an image to wechat's server using this API http://admin.wechat.com/wiki/index.php?title=Transferring_Multimedia_Files url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=%s&...

How can I make my string property nullable?

I want to make the Middle Name of person optional. I have been using C#.net code first approach. For integer data type its easy just by using ? operator to make in nullable. I am looking for a way to make my sting variable nullable. I tried to search...

Python `if x is not None` or `if not x is None`?

I've always thought of the if not x is None version to be more clear, but Google's style guide and PEP-8 both use if x is not None. Is there any minor performance difference (I'm assuming not), and is there any case where one really doesn't fit (maki...

How to use relative/absolute paths in css URLs?

I have a production and development server. The problem is the directory structure. Development: http://dev.com/subdir/images/image.jpg http://dev.com/subdir/resources/css/style.css Production: http://live.com/images/image.jpg http://live.com...

Get top n records for each group of grouped results

The following is the simplest possible example, though any solution should be able to scale to however many n top results are needed: Given a table like that below, with person, group, and age columns, how would you get the 2 oldest people in each g...

How to query for today's date and 7 days before data?

I'm using sql server 2008. How to query out a data which is the date is today and 7 days before today ?...

How to store a command in a variable in a shell script?

I would like to store a command to use at a later period in a variable (not the output of the command, but the command itself) I have a simple script as follows: command="ls"; echo "Command: $command"; #Output is: Command: ls b=`$command`; echo $b...

How to get the sign, mantissa and exponent of a floating point number

I have a program, which is running on two processors, one of which does not have floating point support. So, I need to perform floating point calculations using fixed point in that processor. For that purpose, I will be using a floating point emulati...

How do I POST form data with UTF-8 encoding by using curl?

I would like to POST (send) some form data to a webserver using cURL on a terminal-prompt. This is what I got so far: curl --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod The problem is that the umlaute ("...

Choosing a file in Python with simple Dialog

I would like to get file path as input in my Python console application. Currently I can only ask for full path as an input in the console. Is there a way to trigger a simple user interface where users can select file instead of typing the full pat...

How can I convert a comma-separated string to an array?

I have a comma-separated string that I want to convert into an array, so I can loop through it. Is there anything built-in to do this? For example, I have this string var str = "January,February,March,April,May,June,July,August,September,October...

MySQL Insert query doesn't work with WHERE clause

What's wrong with this query: INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1; It works without the WHERE clause. I've seemed to have forgot my SQL....

Swift 3: Display Image from URL

In Swift 3, I am trying to capture an image from the internet, and have these lines of code: var catPictureURL = NSURL(fileURLWithPath: "http://i.imgur.com/w5rkSIj.jpg") var catPictureData = NSData(contentsOf: catPictureURL as URL) // nil var catPic...

How to get std::vector pointer to the raw data?

I'm trying to use std::vector as a char array. My function takes in a void pointer: void process_data(const void *data); Before I simply just used this code: char something[] = "my data here"; process_data(something); Which worked as expected....

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

I updated to macOS Mojave (this happens on Catalina update too, and seems to potentially occur on every major update thereafter) This morning I navigated to my work's codebase in the Command Line on my MacBook pro, typed in "git status" in ...

Twitter Bootstrap onclick event on buttons-radio

I have a Twitter Bootstrap buttons-radio and hook an onclick event to it. But how do I check which of the buttons that got triggered? My first thought was to simply check for the class 'active', but this should create a race condition (result depend...

How to make a whole 'div' clickable in html and css without JavaScript?

I want to make it so that a whole div is clickable and links to another page when clicked without JavaScript and with valid code/markup. If I have this which is what I want the result to do - <a href="#"> <div>This is a link</div>...

How do I POST a x-www-form-urlencoded request using Fetch?

I have some parameters that I want to POST form-encoded to my server: { 'userName': '[email protected]', 'password': 'Password!', 'grant_type': 'password' } I'm sending my request (currently without parameters) like this var obj = { me...

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I am trying to start my web application on Tomcat 7, but whenever I click on the start button, I get this error: FAIL - Application at context path /Web could not be started and below lines are added to catalina.log file: Feb 08, 2012 7:21:...

Convert YYYYMMDD to DATE

I have a bunch of dates in varchar like this: 20080107 20090101 20100405 ... How do I convert them to a date format like this: 2008-01-07 2009-01-01 2010-04-05 I've tried using this: SELECT [FIRST_NAME] ,[MIDDLE_NAME] ,[LAST_NAME] ...

crop text too long inside div

<div style="display:inline-block;width:100px;"> very long text </div> any way to use pure css to cut the text that is too long rather than show on next new line and only show max 100px ...

How to rename a file using Python

I want to change a.txt to b.kml....

Disable same origin policy in Chrome

Is there any way to disable the Same-origin policy on Google's Chrome browser?...

Can I dispatch an action in reducer?

is it possible to dispatch an action in a reducer itself? I have a progressbar and an audio element. The goal is to update the progressbar when the time gets updated in the audio element. But I don't know where to place the ontimeupdate eventhandler,...

Scale image to fit a bounding box

Is there a css-only solution to scale an image into a bounding box (keeping aspect-ratio)? This works if the image is bigger than the container: img { max-width: 100%; max-height: 100%; } Example: Use case 1 (works): http://jsfiddle.net/Jp5A...

Tooltips with Twitter Bootstrap

I am using Twitter Bootstrap--and I am not a frontend developer! However, it's making the process almost--dare I say--fun! I'm a bit confused about tooltips. They are covered in the documentation but Twitter assumes some knowledge. For example, t...

When should I use Lazy<T>?

I found this article about Lazy: Laziness in C# 4.0 – Lazy What is the best practice to have best performance using Lazy objects? Can someone point me to a practical use in a real application? In other words, when should I use it?...

python: sys is not defined

I have a piece of code which is working in Linux, and I am now trying to run it in windows, I import sys but when I use sys.exit(). I get an error, sys is not defined. Here is the begining part of my code try: import numpy as np import pyfit...

Adding Google Play services version to your app's manifest?

I'm following this tutorial: https://developers.google.com/maps/documentation/android/start#overview on how to add Google Maps to an app within the Android SDK. The only problem I seem to be having is during this bit (I've done everything else wit...

Select query to remove non-numeric characters

I've got dirty data in a column with variable alpha length. I just want to strip out anything that is not 0-9. I do not want to run a function or proc. I have a script that is similar that just grabs the numeric value after text, it looks like this...

Authenticating in PHP using LDAP through Active Directory

I'm looking for a way to authenticate users through LDAP with PHP (with Active Directory being the provider). Ideally, it should be able to run on IIS 7 (adLDAP does it on Apache). Anyone had done anything similar, with success? Edit: I'd prefer a ...

Fatal error: Call to undefined function mysqli_connect()

For 2 days now I'm trying to solve this, but unfortunately no result. Let me tell you my story about the problem. I've bulid an application on a site, and the application deals with the reviews. But, I'm trying to put it on another site, and I copyed...

C# function to return array

/// <summary> /// Returns an array of all ArtworkData filtered by User ID /// </summary> /// <param name="UsersID">User ID to filter on</param> /// <returns></returns> public static Array[] GetDataRecords(int Users...

How to move the layout up when the soft keyboard is shown android

I have a login screen with two EditTexts and a login button in my layout. The problem is that, when I start typing, the soft keyboard is shown and covers the login button. How can I push the layout up or above the keyboard when it appears? I do not ...

How can I make my layout scroll both horizontally and vertically?

I am using a TableLayout. I need to have both horizontal and vertical scrolling for this layout. By default I am able to get vertical scrolling in the view but horizontal scrolling is not working. I am using Android SDK 1.5 r3. I have already tried...

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Sometimes java puzzles me. I have a huge amount of int initializations to make. What's the real difference? Integer.toString(i) new Integer(i).toString() ...

annotation to make a private method public only for test classes

Who has a solution for that common need. I have a class in my application. some methods are public, as they are part of the api, and some are private, as they for internal use of making the internal flow more readable now, say I want to write a un...

Controlling mouse with Python

How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?...

How to create a new database after initally installing oracle database 11g Express Edition?

I have installed Oracle Database 11g Express Edition on my pc (windows 7) and I have installed Oracle SQL Developer as well. I want to create a simple database to start with, maybe with one table or two and then use Oracle SQL Developer to insert d...

Pandas - 'Series' object has no attribute 'colNames' when using apply()

I need to use a lambda function to do a row by row computation. For example create some dataframe import pandas as pd import numpy as np def myfunc(x, y): return x + y colNames = ['A', 'B'] data = np.array([np.arange(10)]*2).T df = pd.DataFra...

How to ignore certain files in Git

I have a repository with a file, Hello.java. When I compile it, an additional Hello.class file is generated. I created an entry for Hello.class in a .gitignore file. However, the file still appears to be tracked. How can I make Git ignore Hello.cla...

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 do I shutdown, restart, or log off Windows via a bat file?

I've been using Remote Desktop Connection to get into a workstation. But in this environment, I cannot use the power options in Start Menu. I need an alternative way to shutdown or restart. How do I control my computer's power state through the comm...

When do items in HTML5 local storage expire?

For how long is data stored in localStorage (as part of DOM Storage in HTML5) available? Can I set an expiration time for the data which I put into local storage?...

Detecting user leaving page with react-router

I want my ReactJS app to notify a user when navigating away from a specific page. Specifically a popup message that reminds him/her to do an action: "Changes are saved, but not published yet. Do that now?" Should i trigger this on react-router ...

ResourceDictionary in a separate assembly

I have resource dictionary files (MenuTemplate.xaml, ButtonTemplate.xaml, etc) that I want to use in multiple separate applications. I could add them to the applications' assemblies, but it's better if I compile these resources in one single assembly...

Laravel requires the Mcrypt PHP extension

I am trying to use the migrate function in Laravel 4 on OSX. However, I am getting the following error: Laravel requires the Mcrypt PHP extension. As far as I understand, it's already enabled (see the image below). What is wrong, and how can I fi...

How to create friendly URL in php?

Normally, the practice or very old way of displaying some profile page is like this: www.domain.com/profile.php?u=12345 where u=12345 is the user id. In recent years, I found some website with very nice urls like: www.domain.com/profile/12345 ...

Cross-reference (named anchor) in markdown

Is there markdown syntax for the equivalent of: Take me to <a href="#pookie">pookie</a> ... <a name="pookie">this is pookie</a> ...

Create tap-able "links" in the NSAttributedString of a UILabel?

I have been searching this for hours but I've failed. I probably don't even know what I should be looking for. Many applications have text and in this text are web hyperlinks in rounded rect. When I click them UIWebView opens. What puzzles me is tha...

How to expand 'select' option width after the user wants to select an option

Maybe this is an easy question, maybe not. I have a select box where I hardcode with width. Say 120px. _x000D_ _x000D_ <select style="width: 120px">_x000D_ <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x0...

Unicode character as bullet for list-item in CSS

I need to use, for example, the star-symbol(?) as the bullet for a list-item. I have read the CSS3 module: Lists, that describes, how to use custom text as bullets, but it's not working for me. I think, the browsers simply don't support the ::marker...

Why are exclamation marks used in Ruby methods?

In Ruby some methods have a question mark (?) that ask a question like include? that ask if the object in question is included, this then returns a true/false. But why do some methods have exclamation marks (!) where others don't? What does it mean...

Should MySQL have its timezone set to UTC?

Follow up question of https://serverfault.com/questions/191331/should-servers-have-their-timezone-set-to-gmt-utc Should the MySQL timezone be set to UTC or should it be set to be the same timezone as the server or PHP is set? (If it is not UTC) Wha...

Set default heap size in Windows

I want to set Java heap size permanently and don't want to run every jar file with options. I use Windows and Java 1.7....

How to apply Hovering on html area tag?

I am trying to hover the area tag of HTML. I tried this in CSS: area:hover { border:1px solid black; } This is the HTML on which it should be applied. <!-- This imagemap inserted by Gwyn's Imagemap Selector http://gwynethllewelyn.net/gwyns...

XMLHttpRequest (Ajax) Error

I'm using XMLHttpRequest in JavaScript. However, it gives me an error, and I don't know what my problem is. I have to parse an XML file and assign its contents to the webpage - here's my code: <script = "text/javascript"> window.onload = ...

Any way to generate ant build.xml file automatically from Eclipse?

From Eclipse, I found I can easily export an Ant build file for my project. It provides references to 3rd party libraries and some base targets. I'm using it from my global build file. The only thing that bothers me about this, is that if something i...

Windows Bat file optional argument parsing

I need my bat file to accept multiple optional named arguments. mycmd.bat man1 man2 -username alice -otheroption For example my command has 2 mandatory parameters, and two optional parameters (-username) that has an argument value of alice, and -o...

2D arrays in Python

What's the best way to create 2D arrays in Python? What I want is want is to store values like this: X , Y , Z so that I access data like X[2],Y[2],Z[2] or X[n],Y[n],Z[n] where n is variable. I don't know in the beginning how big n would be so I ...

How to fix div on scroll

If you scroll down the page in the following URL, the 'share' div will lock onto the browser: http://knowyourmeme.com/memes/pizza-is-a-vegetable I'm assuming they are applying a position: fixed; attribute. How can this be achieved with jQuery?...

change html input type by JS?

How to do this through the tag itself change type from text to password <input type='text' name='pass' /> Is it possible to insert JS inside the input tag itself to change type='text' to type='password'?...

How to give a delay in loop execution using Qt

In my application I want that when a loop is being executed, each time the control transfers to the loop, each execution must be delayed by a particular time. How can I do this?...

How to make lists contain only distinct element in Python?

I have a list in Python, how can I make it's values unique?...

Add views below toolbar in CoordinatorLayout

I have the following layout: <android.support.design.widget.CoordinatorLayout android:id="@+id/main_content" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:la...

The type WebMvcConfigurerAdapter is deprecated

I just migrate to spring mvc version 5.0.1.RELEASE but suddenly in eclipse STS WebMvcConfigurerAdapter is marked as deprecated public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRe...

What is sharding and why is it important?

I think I understand sharding to be putting back your sliced up data (the shards) into an easy to deal with aggregate that makes sense in the context. Is this correct? Update: I guess I am struggling here. In my opinion the application tier shoul...

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

What's the real difference between declaring an array like this: var myArray = new Array(); and var myArray = []; ...

Getting distance between two points based on latitude/longitude

I tried implementing this formula: http://andrew.hedges.name/experiments/haversine/ The aplet does good for the two points I am testing: Yet my code is not working. from math import sin, cos, sqrt, atan2 R = 6373.0 lat1 = 52.2296756 lon1 = 21.0...

Node.js - Find home directory in platform agnostic way

Process.platform returns "win32" for Windows. On Windows a user's home directory might be C:\Users[USERNAME] or C:\Documents and Settings[USERNAME] depending on which version of Windows is being used. On Unix this isn't an issue....

How can I wait for a thread to finish with .NET?

I've never really used threading before in C# where I need to have two threads, as well as the main UI thread. Basically, I have the following. public void StartTheActions() { // Starting thread 1.... Thread t1 = new Thread(new ThreadStart(action...

How to make html <select> element look like "disabled", but pass values?

When I'm disabling a <select name="sel" disabled> <option>123</option> </select> element, it doesnt pass its variable. What to do to look it like disabled, but be in "normal" state? This is because I have a list of "...

install cx_oracle for python

Am on Debian 5, I've been trying to install cx_oracle module for python without any success. First, I installed oracle-xe-client and its dependency (followed tutorial in the following link here). Then, I used the scripts in /usr/lib/oracle/xe/app/o...

How to align texts inside of an input?

For all default inputs, the text you fill starts on the left. How do you make it start on the right?...

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

I have installed a fresh copy of Centos 7. Then I restarted Apache but the Apache failed to start. I have 3 days stucked in this issue. Even the support can not figure out the error. sudo service httpd start Failed to start apache : Job for ...

What's the difference between <b> and <strong>, <i> and <em>?

What's the difference between <b> and <strong>, <i> and <em> in HTML/XHTML? When should you use each?...

How to beautify JSON in Python?

Can someone suggest how I can beautify JSON in Python or through the command line? The only online based JSON beautifier which could do it was: http://jsonviewer.stack.hu/. I need to use it from within Python, however. This is my dataset: { "head...

OR operator in switch-case?

Let's take a simple switch-case that looks like: @Override public void onClick(View v) { switch (v.getId()) { case R.id.someValue : case R.id.someOtherValue: // do stuff break; } } I wonder why it is...

Enabling/Disabling Microsoft Virtual WiFi Miniport

I disabled my Microsoft Virtual WiFi Miniport network adapter from Control Panel\Network and Internet\Network Connections. Just right clicked on the miniport nic and clicked disable, and its gone. Now how could I enable it? After disabling the nic,...

how to install gcc on windows 7 machine?

I have MinGW on my windows 7 machine. I wish to install and use complete gcc for C compiler. I found there is no single pre-compiled ready-made installation file for this purpose. I checked the following page : http://gcc.gnu.org/install/ It is diffi...

Keyboard shortcuts with jQuery

How can I wire an event to fire if someone presses the letter g? (Where is the character map for all the letters BTW?)...

CMake complains "The CXX compiler identification is unknown"

I am following this thread and this one to build my own KDE without a sudo permission. Since there was no Git and CMake installed on the workstation. I just had them both installed under /home/< user> and added /home/< user>/bin and /home/< ...

Reading and writing binary file

I'm trying to write code to read a binary file into a buffer, then write the buffer to another file. I have the following code, but the buffer only stores a couple of ASCII characters from the first line in the file and nothing else. int length; ch...

How to close an iframe within iframe itself

How do I use javascript or jQuery to close an iframe within iframe itself? I've tried <a href="javascript:self.close()"> but it didn't work....

use localStorage across subdomains

I'm replacing cookies with localStorage on browsers that can support it (anyone but IE). The problem is site.com and www.site.com store their own separate localStorage objects. I believe www is considered a subdomain (a stupid decision if you ask me)...

ArrayList of int array in java

I'm new to the concept of arraylist. I've made a short program that is as follows: ArrayList<int[]> arl=new ArrayList<int[]>(); int a1[]={1,2,3}; arl.add(0,a1); System.out.println("Arraylist contains:"+arl.get(0)); It gives the output:...

PHPExcel set border and format for all sheets in spreadsheet

I'm currently trying to set all borders for my spreadsheet, also formatting such as autosize. My code below is working, for sheet 1. All other sheets inside the spreadsheet are completely untouched. I've been trying to get it to work with all other ...

ListView with Add and Delete Buttons in each Row in android

I am developing an android application in which I have made one ListView. I have to add 2 buttons with each row in ListView. These 2 buttons are Add and Delete. When user selects one of the buttons then some actions should be taken. How can I do it?...

How do I attach events to dynamic HTML elements with jQuery?

Suppose I have some jQuery code that attaches an event handler to all elements with class .myclass. For example: $(function(){ $(".myclass").click( function() { // do something }); }); And my HTML might be as follows: <a clas...

XmlDocument - load from string?

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

How to launch multiple Internet Explorer windows/tabs from batch file?

I would like a batch file to launch two separate programs then have the command line window close. Actually, to clarify, I am launching Internet Explorer with two different URLs. So far I have something like this: start "~\iexplore.exe" "url1" star...

Multi-dimensional arraylist or list in C#?

Is it possible to create a multidimensional list in C#? I can create an multidimensional array like so: string[,] results = new string[20, 2]; But I would like to be able to use some of the features in a list or arraylist like being able to add a...

What is the (best) way to manage permissions for Docker shared volumes?

I've been playing around with Docker for a while and keep on finding the same issue when dealing with persistent data. I create my Dockerfile and expose a volume or use --volumes-from to mount a host folder inside my container. What permissions sho...

jQuery if div contains this text, replace that part of the text

Like the title says, I want to replace a specific part of the text in a div. The structure looks like this: <div class="text_div"> This div contains some text. </div> And I want to replace only "contains" with "hello everyone", fo...

Why is “while ( !feof (file) )” always wrong?

I've seen people trying to read files like this in a lot of posts lately: #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { char *path = "stdin"; FILE *fp = argc > 1 ? fopen(path=argv[1], "r") : stdin; ...

Converting Symbols, Accent Letters to English Alphabet

The problem is that, as you know, there are thousands of characters in the Unicode chart and I want to convert all the similar characters to the letters which are in English alphabet. For instance here are a few conversions: ?->H ?->V ?->Y...

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

I need to use PLSQL Developer to access oracle databases. I get the following error when I try to connect to my database. ORA-12154: TNS:could not resolve the connect identifier specified. I am able to use SQLPLUS from the command line to connect to ...

"A referral was returned from the server" exception when accessing AD from C#

DirectoryEntry oDE = new DirectoryEntry("LDAP://DC=Test1,DC=Test2,DC=gov,DC=lk"); using (DirectorySearcher ds = new DirectorySearcher(oDE)) { ds.PropertiesToLoad.Add("name"); ds.PropertiesToLoad.Add("userPrincipalName"); ds.Filter = "(&...

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

This is my fiddle, http://jsfiddle.net/4vaxE/35/ It work fine in my fiddle. However, when I transfer it to dreamweaver, it can't work. And I found this two error in my coding. Uncaught ReferenceError: jQuery is not defined uncaught referenceerro...

How to master AngularJS?

I'm pretty new to AngularJS and I find it a bit awkward. The easy stuff is very easy, but the advanced things are significantly harder (directives, provider / service / factory...) The documentation isn't very helpful for someone who's just starting...

Determining if a number is prime

I have perused a lot of code on this topic, but most of them produce the numbers that are prime all the way up to the input number. However, I need code which only checks whether the given input number is prime. Here is what I was able to write, bu...

How to hide navigation bar permanently in android activity?

I want to hide navigation bar permanently in my activity(not whole system ui). now i'm using this piece of code getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); It hides the bar but when user touches the sc...

HTML5 video won't play in Chrome only

some background I've tested my video in FF and Safari (including iDevices) and it plays properly, but it will not play in the Chrome browser. As you can see in the code below, I've created mp4, m4v, webM, and ogv files, and I've tested all of them on...

Check if URL has certain string with PHP

I would like to know if some word is present in the URL. For example, if word car is in the URL, like www.domain.com/car/ or www.domain.com/car/audi/ it would echo 'car is exist' and if there's nothing it would echo 'no cars'....

Is it possible to save HTML page as PDF using JavaScript or jquery?

Is it possible to save HTML page as PDF using JavaScript or jquery? In Detail: I generated one HTML Page which contains a table . It has one button 'save as PDF'. If user clicks that button then that HTML page has to convert as PDF file. Is it pos...

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

When I load Visual Studio 2012 up, it will attempt to connect to the previous TFS server that it was connected to. On one of my machines (that also happens to connect to occasionally TFS2008 and TFS2010 servers) always seems to default to completely...

Linux / Bash, using ps -o to get process by specific name?

I am trying to use the ps -o command to get just specific info about processes matching a certain name. However, I am having some issues on this, when I try to use this even to just get all processes, like so, it just returns a subset of what a norma...

Map and Reduce in .NET

What scenarios would warrant the use of the "Map and Reduce" algorithm? Is there a .NET implementation of this algorithm? ...

Adding image to JFrame

So I am using Eclipse with Windows builder. I was just wondering if there was anyway I can import an image that'll show up on the JFrame that I can easily move around and re-size instead of setting the location and size and drawing it....

Can grep show only words that match search pattern?

Is there a way to make grep output "words" from files that match the search expression? If I want to find all the instances of, say, "th" in a number of files, I can do: grep "th" * but the output will be something like (bold is by me); some-te...

'DataFrame' object has no attribute 'sort'

I face some problem here, in my python package I have install numpy, but I still have this error 'DataFrame' object has no attribute 'sort' Anyone can give me some idea.. This is my code : final.loc[-1] =['', 'P','Actual'] final.index = final.inde...

How to get row number from selected rows in Oracle

I am selecting few rows from database e.g.: select * from student where name is like %ram% Result: ID Name email Branch 7 rama [email protected] B1 5 ramb [email protected] B2 3 ramc [email protected] B3 8 ramd...

Setting up maven dependency for SQL Server

I am developing a portlet where I have Hibernate access to SQL Server database. I set up maven dependencies for it and try to find out SQL Server connector on the same way I know MySql has it. Still my Google-search gives only Mysql if I search for ...

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

Is it possible to move/rename files in Git and maintain their history?

I would like to rename/move a project subtree in Git moving it from /project/xyz to /components/xyz If I use a plain git mv project components, then all the commit history for the xyz project gets lost. Is there a way to move this such that th...

How to split data into training/testing sets using sample function

I've just started using R and I'm not sure how to incorporate my dataset with the following sample code: sample(x, size, replace = FALSE, prob = NULL) I have a dataset that I need to put into a training (75%) and testing (25%) set. I'm not sure w...

What is meant by immutable?

This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie. Can somebody clarify what is meant by immutable? Why is a String immutable? What are the advantages/disadvantages of the immutable objects? Why sho...

Logarithmic returns in pandas dataframe

Python pandas has a pct_change function which I use to calculate the returns for stock prices in a dataframe: ndf['Return']= ndf['TypicalPrice'].pct_change() I am using the following code to get logarithmic returns, but it gives the exact same val...

Calculate the display width of a string in Java

How to calculate the length (in pixels) of a string in Java? Preferable without using Swing. EDIT: I would like to draw the string using the drawString() in Java2D and use the length for word wrapping....

Close/kill the session when the browser or tab is closed

Can somebody tell me how can I close/kill the session when the user closes the browser? I am using stateserver mode for my asp.net web app. The onbeforeunload method is not proper as it fires when user refreshes the page....

What does the "+=" operator do in Java?

Can you please help me understand what the following code means: x += 0.1; ...

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

I am working on a cross-platform React Native mobile app. I am writing console.log statements as I develop. I want to see these logging statements in Chrome while I'm running the Android app in the default Android emulator. According to Facebook's do...

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

No resource found - Theme.AppCompat.Light.DarkActionBar

I used ActionBar Style Generator, and now trying to use into my app, but getting : error: Error retrieving parent for item: No resource found that matches the given name '@style/ Theme.AppCompat.Light.DarkActionBar'. i am using android-...

Google Android USB Driver and ADB

I am looking for guidance or a definitive answer on the following. I want to use the Google Android USB Driver and modify the android_winusb.inf to support any number of Android devices. I was able to add an HTC Evo tablet successfully, but when I ...

How to edit .csproj file

When I am compiling my .csproj file using .NET Framework 4.0 MSBUILD.EXE file, I am getting an error: "lable01" not found in the current context of "website01.csproj". Actually, I need to add every ASP.NET page with its code-behin...

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

I'm now reading documentation on Twitter Bootstrap 3, and tried to follow column ordering as shown in this page but hit the wall. I don't understand why such a code works nor how to correctly specify the setting. What I want to show is one grid, wh...

How to allow access outside localhost

How can I allow access outside the localhost at Angular2? I can navigate at localhost:3030/panel easily but I can not navigate when I write my IP such as 10.123.14.12:3030/panel/. Could you please allow me how to fix it? I am not using npm (node pr...

Python: Get relative path from comparing two absolute paths

Say, I have two absolute paths. I need to check if the location referring to by one of the paths is a descendant of the other. If true, I need to find out the relative path of the descendant from the ancestor. What's a good way to implement this in P...

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

Hai guys, I ve used the following split function, CREATE FUNCTION dbo.Splitfn(@String varchar(8000), @Delimiter char(1)) returns @temptable TABLE (items varchar(8000)) as begin declare @idx int declare @slice var...

JavaScript .replace only replaces first Match

var textTitle = "this is a test" var result = textTitle.replace(' ', '%20'); But the replace functions stops at the first instance of the " " and I get the Result : "this%20is a test" Any ideas on where Im going wrong im sure its a simple fix....

How do I iterate over a JSON structure?

I have the following JSON structure: [{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }] How do I iterate over it using JavaScript?...

Replace invalid values with None in Pandas DataFrame

Is there any method to replace values with None in Pandas in Python? You can use df.replace('pre', 'post') and can replace a value with another, but this can't be done if you want to replace with None value, which if you try, you get a strange resul...

VBA, if a string contains a certain letter

I do not usually work with VBA and I cannot figure this out. I am trying to determine whether a certain letter is contained within a string on my spreadhseet. Private Sub CommandButton1_Click() Dim myString As String RowCount = WorksheetFunction.Co...

How to set Python's default version to 3.x on OS X?

I'm running Mountain Lion and the basic default Python version is 2.7. I downloaded Python 3.3 and want to set it as default. Currently: $ python version 2.7.5 $ python3.3 version 3.3 How do I set it so that every time I run $ python it o...

How do I migrate an SVN repository with history to a new Git repository?

I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like: SVN repository in: svn://myserver/path/to/svn/repos Git repository in: git://myserver/path/to/git/repos...

How to create a file on Android Internal Storage?

I want to save a file on internal storage into a specific folder. My code is: File mediaDir = new File("media"); if (!mediaDir.exists()){ mediaDir.createNewFile(); mediaDir.mkdir(); } File f = new File(getLocalPath()); f.createNewFile(); File...

Base64 Encoding Image

I am building an open search add-on for Firefox/IE and the image needs to be Base64 Encoded so how can I base 64 encode the favicon I have? I am only familiar with PHP...

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

What I want is for the green background to be just behind the text, not to be 100% of the page width. Here is my current code: _x000D_ _x000D_ h1 { _x000D_ text-align: center; _x000D_ background-color: green; _x000D_ }_x000D_ <h1>The L...

Array vs ArrayList in performance

Which one is better in performance between Array of type Object and ArrayList of type Object? Assume we have a Array of Animal objects : Animal animal[] and a arraylist : ArrayList list<Animal> Now I am doing animal[10] and l...

What I can do to resolve "1 commit behind master"?

After pushing I've been seeing this message at remote repository: 1 commit behind master. This merge has conflicts that must be resolved before it can be committed. To manually merge these changes into TA20footerLast run the following commands: git ...

How to print current date on python3?

From what I gather, here (for example), this should print the current year in two digits print (datetime.strftime("%y")) However, I get this error TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str' So I tri...

How to force the browser to reload cached CSS and JavaScript files

I have noticed that some browsers (in particular, Firefox and Opera) are very zealous in using cached copies of .css and .js files, even between browser sessions. This leads to a problem when you update one of these files, but the user's browser keep...

Where value in column containing comma delimited values

I wish to write an SQL statement for SQL Server 2008 that Selects entry's where a column contains a value, now the value within the column is a comma delimited list (usually - there could only be one entry (and no leading comma)) so what In checking ...

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

I tried to install OpenCV2.2 on Ubuntu 11.04. But OpenCV compilation fails stating an error related to linux/videodev.h file. File available in /user/includes/linux is named videodev2.h. /home/user/OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp:217:2...

Matplotlib color according to class labels

I have two vectors, one with values and one with class labels like 1,2,3 etc. I would like to plot all the points that belong to class 1 in red, to class 2 in blue, to class 3 in green etc. How can I do that? ...

Android: How do I get string from resources using its name?

I would like to have 2 languages for the UI and separate string values for them in my resource file res\values\strings.xml: <string name="tab_Books_en">Books</string> <string name="tab_Quotes_en">Quotes</string> <string...

dropping infinite values from dataframes in pandas?

what is the quickest/simplest way to drop nan and inf/-inf values from a pandas DataFrame without resetting mode.use_inf_as_null? I'd like to be able to use the subset and how arguments of dropna, except with inf values considered missing, like: df....

Error Running React Native App From Terminal (iOS)

I am following the tutorial on the official React Native website. Using the following to build my project: react-native run-ios I get the error: Found Xcode project TestProject.xcodeproj xcrun: error: unable to find utility "instruments", not a ...

Bring a window to the front in WPF

How can I bring my WPF application to the front of the desktop? So far I've tried: SwitchToThisWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle, true); SetWindowPos(new WindowInteropHelper(Application.Current.MainWindow).Handle...

How to add MVC5 to Visual Studio 2013?

I'm starting a new project, and would like to give a try to MVC 5 (I have built a web app using MVC 4 before). In Visual Studio 2013, I click the New Project and navigate to Visual C# > Web > Visual Studio 2012 (even though I have installed VS 2013 ...

Using multiple IF statements in a batch file

When using more than 1 IF statement, is there a special guideline that should be followed? Should they be grouped? Should I use parenthesis to wrap the command(s)? An example to use would be: IF EXIST somefile.txt IF EXIST someotherfile.txt SET var...

Python OpenCV2 (cv2) wrapper to get image size?

How to get the size of an image in cv2 wrapper in Python OpenCV (numpy). Is there a correct way to do that other than numpy.shape(). How can I get it in these format dimensions: (width, height) list?...

How to change HTML Object element data attribute value in javascript

How do you change HTML Object element data attribute value in JavaScript? Here is what i am trying <object type="text/html" id="htmlFrame" style="border: none;" standby="loading" width="100%"></object> var element = document.getEleme...

Python Requests package: Handling xml response

I like very much the requests package and its comfortable way to handle JSON responses. Unfortunately, I did not understand if I can also process XML responses. Has anybody experience how to handle XML responses with the requests package? Is it nec...

How to completely DISABLE any MOUSE CLICK

After the user clicks on...."log in" button, and other events, I made a loading script -to let users know they have to wait (Until ajax replies back). How can I DISABLE any MOUSE CLICKS (right click, left click, double click, middle click, x click),...

Constants in Kotlin -- what's a recommended way to create them?

How is it recommended to create constants in Kotlin? And what's the naming convention? I've not found that in the documentation. companion object { //1 val MY_CONST = "something" //2 const val MY_CONST = "something" //3 val...

How to terminate a window in tmux?

How to terminate a window in tmux? Like the Ctrlak shortcut in screen with Ctrla being the prefix....

What are the differences between 'call-template' and 'apply-templates' in XSL?

I am new in XSLT so I'm little bit confused about the two tags, <xsl:apply-templates name="nodes"> and <xsl:call-template select="nodes"> So can you list out the difference between them?...

Is there a list of Pytz Timezones?

I would like to know what are all the possible values for the timezone argument in the Python library pytz. How to do it?...

printf %f with only 2 numbers after the decimal point?

In my printf, I need to use %f but I'm not sure how to truncate to 2 decimal places: Example: getting 3.14159 to print as: 3.14...

Static class initializer in PHP

I have an helper class with some static functions. All the functions in the class require a ‘heavy’ initialization function to run once (as if it were a constructor). Is there a good practice for achieving this? The only thing I thought of was ...

How to open an Excel file in C#?

I am trying to convert some VBA code to C#. I am new to C#. Currently I am trying to open an Excel file from a folder and if it does not exist then create it. I am trying something like the following. How can I make it work? Excel.Application objexc...

Table is marked as crashed and should be repaired

I am getting this error in wordpress phpMyadmin #145 - Table './DB_NAME/wp_posts' is marked as crashed and should be repaired When I login to phpMyadmin, it says wp_posts is "in use" My website is currently down because of this. I googled this ...

How to load/edit/run/save text files (.py) into an IPython notebook cell?

I've recently moved over to using IPython notebooks as part of my workflow. However, I've not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can...

Convert Java string to Time, NOT Date

I would like to convert a variable string to a Time type variable, not Date using Java. the string look like this 17:40 I tried using the code below but this instance is a date type variable not time String fajr_prayertime = prayerTimes.get(...

Spaces cause split in path with PowerShell

I'm having an issue with powershell when invoking an exe at a path containing spaces. PS C:\Windows Services> invoke-expression "C:\Windows Services\MyService.exe" The term 'C:\Windows' is not recognized as the name of a cmdlet, function, scr...

How to control the width and height of the default Alert Dialog in Android?

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Title"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { ...

Python int to binary string?

Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python? There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library....

How do you format an unsigned long long int using printf?

#include <stdio.h> int main() { unsigned long long int num = 285212672; //FYI: fits in 29 bits int normalInt = 5; printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt); ...

Check if a PHP cookie exists and if not set its value

I am working on a multilingual site so I tried this approach: echo $_COOKIE["lg"]; if (!isset($_COOKIE["lg"])) setcookie("lg", "ro"); echo $_COOKIE["lg"]; The idea is that if the client doesn't have an lg cookie (it is, therefore, the first ti...

SQL Stored Procedure: If variable is not null, update statement

I have an update statement in a stored procedure that looks generally like this: Update [TABLE_NAME] Set XYZ=@ABC Is there a good way to only trigger the update statement if the variable is not null or the value -1? Similar to an IF NOT EXISTS......

How do I cancel an HTTP fetch() request?

There is a new API for making requests from JavaScript: fetch(). Is there any built in mechanism for canceling these requests in-flight?...

CSS:Defining Styles for input elements inside a div

I have a div called "divContainer" inside which i have few input elements like textboxes,radio buttons et.. How can i define the style for then in the CSS ? I wanna mention styles for elements inside this purticular div.not for the entire form. Ex:...

Convert INT to FLOAT in SQL

I have this Query : SELECT sl.sms_prefix, sum( sl.parts ) , cp.country_name, CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4)) FROM sms_log sl, sms_transaction st, country_prefix cp WHERE st.customer_id =1 AND st.sendtime >...

How does one generate a random number in Apple's Swift language?

I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one's own program? Or is there a library that does this that we can use now?...

Convert varchar into datetime in SQL Server

How do I convert a string of format mmddyyyy into datetime in SQL Server 2008? My target column is in DateTime I have tried with Convert and most of the Date style values however I get an error message: 'The conversion of a varchar data type to...

Difference between git pull and git pull --rebase

I started using git sometime back and do not fully understand the intricacies. My basic question here is to find out the difference between a git pull and git pull --rebase , since adding the --rebase option does not seem to do something very differe...

Getting list of parameter names inside python function

Possible Duplicate: Getting method parameter names in python Is there an easy way to be inside a python function and get a list of the parameter names? For example: def func(a,b,c): print magic_that_does_what_I_want() >>> f...

remove attribute display:none; so the item will be visible

The element is: span { position:absolute; float:left; height:80px; width:150px; top:210px; left:320px; background-color:yellow; display:none; //No display border: 3px solid #...

Zoom in on a point (using scale and translate)

I want to be able to zoom in on the point under the mouse in an HTML 5 canvas, like zooming on Google Maps. How can I achieve that?...

mysql server port number

I've just made a database on mysql on my server. I want to connect to this via my website using php. This is the contents of my connections file: $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $conn = mysql_connect($dbhost, $dbuser,...

Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?...

Set mouse focus and move cursor to end of input using jQuery

This question has been asked in a few different formats but I can't get any of the answers to work in my scenario. I am using jQuery to implement command history when user hits up/down arrows. When up arrow is hit, I replace the input value with pre...

Android ADT error, dx.jar was not loaded from the SDK folder

I just downloaded Eclipse Galileo and installed ADT10 and tried to a phonegap app using this guide: http://www.phonegap.com/start But each time i try to build im getting this error: Unknown error: Unable to build: the file dx.jar was not loaded from ...

Selecting option by text content with jQuery

I want to set a dropdown box to whatever has been passed through a querystring using jquery. How do I add the selected attribute to an option such that the "TEXT" value is equal to a certain param from the query string? $(document).ready(func...

select count(*) from table of mysql in php

I am able to get both the value and row of the mysql query result. But I am struggling to get the single output of a query. e.g.: $result = mysql_query("SELECT COUNT(*) FROM Students;"); I need the result to display. But I am not getting the resu...

curl error 18 - transfer closed with outstanding read data remaining

when retrieving data from a URL using curl, I sometimes (in 80% of the cases) get error 18: transfer closed with outstanding read data remaining Part of the returned data is then missing. The weird thing is that this does never occur when the CURLO...

Disable scrolling in an iPhone web application?

Is there any way to completely disable web page scrolling in an iPhone web app? I've tried numerous things posted on google, but none seem to work. Here's my current header setup: <meta name="viewport" content="width=device-width; initial-scale=...

How to understand nil vs. empty vs. blank in Ruby

I find myself repeatedly looking for a clear definition of the differences of nil?, blank?, and empty? in Ruby on Rails. Here's the closest I've come: blank? objects are false, empty, or a whitespace string. For example, "", " ", nil, [], and {} a...

The easiest way to replace white spaces with (underscores) _ in bash

recently I had to write a little script that parsed VMs in XenServer and as the names of the VMs are mostly with white spaces in e.g Windows XP or Windows Server 2008, I had to trim those white spaces and replace them with underscores _ . I found a s...

Quick way to list all files in Amazon S3 bucket?

I have an amazon s3 bucket that has tens of thousands of filenames in it. What's the easiest way to get a text file that lists all the filenames in the bucket?...

How to get an object's properties in JavaScript / jQuery?

In JavaScript / jQuery, if I alert some object, I get either [object] or [object Object] Is there any way to know: what is the difference between these two objects what type of Object is this what all properties does this object contains and valu...

Order Bars in ggplot2 bar graph

I am trying to make a bar graph where the largest bar would be nearest to the y axis and the shortest bar would be furthest. So this is kind of like the Table I have Name Position 1 James Goalkeeper 2 Frank Goalkeeper 3 Jean Defense ...

Breaking out of a for loop in Java

In my code I have a for loop that iterates through a method of code until it meets the for condition. Is there anyway to break out of this for loop? So if we look at the code below, what if we want to break out of this for loop when we get to "15"?...

Calculate difference between two dates (number of days)?

I see that this question has been answered for Java, JavaScript, and PHP, but not C#. So, how might one calculate the number of days between two dates in C#?...

Passing multiple parameters with $.ajax url

I am facing problem in passing parrameters with ajax url.I think error is in parametters code syntax.Plz help. var timestamp = null; function waitformsg(id,name) { $.ajax({ type:"Post", url:"getdata.php?timestamp="+timestam...

What does the "no version information available" error from linux dynamic linker mean?

In our product we ship some linux binaries that dynamically link to system libraries like "libpam". On some customer systems we get the following error on stderr when the program runs: ./authpam: /lib/libpam.so.0: no version information available (...

Express.js: how to get remote client address

I don't completely understand how I should get a remote user IP address. Let's say I have a simple request route such as: app.get(/, function (req, res){ var forwardedIpsStr = req.header('x-forwarded-for'); var IP = ''; if (forwardedIpsSt...

if-else statement inside jsx: ReactJS

I need to change render function and run some sub render function when a specific state given, For example: render() { return ( <View style={styles.container}> if (this.state == 'news'){ return ( ...

How to query a MS-Access Table from MS-Excel (2010) using VBA

I am trying to write some vba code in Excel to query a table in Access. I have tried multiple code samples for this such as the added links and they all seem to fail at the "Open connection" part. I have tried using different references but I'm not s...

invalid types 'int[int]' for array subscript

This code throws up the compile error given in the title, can anyone tell me what to change? #include <iostream> using namespace std; int main(){ int myArray[10][10][10]; for (int i = 0; i <= 9; ++i){ for (int t = 0; t &...

Postgres DB Size Command

What is the command to find the size of all the databases? I am able to find the size of a specific database by using following command: select pg_database_size('databaseName'); ...

PHP regular expressions: No ending delimiter '^' found in

I've been having some trouble with regular expressions. This is my code $pattern = "^([0-9]+)$"; if (preg_match($pattern, $input)) echo "yes"; else echo "nope"; I run it and get: Warning: preg_match() [function.preg-match]: No ending ...

How to know elastic search installed version from kibana?

Currently I am getting these alerts: Upgrade Required Your version of Elasticsearch is too old. Kibana requires Elasticsearch 0.90.9 or above. Can someone tell me if there is a way I can find the exact installed version of ELS?...

Adding and removing style attribute from div with jquery

I've inherited a project I'm working on and I'm updating some jquery animations (very little practice with jquery). I have a div I need to add and remove the style attribute from. Here is the div: <div id='voltaic_holder'> At one point in t...

Java Minimum and Maximum values in Array

My code does not give errors, however it is not displaying the minimum and maximum values. The code is: Scanner input = new Scanner(System.in); int array[] = new int[10]; System.out.println("Enter the numbers now."); for (int i = 0; i < array....

Compiling an application for use in highly radioactive environments

We are compiling an embedded C++ application that is deployed in a shielded device in an environment bombarded with ionizing radiation. We are using GCC and cross-compiling for ARM. When deployed, our application generates some erroneous data and cra...

E: Unable to locate package npm

When I try to install npm with sudo apt-get install npm, I got following error: E: Unable to locate package npm Why can't apt find npm? I'm using Debian 9 and already did run sudo apt-get install nodejs ...

How to convert java.util.Date to java.sql.Date?

I am trying to use a java.util.Date as input and then creating a query with it - so I need a java.sql.Date. I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Jav...

Object of custom type as dictionary key

What must I do to use my objects of a custom type as keys in a Python dictionary (where I don't want the "object id" to act as the key) , e.g. class MyThing: def __init__(self,name,location,length): self.name = name self...

HTML radio buttons allowing multiple selections

In my HTML form I have the below as a set of radio buttons, depending on what radio button you select depends on what the next form <fieldset> is revealed, this all works. The problem is for some reason they are working like a check box and not...

Use ASP.NET MVC validation with jquery ajax?

I have simple ASP.NET MVC action like this : public ActionResult Edit(EditPostViewModel data) { } The EditPostViewModel have validation attributes like this : [Display(Name = "...", Description = "...")] [StringLength(100, MinimumLength = 3, E...

PHP - warning - Undefined property: stdClass - fix?

I get this warning in my error logs and wanted to know how to correct this issues in my code. Warning: PHP Notice: Undefined property: stdClass::$records in script.php on line 440 Some Code: // Parse object to get account id's // The response do...

How does Access-Control-Allow-Origin header work?

Apparently, I have completely misunderstood its semantics. I thought of something like this: A client downloads javascript code MyCode.js from http://siteA - the origin. The response header of MyCode.js contains Access-Control-Allow-Origin: http://...

Fastest way to ping a network range and return responsive hosts?

Constraints: 1. Speed matters. 2. I am allowed to ping once. I'm debating whether to use Python or shellscripting. Is there a method faster than bash? Here is the current code, for ip in $(seq int1 int2); do ping -c 1 xxx.xxx.xxx.$ip | grep ...

Setting Windows PATH for Postgres tools

I cannot access PostgreSQL through the command line in Windows. Although I am able to create and update the databases, access them through PGAdminIII, and push to Heroku, I am unable to access them directly through my command line using the psql comm...

Can't access Eclipse marketplace

I can't seem to access the Eclipse marketplace. I'm using Juno 4.2. I tried deleting eclipse and removing all plugins, deleting my .metadata, and deleting the eclipse app data. I've tried switching my default browser from firefox to chrome, I've tri...

What are the pros and cons of parquet format compared to other formats?

Characteristics of Apache Parquet are : Self-describing Columnar format Language-independent In comparison to Avro, Sequence Files, RC File etc. I want an overview of the formats. I have already read : How Impala Works with Hadoop File Formats ,...

Best way to check for null values in Java?

Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException. What is the best way to go about this? I've considered these methods. Which one is the best programming practice for Java? // ...

Pass mouse events through absolutely-positioned element

I'm attempting to capture mouse events on an element with another absolutely-positioned element on top of it. Right now, events on the absolutely-positioned element hit it and bubble up to its parent, but I want it to be "transparent" to these mouse...

How to TryParse for Enum value?

I want to write a function which can validate a given value (passed as a string) against possible values of an enum. In the case of a match, it should return the enum instance; otherwise, it should return a default value. The function may not intern...

Find which version of package is installed with pip

Using pip, is it possible to figure out which version of a package is currently installed? I know about pip install XYZ --upgrade but I am wondering if there is anything like pip info XYZ. If not what would be the best way to tell what version I am...

How do I retrieve my MySQL username and password?

I lost my MySQL username and password. How do I retrieve it?...

How do I exit a WPF application programmatically?

In the few years I've been using C# (Windows Forms), I've never used WPF. But, now I love WPF, but I don't know how I am supposed to exit my application when the user clicks on the Exit menu item from the File menu. I have tried: this.Dispose(); th...

Can a local variable's memory be accessed outside its scope?

I have the following code. #include <iostream> int * foo() { int a = 5; return &a; } int main() { int* p = foo(); std::cout << *p; *p = 8; std::cout << *p; } And the code is just running with no runt...

Git Push Error: insufficient permission for adding an object to repository database

When I try to push to a shared git remote, I get the following error: insufficient permission for adding an object to repository database Then I read about a fix here: Fix This worked for the next push, since all of the files were of the correct gr...

Convert from MySQL datetime to another format with PHP

I have a datetime column in MySQL. How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?...

Swap x and y axis without manually swapping values

So I have a set of data that has conditional formatting. Basically it's a set of photometric measurements of stars that I want to put on a chart with different colors for stars in different ranges of Color Index (basically color them by their spectra...

Get value from input (AngularJS)

I have the following inputs and need their values: <input type="hidden" ng-model="movie" value="harry_potter"/> <input type="text" ng-model="year" value="2000"/> What can I do to get the value of each input?...

how to check for datatype in node js- specifically for integer

I tried the following to check for the datatype (specifically for integer), but not working. var i = "5"; if(Number(i) = 'NaN') { console.log('This is not number')); } ...

Eclipse hangs on loading workbench

My eclipse stops loading workbench. I tried already starting with ./eclipse --clean When starting from console it throws following exception: java.lang.NullPointerException at org.eclipse.core.internal.runtime.Log.isLoggable(Log.java:101) at ...

Converting a Pandas GroupBy output from Series to DataFrame

I'm starting with input data like this df1 = pandas.DataFrame( { "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } ) Which when printed ap...

jquery change style of a div on click

I have a div, with a specific style(let's say a certain background). What I want is, when one clicks on a list element having that div applied another specific style (another background type) to be applied to that div, If another area in a differen...

How to pass credentials to httpwebrequest for accessing SharePoint Library

I'm trying to read files from a SharePoint document library using HttpWebRequest. In order to do that I have to pass some credentials. I'm using the below request: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "...

Copy folder recursively, excluding some folders

I am trying to write a simple bash script that will copy the entire contents of a folder including hidden files and folders into another folder, but I want to exclude certain specific folders. How could I achieve this?...

How to create PDF files in Python

I'm working on a project which takes some images from user and then creates a PDF file which contains all of these images. Is there any way or any tool to do this in Python? E.g. to create a PDF file (or eps, ps) from image1 + image 2 + image 3 -> P...

Make a negative number positive

I have a Java method in which I'm summing a set of numbers. However, I want any negatives numbers to be treated as positives. So (1)+(2)+(1)+(-1) should equal 5. I'm sure there is very easy way of doing this - I just don't know how....

Set default time in bootstrap-datetimepicker

I want to set default time in this datetimepicker as 00:01 for the current date. Anyone tried that before? Having a tough time with it. It Seems simple. $('#startdatetime-from').datetimepicker({ language: 'en', format: 'yyyy-MM-dd hh:mm' });...

Getting "project" nuget configuration is invalid error

I'm getting "[project] nuget configuration is invalid" error. I received an error like this before and used the 'Update Nuget package manager' solution mentioned here: Unable to Install Any Package in Visual Studio 2015 I've also tried the other so...

iOS start Background Thread

I have a small sqlitedb in my iOS device. When a user presses a button, I fetch the data from sqlite & show it to user. This fetching part I want to do it in a background thread (to not block the UI main thread). I do this like so - [self perf...

This version of the application is not configured for billing through Google Play

When I try to run my application with in-app billing I am getting the error: "This version of the application is not configured for billing through Google Play. Check the help center for more information". I have the billing permission already in th...

How to prevent page from reloading after form submit - JQuery

I am working on a website for my app development class and I have the weirdest issue. I am using a bit of JQuery to send form data to a php page called 'process.php, and then upload it to my DB. The weird bug is that the page reloads upon submittin...

What is the best way to programmatically detect porn images?

Akismet does an amazing job at detecting spam comments. But comments are not the only form of spam these days. What if I wanted something like akismet to automatically detect porn images on a social networking site which allows users to upload their ...

How to change Named Range Scope

When I create a named range through the Name Manager, I'm given the option of specifying Workbook or [worksheet name] scope. But if then want to change scope, the drop-down is grayed out. Is there a way, in either Name Manager or, preferablly, VBA to...

What is the meaning of curly braces?

Just starting to figure Python out. I've read this question and its responses: Is it true that I can't use curly braces in Python? and I still can't fathom how curly braces work, especially since pages like Simple Programs: http://wiki.python...

What is base 64 encoding used for?

I've heard people talking about "base 64 encoding" here and there. What is it used for?...

Return array in a function

I have an array int arr[5] that is passed to a function fillarr(int arr[]): int fillarr(int arr[]) { for(...); return arr; } How can I return that array? How will I use it, say I returned a pointer how am I going to access it? ...

Boxplot show the value of mean

In this boxplot we can see the mean but how can we have also the number value on the plot for every mean of every box plot? ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() + stat_summary(fun.y=mean, colour="darkre...

Set ANDROID_HOME environment variable in mac

I am new in developing native app using Salesforce SDK. I tried to create android project from command line using forcedroid tool but there is problem in setting environment variable named ANDROID_HOME. But i don't know how to set this variable. I ...

How to handle back button in activity

How to handle a back button in an activity? I have some buttons. If I click one of the button it's redirecting to the buttons which I required. It's working fine but When I press back button it gets finished. How to solve this problem. I have only o...

how to do file upload using jquery serialization

So I have a form and I'm submitting the form through ajax using jquery serialization function serialized = $(Forms).serialize(); $.ajax({ type : "POST", cache : false, url : "blah", dat...

javascript password generator

What would be the best approach to creating a 8 character random password containing a-z, A-Z and 0-9? Absolutely no security issues, this is merely for prototyping, I just want data that looks realistic. I was thinking a for (0 to 7) Math.random t...

Create a File object in memory from a string in Java

I have a function that accepts File as an argument. I don't want to create/write a new File (I don't have write access to filesystem) in order to pass my string data to the function. I should add that the String data don't exist in a file (so I canno...

How to make a simple collection view with Swift

I'm trying to learn how to use UICollectionView. The documentation is a little hard to understand and the tutorials that I found were either in Objective C or long complicated projects. When I was learning how to use UITableView, We ? Swift's How to...

How do I initialize the base (super) class?

In Python, consider I have the following code: >>> class SuperClass(object): def __init__(self, x): self.x = x >>> class SubClass(SuperClass): def __init__(self, y): self.y = y # how do I initialize...

How to pass argument to Makefile from command line?

How to pass argument to Makefile from command line? I understand I can do $ make action VAR="value" $ value with Makefile VAR = "default" action: @echo $(VAR) How do I get the following behavior? $ make action value value ? How about ...

Checkout another branch when there are uncommitted changes on the current branch

Most of the time when I try to checkout another existing branch, Git doesn't allow me if I have some uncommitted changes on the current branch. So I'll have to commit or stash those changes first. However, occasionally Git does allow me to checkout...

How to change an application icon programmatically in Android?

Is it possible to change an application icon directly from the program? I mean, change icon.png in the res\drawable folder. I would like to let users to change application's icon from the program so next time they would see the previously selected ic...

How to select label for="XYZ" in CSS?

HTML: <label for="email">{t _your_email}:</label> CSS: label { display: block; width: 156px; cursor: pointer; padding-right: 6px; padding-bottom: 1px; } I wish to select the label based on the 'for' attribute to make...

Check if cookies are enabled

I am working on a page that requires javascript and sessions. I already have code to warn the user if javascript is disabled. Now, I want to handle the case where cookies are disabled, as the session id is stored in cookies. I have thought of just a...

Scala Doubles, and Precision

Is there a function that can truncate or round a Double? At one point in my code I would like a number like: 1.23456789 to be rounded to 1.23...

How to create a multi line body in C# System.Net.Mail.MailMessage

If create the body property as System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.Body ="First Line \n second line"; I also tried message.Body ="First Line" + system.environment + "second line"; Both of these wer...

String vs. StringBuilder

I understand the difference between String and StringBuilder (StringBuilder being mutable) but is there a large performance difference between the two? The program I’m working on has a lot of case driven string appends (500+). Is using StringBuil...

No visible cause for "Unexpected token ILLEGAL"

I'm getting this JavaScript error on my console: Uncaught SyntaxError: Unexpected token ILLEGAL This is my code: _x000D_ _x000D_ var foo = 'bar';?_x000D_ _x000D_ _x000D_ It's super simple, as you can see. How could it be causing a syntax err...

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I have a Play Framework application and I was using Hibernate 4.2.5.Final (which is retrieved via the Maven dependency manager). I decided to upgrade to Hibernate 4.3.0.Final, recompile my application successfully, and ran it. I got the exception b...

How to specify legend position in matplotlib in graph coordinates

I am aware of the bbox_to_anchor keyword and this thread, which very helpfully suggests how to manually place the legend: How to put the legend out of the plot However, I'd like to use the coordinates of my x- and y-axis in the graph to specify the...

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

I need to perform some operations on scope and the template. It seems that I can do that in either the link function or the controller function (since both have access to the scope). When is it the case when I have to use link function and not the c...

Bootstrap Modal before form Submit

I'm new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from the form fields. I searched all over the internet but can't find the right one ...

Opening a new tab to read a PDF file

I am probably missing something simple here, however i will ask anyway. I have made a link to open up a PDF file, however it opens up in the current tab rather than a new one. What code shall i use in HTML to open a new tab to read the PDF file. <...

How to check permissions of a specific directory?

I know that using ls -l "directory/directory/filename" tells me the permissions of a file. How do I do the same on a directory? I could obviously use ls -l on the directory higher in the hierarchy and then just scroll till I find it but it's such a ...

pycharm running way slow

I'm a big fan of PyCharm by JetBrains but I do run into some issues that I thought maybe I'll ask here about. It hangs unexpectedly and this happens often. Overall, its a little bit slow for my taste and I would love some tips on how to increase th...

Node.js check if path is file or directory

I can't seem to get any search results that explain how to do this. All I want to do is be able to know if a given path is a file or a directory (folder)....

Create an Excel file using vbscripts

How do I create an excel file using VBScript? I searched the net but it just mentions opening an existing file. This is the extraction from the Internet shown below Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workboo...

How to change the default collation of a table?

create table check2(f1 varchar(20),f2 varchar(20)); creates a table with the default collation latin1_general_ci; alter table check2 collate latin1_general_cs; show full columns from check2; shows the individual collation of the columns as 'lati...

google-services.json for different productFlavors

Update: GCM is deprecated, use FCM I'm implementing the new Google Cloud Messaging following the guides from the Google Developers page here I've successfully run and test it. But my problem now is I have different product flavors with differen...

Angular2 @Input to a property with get/set

I have an Angular2 component in that component it currently has a bunch fields that have @Input() applied before them to allow binding to that property, i.e. @Input() allowDay: boolean; What I would like to do is actually bind to a property with g...

How to join two JavaScript Objects, without using JQUERY

I have two json objects obj1 and obj2, i want to merge them and crete a single json object. The resultant json should have all the values from obj2 and the values from obj1 which is not present in obj2. Question: var obj1 = { "name":"manu", ...

Android Google Maps API V2 Zoom to Current Location

I'm trying to mess around with the Maps API V2 to get more familiar with it, and I'm trying to start the map centered at the user's current location. Using the map.setMyLocationEnabled(true); statement, I am able to show my current location on the ma...

Taking the record with the max date

Let's assume I extract some set of data. i.e. SELECT A, date FROM table I want just the record with the max date (for each value of A). I could write SELECT A, col_date FROM TABLENAME t_ext WHERE col_date = (SELECT MAX (col_date) ...

How can I enable CORS on Django REST Framework

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

Easiest way to develop simple GUI in Python

I'm done with my class project which I coded using Python. I'm working on the extra credit part i.e. GUI development - Windows platform. I need something simple, easy to use, possibly drag-and-drop GUI development tool for Python. GUI needs to look ...

How to loop through each and every row, column and cells in a GridView and get its value

I have a GridView which is databound, on button_click I want to read the GridView row by row each column and read the value of each cell in a row and update a table in database? I also know how to check if that cell contains null. I am trying someth...

SQL Server converting varbinary to string

I want to do conversion in T-SQL from a varbinary type to string type Here is an example : First I got this varbinary 0x21232F297A57A5A743894A0E4A801FC3 And then I want to convert it to 21232f297a57a5a743894a0e4a801fc3 How to do this?...

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

I am getting following error, when I run the demo JSF application on the console [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property. ...

How to make a phone call programmatically?

I'm passing to an activity the number to call by a bundle and then, in such activity, I have a button to call to that number, this is the code: callButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { ...

How to set up tmux so that it starts up with specified windows opened?

How to set up tmux so that it starts up with specified windows opened?...

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

I'm trying to install mysql inside a docker container,Tried various images from github, it seems they all manage to successfully install the mysql but when I try to run the mysql it gives an error: ERROR 2002 (HY000): Can't connect to local MySQL...

How to install iPhone application in iPhone Simulator

I have a mySample.app file - an iPhone application developed by xcode. How do I run this (only mySample.app file) application using my xcode?...

Function pointer to member function

I'd like to set up a function pointer as a member of a class that is a pointer to another function in the same class. The reasons why I'm doing this are complicated. In this example, I would like the output to be "1" class A { public: int f(); in...

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

I have a mapping application that can add ArcGIS 9.3+ base maps given a URL. One of the URLs that I would like to add is from a customer's URL and is secured. My mapping application was using Java 6 before and was able to add the secure URL with no...

Is it better to use path() or url() in urls.py for django 2.0?

In a django online course, the instructor has us use the url() function to call views and utilize regular expressions in the urlpatterns list. I've seen other examples on youtube of this. e.g. from django.contrib import admin from django.urls import...

Shell equality operators (=, ==, -eq)

Can someone please explain the difference between =, == and -eq in shell scripting? Is there any difference between the following? [ $a = $b ] [ $a == $b ] [ $a -eq $b ] Is it simply that = and == are only used when the variables contain numbers?...

Printing object properties in Powershell

When working in the interactive console if I define a new object and assign some property values to it like this: $obj = New-Object System.String $obj | Add-Member NoteProperty SomeProperty "Test" Then when I type the name of my variable into the ...

How to show "Done" button on iPhone number pad

There is no "Done" button on the number pad. When a user finishes entering numeric information in a text field, how can I make the number pad disappear? I could get a "Done" button by using the default keyboard, but then users would have to switch t...

Styling HTML email for Gmail

I'm generating a html email that uses an internal stylesheet, i.e. <!doctype html> <html> <head> <style type="text/css"> h2.foo {color: red} </style> </head> <body> <h2 class="foo">Email c...

How to make ConstraintLayout work with percentage values?

With a Preview 1 of Android Studio 2.2 Google released a new layout in its support library: ConstraintLayout. With ConstraintLayout it is easier to use a Design tool in Android Studio, but I didn't find a way to use relative sizes (percents or 'weigh...

Fastest way to serialize and deserialize .NET objects

I'm looking for the fastest way to serialize and deserialize .NET objects. Here is what I have so far: public class TD { public List<CT> CTs { get; set; } public List<TE> TEs { get; set; } public string Code { get; set; } ...

Loop over html table and get checked checkboxes (JQuery)

I have an HTML table with a checkbox in each row. I want to loop over the table and see if there are any checkboxes that are checked. The following does not work: $("#save").click( function() { $('#mytable tr').each(function (i, row) { ...

Git - What is the difference between push.default "matching" and "simple"

I have been using git for a while now, but I have never had to set up a new remote repo myself and I have been curious on doing so. I have been reading tutorials and I am confused on how to get "git push" to work. If I simply use git push it asks m...

grep regex whitespace behavior

I have a textfile, containing something like: 12,34 EUR 5,67 EUR ... There is one whitespace before 'EUR' and I ignore 0,XX EUR. I tried: grep '[1-9][0-9]*,[0-9]\{2\}\sEUR' => didn't match ! grep '[1-9][0-9]*,[0-9]\{2\} EUR' => worked...

How can I format a list to print each element on a separate line in python?

How can I format a list to print each element on a separate line? For example I have: mylist = ['10', '12', '14'] and I wish to format the list so it prints like this: 10 12 14 so the \n, brackets, commas and '' is removed and each element is p...

Get original URL referer with PHP?

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

java build path problems

From someone's project, I am getting this error: Java Build Path Problems (1 item) Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workplace that are strictly compatible with this environment. I have the ...

Python convert tuple to string

I have a tuple of characters like such: ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') How do I convert it to a string so that it is like: 'abcdgxre' ...

Undefined reference to `pow' and `floor'

I'm trying to make a simple fibonacci calculator in C but when compiling gcc tells me that I'm missing the pow and floor functions. What's wrong? Code: #include <stdio.h> #include <math.h> int fibo(int n); int main() { printf(...

Fragment MyFragment not attached to Activity

I've created a small test app which represents my problem. I'm using ActionBarSherlock to implement tabs with (Sherlock)Fragments. My code: TestActivity.java public class TestActivity extends SherlockFragmentActivity { private ActionBar actionB...

How to create a new text file using Python

I'm practicing the management of .txt files in python. I've been reading about it and found that if I try to open a file that doesn't exists yet it will create it on the same directory from where the program is being executed. The problem comes that ...

How to pass arguments from command line to gradle

I'm trying to pass an argument from command line to a java class. I followed this post: http://gradle.1045684.n5.nabble.com/Gradle-application-plugin-question-td5539555.html but the code does not work for me (perhaps it is not meant for JavaExec?). ...

Function to get yesterday's date in Javascript in format DD/MM/YYYY

I've been looking for a while to get yesterday's date in format DD/MM/YYYY. Here's my current code: var $today = new Date(); var $dd = $today.getDate(); var $mm = $today.getMonth()+1; //January is 0! var $yyyy = $today.getFullYear(); if($dd<10){...

Multiple linear regression in Python

I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.). For example, with this dat...

Last executed queries for a specific database

I know how to get the last executed queries using the following SQL in SSMS - SELECT deqs.last_execution_time AS [Time], dest.text AS [Query] FROM sys.dm_exec_query_stats AS deqs CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest ORDER BY deq...

How to prevent a click on a '#' link from jumping to top of page?

I'm currently using <a> tags with jQuery to initiate things like click events, etc. Example is <a href="#" class="someclass">Text</a> But I hate how the '#' makes the page jump to the top of the page. What can I do instead?...