Programs & Examples On #Picturegallery

Clear and refresh jQuery Chosen dropdown list

If trigger("chosen:updated"); not working, use .trigger("liszt:updated"); of @Nhan Tran it is working fine.

How to add a char/int to an char array in C?

strcat has the declaration:

char *strcat(char *dest, const char *src)

It expects 2 strings. While this compiles:

char str[1024] = "Hello World";
char tmp = '.';

strcat(str, tmp);

It will cause bad memory issues because strcat is looking for a null terminated cstring. You can do this:

char str[1024] = "Hello World";
char tmp[2] = ".";

strcat(str, tmp);

Live example.

If you really want to append a char you will need to make your own function. Something like this:

void append(char* s, char c) {
        int len = strlen(s);
        s[len] = c;
        s[len+1] = '\0';
}

append(str, tmp)

Of course you may also want to check your string size etc to make it memory safe.

Dark color scheme for Eclipse

This is another dark Eclipse theme: http://blog.prabir.me/post/Dark-Eclipse-Theme.aspx.

I have the Visual Studio equivalent of the theme.

Convert Base64 string to an image file?

An easy way I'm using:

file_put_contents($output_file, file_get_contents($base64_string));

This works well because file_get_contents can read data from a URI, including a data:// URI.

Disable/turn off inherited CSS3 transitions

If you want to disable a single transition property, you can do:

transition: color 0s;

(since a zero second transition is the same as no transition.)

Merge a Branch into Trunk

The syntax is wrong, it should instead be

svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>

Comparison between Corona, Phonegap, Titanium

You should learn objective c and program native apps. Do not rely on these things you think will make life easier. Apple has made sure the easiest way is using their native tools and language. For your 100 lines of javascript I can do the same in 3 lines of code or no code at all depending on the element. Watch some tutorials - if you understand javascript then objective c is not hard. Workarounds are miserable and apple can pull the plug on you anytime they want.

How can I get the UUID of my Android phone in an application?

Instead of getting IMEI from TelephonyManager use ANDROID_ID.

Settings.Secure.ANDROID_ID

This works for each android device irrespective of having telephony.

Initialise numpy array of unknown length

a = np.empty(0)
for x in y:
    a = np.append(a, x)

How do I read a response from Python Requests?

Requests doesn't have an equivalent to Urlib2's read().

>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.

Edit for Python 3:

Python now handles data types differently. response.content returns a sequence of bytes (integers that represent ASCII) while response.text is a string (sequence of chars).

Thus,

>>> print response.content == response.text
False

>>> print str(response.content) == response.text
True

How can I apply a function to every row/column of a matrix in MATLAB?

Building on Alex's answer, here is a more generic function:

applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :));
newApplyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1), 'UniformOutput', false)';
takeAll = @(x) reshape([x{:}], size(x{1},2), size(x,1))';
genericApplyToRows = @(func, matrix) takeAll(newApplyToRows(func, matrix));

Here is a comparison between the two functions:

>> % Example
myMx = [1 2 3; 4 5 6; 7 8 9];
myFunc = @(x) [mean(x), std(x), sum(x), length(x)];
>> genericApplyToRows(myFunc, myMx)

ans =

     2     1     6     3
     5     1    15     3
     8     1    24     3

>> applyToRows(myFunc, myMx)
??? Error using ==> arrayfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.

Error in ==> @(func,matrix)arrayfun(applyToGivenRow(func,matrix),1:size(matrix,1))'

Where is Java's Array indexOf?

For primitives, if you want to avoid boxing, Guava has helpers for primitive arrays e.g. Ints.indexOf(int[] array, int target)

How Can I Truncate A String In jQuery?

  function truncateString(str, length) {
     return str.length > length ? str.substring(0, length - 3) + '...' : str
  }

How to run jenkins as a different user

If you really want to run Jenkins as you, I suggest you check out my Jenkins.app. An alternative, easy way to run Jenkins on Mac.

See https://github.com/stisti/jenkins-app/

Download it from https://github.com/stisti/jenkins-app/downloads

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

When ever I got this problem:

AttributeError: module 'enum' has no attribute 'IntFlag'

simply first i run the command:

unset PYTHONPATH 

and then run my desired command then got success in that.

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

Go to Start > Programs > Microsoft SQL Server > Enterprise Manager

Right-click the SQL Server instance name > Select Properties from the context menu > Select Security node in left navigation bar

Under Authentication section, select SQL Server and Windows Authentication

Note: The server must be stopped and re-started before this will take effect

Error 18452 (not associated with a trusted sql server connection)

Put icon inside input element in a form

I find this the best and cleanest solution to it. Using text-indent on the input element

CSS:

#icon{
    background-image:url(../images/icons/dollar.png); 
    background-repeat: no-repeat; 
    background-position: 2px 3px;
}

HTML:

<input id="icon" style="text-indent:17px;" type="text" placeholder="Username" />

Xampp MySQL not starting - "Attempting to start MySQL service..."

  1. In the cmd type: services.msc Find MySql and change properties to the disabled.
  2. In the control panel of Xampp uninstall MySql by the checkbox on the left side, and install again by the click in the same checkbox.

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

How to compile or convert sass / scss to css with node-sass (no Ruby)?

I picked node-sass implementer for libsass because it is based on node.js.

Installing node-sass

  • (Prerequisite) If you don't have npm, install Node.js first.
  • $ npm install -g node-sass installs node-sass globally -g.

This will hopefully install all you need, if not read libsass at the bottom.

How to use node-sass from Command line and npm scripts

General format:

$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css

Examples:

  1. $ node-sass my-styles.scss my-styles.css compiles a single file manually.
  2. $ node-sass my-sass-folder/ -o my-css-folder/ compiles all the files in a folder manually.
  3. $ node-sass -w sass/ -o css/ compiles all the files in a folder automatically whenever the source file(s) are modified. -w adds a watch for changes to the file(s).

More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.

You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.

  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • Add "sass": "node-sass -w sass/ -o css/" to scripts in package.json file. It should look something like this:
"scripts": {
    "test" : "bla bla bla",
    "sass": "node-sass -w sass/ -o css/"
 }
  • $ npm run sass will compile your files.

How to use with gulp

  • $ npm install -g gulp installs Gulp globally.
  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • $ npm install --save-dev gulp installs Gulp locally. --save-dev adds gulp to devDependencies in package.json.
  • $ npm install gulp-sass --save-dev installs gulp-sass locally.
  • Setup gulp for your project by creating a gulpfile.js file in your project root folder with this content:
'use strict';
var gulp = require('gulp');

A basic example to transpile

Add this code to your gulpfile.js:

var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
  gulp.src('./sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

$ gulp sass runs the above task which compiles .scss file(s) in the sass folder and generates .css file(s) in the css folder.

To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js:

gulp.task('sass:watch', function () {
  gulp.watch('./sass/**/*.scss', ['sass']);
});

All is set now! Just run the watch task:

$ gulp sass:watch

How to use with Node.js

As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.

What about libsass?

Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:

LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.

How do I redirect a user when a button is clicked?

$("#yourbuttonid").click(function(){ document.location = "<%= Url.Action("Youraction") %>";})

Amazon Linux: apt-get: command not found

There can be 2 issues :=

1. Your are trying the command in machine that does not support apt-get command
because apt-get is suitable for Linux based Ubuntu machines; for MAC, try
apt-get equivalent such as Brew

2. The other issue can be that your installation was not completed properly So

The short answer:

Re-install Ubuntu from a Live CD or USB.

The long version:

The long version would be a waste of your time: your system will never
be clean, but if you insist you could try:

==> Copying everything (missing) except for the /home folder from the Live
CD/USB to your HDD.

OR

==> Do a re-install/repair over the broken system again with the Live
CD / USB stick.

OR

==> Download the deb file for apt-get and install as explained on above posts.
I would definitely go for a fresh new install as there are so many things to
do and so little time.

How to give Jenkins more heap space when it´s started as a service under Windows?

From the Jenkins wiki:

The JVM launch parameters of these Windows services are controlled by an XML file jenkins.xml and jenkins-slave.xml respectively. These files can be found in $JENKINS_HOME and in the slave root directory respectively, after you've install them as Windows services.

The file format should be self-explanatory. Tweak the arguments for example to give JVM a bigger memory.

https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+as+a+Windows+service

Defining private module functions in python

In Python, "privacy" depends on "consenting adults'" levels of agreement - you can't force it (any more than you can in real life;-). A single leading underscore means you're not supposed to access it "from the outside" -- two leading underscores (w/o trailing underscores) carry the message even more forcefully... but, in the end, it still depends on social convention and consensus: Python's introspection is forceful enough that you can't handcuff every other programmer in the world to respect your wishes.

((Btw, though it's a closely held secret, much the same holds for C++: with most compilers, a simple #define private public line before #includeing your .h file is all it takes for wily coders to make hash of your "privacy"...!-))

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Example of uppercasedFirstCharacter convenience property in Swift3 and Swift4.

Property uppercasedFirstCharacterNew demonstrates how to use String slicing subscript in Swift4.

extension String {

   public var uppercasedFirstCharacterOld: String {
      if characters.count > 0 {
         let splitIndex = index(after: startIndex)
         let firstCharacter = substring(to: splitIndex).uppercased()
         let sentence = substring(from: splitIndex)
         return firstCharacter + sentence
      } else {
         return self
      }
   }

   public var uppercasedFirstCharacterNew: String {
      if characters.count > 0 {
         let splitIndex = index(after: startIndex)
         let firstCharacter = self[..<splitIndex].uppercased()
         let sentence = self[splitIndex...]
         return firstCharacter + sentence
      } else {
         return self
      }
   }
}

let lorem = "lorem".uppercasedFirstCharacterOld
print(lorem) // Prints "Lorem"

let ipsum = "ipsum".uppercasedFirstCharacterNew
print(ipsum) // Prints "Ipsum"

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

Cleanest way to build an SQL string in Java

Why do you want to generate all the sql by hand? Have you looked at an ORM like Hibernate Depending on your project it will probably do at least 95% of what you need, do it in a cleaner way then raw SQL, and if you need to get the last bit of performance you can create the SQL queries that need to be hand tuned.

How to select option in drop down protractorjs e2e tests

We can create a custom DropDown class for this and add a method as:

async selectSingleValue(value: string) {
        await this.element.element(by.xpath('.//option[normalize-space(.)=\'' + value + '\']')).click();
    }

Also, to verify what value is currently selected, we can have:

async getSelectedValues() {
        return await this.element.$('option:checked').getText();
    }

Get Hours and Minutes (HH:MM) from date

If you want to display 24 hours format use:

SELECT FORMAT(GETDATE(),'HH:mm')

and to display 12 hours format use:

SELECT FORMAT(GETDATE(),'hh:mm')

How to get character array from a string?

Array.prototype.slice will do the work as well.

_x000D_
_x000D_
const result = Array.prototype.slice.call("Hello world!");_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How to make a owl carousel with arrows instead of next previous

This is how you do it in your $(document).ready() function with FontAwesome Icons:

 $( ".owl-prev").html('<i class="fa fa-chevron-left"></i>');
 $( ".owl-next").html('<i class="fa fa-chevron-right"></i>');

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

There is also some more detail on the use of <mvc:annotation-driven /> in the Spring docs. In a nutshell, <mvc:annotation-driven /> gives you greater control over the inner workings of Spring MVC. You don't need to use it unless you need one or more of the features outlined in the aforementioned section of the docs.

Also, there are other "annotation-driven" tags available to provide additional functionality in other Spring modules. For example, <transaction:annotation-driven /> enables the use of the @Transaction annotation, <task:annotation-driven /> is required for @Scheduled et al...

How to figure out the SMTP server host?

You can use the dig/host command to look up the MX records to see which mail server is handling mails for this domain.

On Linux you can do it as following for example:

$ host google.com
google.com has address 74.125.127.100
google.com has address 74.125.67.100
google.com has address 74.125.45.100
google.com mail is handled by 10 google.com.s9a2.psmtp.com.
google.com mail is handled by 10 smtp2.google.com.
google.com mail is handled by 10 google.com.s9a1.psmtp.com.
google.com mail is handled by 100 google.com.s9b2.psmtp.com.
google.com mail is handled by 10 smtp1.google.com.
google.com mail is handled by 100 google.com.s9b1.psmtp.com.

(as you can see, google has quite a lot of mail servers)

If you are working with windows, you might use nslookup (?) or try some web tool (e.g. that one) to display the same information.

Although that will only tell you the mail server for that domain. All other settings which are required can't be gathered that way. You might have to ask the provider.

How to change the default background color white to something else in twitter bootstrap

Its not recommended to overwrite bootstrap file, just in your local style.css use

body{background: your color !important;

here !important declaration overwrite bootstrap value.

The calling thread cannot access this object because a different thread owns it

As mentioned here, Dispatcher.Invoke could freeze the UI. Should use Dispatcher.BeginInvoke instead.

Here is a handy extension class to simplify the checking and calling dispatcher invocation.

Sample usage: (call from WPF window)

this Dispatcher.InvokeIfRequired(new Action(() =>
{
    logTextbox.AppendText(message);
    logTextbox.ScrollToEnd();
}));

Extension class:

using System;
using System.Windows.Threading;

namespace WpfUtility
{
    public static class DispatcherExtension
    {
        public static void InvokeIfRequired(this Dispatcher dispatcher, Action action)
        {
            if (dispatcher == null)
            {
                return;
            }
            if (!dispatcher.CheckAccess())
            {
                dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
                return;
            }
            action();
        }
    }
}

Regex: Check if string contains at least one digit

you could use look-ahead assertion for this:

^(?=.*\d).+$

Splitting a string into separate variables

Like this?

$string = 'FirstPart SecondPart'
$a,$b = $string.split(' ')
$a
$b

scp from Linux to Windows

As @Hesham Eraqi suggested, it worked for me in this way (transfering from Ubuntu to Windows (I tried to add a comment in that answer but because of reputation, I couldn't)):

pscp -v -r -P 53670 [email protected]:/data/genetic_map/sample/P2_283/* \\Desktop-mojbd3n\d\cc_01-1940_data\

where:

-v: show verbose messages.
-r: copy directories recursively.
-P: connect to specified port.
53670: the port number to connect the Ubuntu server.
\\Desktop-mojbd3n\d\genetic_map_data\: I needed to transfer to an external HDD, thus I had to give permissions of sharing to this device.

Chrome Extension - Get DOM content

The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.

Regarding your question if content scripts or background pages are the way to go:

Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.

Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.


Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:

background.js:

// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
});

content.js:

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message has the expected format...
    if (msg.text === 'report_back') {
        // Call the specified callback, passing
        // the web-page's DOM content as argument
        sendResponse(document.all[0].outerHTML);
    }
});

manifest.json:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",
  ...

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}

variable is not declared it may be inaccessible due to its protection level

If I remember correctly, this is the default property for controls.

Can you try by going into Design-View for the admin_reasons that contains the specified Control, then changing the control's Modifiers property to Public or Internal.

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

This was totally my bad.

I was using standard node http.request on a part of the code which should be sending requests to only http adresses. Seems like the db had a single https address which was queried with a random interval.

Simply, I was trying to send a http request to https.

Get the last insert id with doctrine 2?

Here i post my code, after i have pushed myself for one working day to find this solution.

Function to get the last saved record :

private function getLastId($query) {
        $conn = $this->getDoctrine()->getConnection();
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $lastId = $stmt->fetch()['id'];
        return $lastId;
    }

Another Function which call the above function

private function clientNum() {
        $lastId = $this->getLastId("SELECT id FROM client ORDER BY id DESC LIMIT 1");
        $noClient = 'C' . sprintf("%06d", $lastId + 1); // C000002 if the last record ID is 1
        return $noClient;
    }

Spring-boot default profile for integration tests

You could put an application.properties file in your test/resources folder. There you set

spring.profiles.active=test

This is kind of a default test profile while running tests.

Tkinter example code for multiple windows, why won't buttons load correctly?

You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button, but also for other widgets and non-gui objects such as StringVar.

Quick fix: add the frame new as the first argument to your Button in Demo2.

Possibly better: Currently you have Demo2 inheriting from tk.Frame but I think this makes more sense if you change Demo2 to be something like this,

class Demo2(tk.Toplevel):     
    def __init__(self):
        tk.Toplevel.__init__(self)
        self.title("Demo 2")
        self.button = tk.Button(self, text="Button 2", # specified self as master
                                width=25, command=self.close_window)
        self.button.pack()

    def close_window(self):
        self.destroy()

Just as a suggestion, you should only import tkinter once. Pick one of your first two import statements.

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Typically you add a class selector to the :not() pseudo-class like so:

:not(.printable) {
    /* Styles */
}

:not([attribute]) {
    /* Styles */
}

But if you need better browser support (IE8 and older don't support :not()), you're probably better off creating style rules for elements that do have the "printable" class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.

Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that are .printable, or otherwise affect them one way or another. For example, although display is not inherited, setting display: none on a :not(.printable) will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using visibility: hidden instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.

Why doesn't git recognize that my file has been changed, therefore git add not working

TL;DR; Are you even on the correct repository?

My story is bit funny but I thought it can happen with someone who might be having a similar scenario so sharing it here.

Actually on my machine, I had two separate git repositories repo1 and repo2 configured in the same root directory named source. These two repositories are essentially the repositories of two products I work off and on in my company. Now the thing is that as a standard guideline, the directory structure of source code of all the products is exactly the same in my company.

So without realizing I modified an exactly same named file in repo2 which I was supposed to change in repo1. So, I just kept running command git status on repo1 and it kept giving the same message

On branch master

nothing to commit, working directory clean

for half an hour. Then colleague of mine observed it as independent pair of eyes and brought this thing to my notice that I was in wrong but very similar looking repository. The moment I switched to repo1 Git started noticing the changed files.

Not so common case. But you never know!

How do I find the parent directory in C#?

You can use System.IO.Directory.GetParent() to retrieve the parent directory of a given directory.

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

    // pop back stack all the way
    final FragmentManager fm = getSherlockActivity().getSupportFragmentManager();
    int entryCount = fm.getBackStackEntryCount(); 
    while (entryCount-- > 0) {
        fm.popBackStack();
    }

How to detect orientation change?

Swift 4:

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(deviceRotated), name: UIDevice.orientationDidChangeNotification, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
}

@objc func deviceRotated(){
    if UIDevice.current.orientation.isLandscape {
        //Code here
    } else {
        //Code here
    }
}

A lot of answers dont help when needing to detect across various view controllers. This one does the trick.

QtCreator: No valid kits found

In my case, it goes well after I installed CMake in my system:)

sudo pacman -S cmake

for manjaro operating system.

Build an iOS app without owning a mac?

Also if you want to save some money you don't must buy a Mac. There is other ways how to do it:

1.) You can use practically any OS to run latest MacOS in virtual machine (look at YouTube). I am using this method really long time without any problems on windows with VMWare.

2.) Hackintosh. Install MacOS to your PC. You must have compatible components, but if you have, this is the best way, because you eliminate the lags in VM... I am using this in this time. Perfect. On my laptop, but please don't tell this to Apple, because practically this is illegal

3.) If you are making simple apps with minimum UI, you can use Theos. Also with Theos you can create cydia tweaks. Only one problem: codesign. If you want to publish app on App Store you still must have MacOS, but if you want to make app in home you can use CydiaImpactor to sign the apps with Apple ID.

I used all of this ways and all is working. By my VM is best solution if you don't want to spend lot of time by installing Hackintosh.

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

For me the error was:

Error: unexpected input in "?"

and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.

EDIT: OP requested an example. Here it goes.

?  ~ cat a.R
cat('hello world\n')
?  ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f  ...cat('hello wo
00000010: 726c 645c 6e27 290a                      rld\n').
?  ~ R -f a.R        

R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> cat('hello world\n')
Error: unexpected input in "?"
Execution halted

Is it possible to break a long line to multiple lines in Python?

There is more than one way to do it.

1). A long statement:

>>> def print_something():
         print 'This is a really long line,', \
               'but we can make it across multiple lines.'

2). Using parenthesis:

>>> def print_something():
        print ('Wow, this also works?',
               'I never knew!')

3). Using \ again:

>>> x = 10
>>> if x == 10 or x > 0 or \
       x < 100:
       print 'True'

Quoting PEP8:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

Use formula in custom calculated field in Pivot Table

Thank you for planting a seed, Cel! I've been struggling with this for hours, finally got it. I was counting a text field, oops, calculation failed.

Created 2 helper columns in my raw data, each resulting in 1 if condition met, 0 if not. Then pulled each into a pivot column, mine are called, "Inbd" (for Inbound), "Back", where "Back" is a return to sending facility, so in reality the total is one trip, not 2 trips, i.e., back is a subset of inbound and not every inbd has a back (obviously). Trying to calculate in the pivot table so I can sort on the field the rate of back to inbound for each sending facility.

For my calculated field I used: =IFERROR(IF(Pvt_Back>0,Pvt_Back/Pvt_Inbd,0),0) So: if we sent back to sending some number of times greater than 0, divide Back/Inbd to give me a rate; if equal to 0, then 0; if Inbd = 0, then 0 to avoid Div/0 error.

Thanks again!! :)

What is the difference between null=True and blank=True in Django?

This is how the ORM maps blank & null fields for Django 1.8

class Test(models.Model):
    charNull        = models.CharField(max_length=10, null=True)
    charBlank       = models.CharField(max_length=10, blank=True)
    charNullBlank   = models.CharField(max_length=10, null=True, blank=True)

    intNull         = models.IntegerField(null=True)
    intBlank        = models.IntegerField(blank=True)
    intNullBlank    = models.IntegerField(null=True, blank=True)

    dateNull        = models.DateTimeField(null=True)
    dateBlank       = models.DateTimeField(blank=True)
    dateNullBlank   = models.DateTimeField(null=True, blank=True)        

The database fields created for PostgreSQL 9.4 are :

CREATE TABLE Test (
  id              serial                    NOT NULL,

  "charNull"      character varying(10),
  "charBlank"     character varying(10)     NOT NULL,
  "charNullBlank" character varying(10),

  "intNull"       integer,
  "intBlank"      integer                   NOT NULL,
  "intNullBlank"  integer,

  "dateNull"      timestamp with time zone,
  "dateBlank"     timestamp with time zone  NOT NULL,
  "dateNullBlank" timestamp with time zone,
  CONSTRAINT Test_pkey PRIMARY KEY (id)
)

The database fields created for MySQL 5.6 are :

CREATE TABLE Test (
     `id`            INT(11)     NOT  NULL    AUTO_INCREMENT,

     `charNull`      VARCHAR(10) NULL DEFAULT NULL,
     `charBlank`     VARCHAR(10) NOT  NULL,
     `charNullBlank` VARCHAR(10) NULL DEFAULT NULL,

     `intNull`       INT(11)     NULL DEFAULT NULL,
     `intBlank`      INT(11)     NOT  NULL,
     `intNullBlank`  INT(11)     NULL DEFAULT NULL,

     `dateNull`      DATETIME    NULL DEFAULT NULL,
     `dateBlank`     DATETIME    NOT  NULL,
     `dateNullBlank` DATETIME    NULL DEFAULT NULL
)

How is the default max Java heap size determined?

This is changed in Java 6 update 18.

Assuming that we have more than 1 GB of physical memory (quite common these days), it's always 1/4th of your physical memory for the server vm.

how to evenly distribute elements in a div next to each other?

_x000D_
_x000D_
.container {_x000D_
  padding: 10px;_x000D_
}_x000D_
.parent {_x000D_
  width: 100%;_x000D_
  background: #7b7b7b;_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  height: 4px;_x000D_
}_x000D_
.child {_x000D_
  color: #fff;_x000D_
  background: green;_x000D_
  padding: 10px 10px;_x000D_
  border-radius: 50%;_x000D_
  position: relative;_x000D_
  top: -8px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="parent">_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Loading cross-domain endpoint with AJAX

I'm posting this in case someone faces the same problem I am facing right now. I've got a Zebra thermal printer, equipped with the ZebraNet print server, which offers a HTML-based user interface for editing multiple settings, seeing the printer's current status, etc. I need to get the status of the printer, which is displayed in one of those html pages, offered by the ZebraNet server and, for example, alert() a message to the user in the browser. This means that I have to get that html page in Javascript first. Although the printer is within the LAN of the user's PC, that Same Origin Policy is still staying firmly in my way. I tried JSONP, but the server returns html and I haven't found a way to modify its functionality (if I could, I would have already set the magic header Access-control-allow-origin: *). So I decided to write a small console app in C#. It has to be run as Admin to work properly, otherwise it trolls :D an exception. Here is some code:

// Create a listener.
        HttpListener listener = new HttpListener();
        // Add the prefixes.
        //foreach (string s in prefixes)
        //{
        //    listener.Prefixes.Add(s);
        //}
        listener.Prefixes.Add("http://*:1234/"); // accept connections from everywhere,
        //because the printer is accessible only within the LAN (no portforwarding)
        listener.Start();
        Console.WriteLine("Listening...");
        // Note: The GetContext method blocks while waiting for a request. 
        HttpListenerContext context;
        string urlForRequest = "";

        HttpWebRequest requestForPage = null;
        HttpWebResponse responseForPage = null;
        string responseForPageAsString = "";

        while (true)
        {
            context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            urlForRequest = request.RawUrl.Substring(1, request.RawUrl.Length - 1); // remove the slash, which separates the portNumber from the arg sent
            Console.WriteLine(urlForRequest);

            //Request for the html page:
            requestForPage = (HttpWebRequest)WebRequest.Create(urlForRequest);
            responseForPage = (HttpWebResponse)requestForPage.GetResponse();
            responseForPageAsString = new StreamReader(responseForPage.GetResponseStream()).ReadToEnd();

            // Obtain a response object.
            HttpListenerResponse response = context.Response;
            // Send back the response.
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseForPageAsString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            response.AddHeader("Access-Control-Allow-Origin", "*"); // the magic header in action ;-D
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            // You must close the output stream.
            output.Close();
            //listener.Stop();

All the user needs to do is run that console app as Admin. I know it is way too ... frustrating and complicated, but it is sort of a workaround to the Domain Policy problem in case you cannot modify the server in any way.

edit: from js I make a simple ajax call:

$.ajax({
                type: 'POST',
                url: 'http://LAN_IP:1234/http://google.com',
                success: function (data) {
                    console.log("Success: " + data);
                },
                error: function (e) {
                    alert("Error: " + e);
                    console.log("Error: " + e);
                }
            });

The html of the requested page is returned and stored in the data variable.

Core Data: Quickest way to delete all instances of an entity

Extending Dave Delong's answer.

Swift Version that takes care of iOS 9 and previous versions as well. I have also covered Error handling in this:

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let fetchRequest = NSFetchRequest(entityName: "Car")
    if #available(iOS 9.0, *) {
        let delete = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try appDelegate.persistentStoreCoordinator.executeRequest(delete, withContext: appDelegate.managedObjectContext)
        } catch let error as NSError {
            print("Error occured while deleting: \(error)")
        }
    } else {
        // Fallback on earlier versions
        let carRequest = NSFetchRequest()
        carRequest.entity = NSEntityDescription.entityForName("Cars", inManagedObjectContext: appDelegate.managedObjectContext)
        carRequest.includesPropertyValues = false

        do {
            let cars: NSArray = try appDelegate.managedObjectContext.executeFetchRequest(carRequest)

            for car in cars {
                appDelegate.managedObjectContext.delete(car)
            }

            try appDelegate.managedObjectContext.save()

        } catch let error as NSError {
            print("Error occured while fetching or saving: \(error)")
        }
    }

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

git config --global http.postBuffer 524288000

Work in my case - AWS code commit

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

Chain-calling parent initialisers in python

Python 3 includes an improved super() which allows use like this:

super().__init__(args)

Sending E-mail using C#

Take a look at the FluentEmail library. I've blogged about it here

You have a nice and fluent api for your needs:

Email.FromDefault()
 .To("[email protected]")
 .Subject("New order has arrived!")
 .Body("The order details are…")  
 .Send();

How to get the current date and time of your timezone in Java?

As Jon Skeet already said, java.util.Date does not have a time zone. A Date object represents a number of milliseconds since January 1, 1970, 12:00 AM, UTC. It does not contain time zone information.

When you format a Date object into a string, for example by using SimpleDateFormat, then you can set the time zone on the DateFormat object to let it know in which time zone you want to display the date and time:

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

System.out.println("Date and time in Madrid: " + df.format(date));

If you want the local time zone of the computer that your program is running on, use:

df.setTimeZone(TimeZone.getDefault());

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

Remove duplicated rows

The function distinct() in the dplyr package performs arbitrary duplicate removal, either from specific columns/variables (as in this question) or considering all columns/variables. dplyr is part of the tidyverse.

Data and package

library(dplyr)
dat <- data.frame(a = rep(c(1,2),4), b = rep(LETTERS[1:4],2))

Remove rows duplicated in a specific column (e.g., columna)

Note that .keep_all = TRUE retains all columns, otherwise only column a would be retained.

distinct(dat, a, .keep_all = TRUE)

  a b
1 1 A
2 2 B

Remove rows that are complete duplicates of other rows:

distinct(dat)

  a b
1 1 A
2 2 B
3 1 C
4 2 D

Use jQuery to navigate away from page

window.location = myUrl;

Anyway, this is not jQuery: it's plain javascript

How do I get the backtrace for all the threads in GDB?

Is there a command that does?

thread apply all where

Get all mysql selected rows into an array

  1. Loop through the results and place each one in an array

  2. use mysqli_fetch_all() to get them all at one time

Auto generate function documentation in Visual Studio

I'm working on an open-source project called Todoc which analyzes words to produce proper documentation output automatically when saving a file. It respects existing comments and is really fast and fluid.

http://todoc.codeplex.com/

How to remove an app with active device admin enabled on Android?

Redmi/xiaomi user

Go to "Settings" -> "Password & security" -> "Privacy" -> "Special app access" -> "Device admin apps" and select the account which you want to uninstall.

Or Simply

go to setting -> Then search for Device admin apps -> click and select the account which you want to uninstall.

MongoDB or CouchDB - fit for production?

We use couchdb in production and have since just before the project went under the Apache umbrella.

We use it to store everything that we might otherwise use a dbms, plus all sorts of unstructured data. Personally, I really like how you can just throw all sorts of data into it and use the views to cull what you don't need depending on the situation.

The hardest part was moving away from the dbms mindset. We wrote our own migration utils when the storage format changed just to be safe, so that wasn't really a problem.

We haven't had any negative experiences yet, but then again we haven't had the setup under any kind of huge load. I think things would work pretty well since we have two slave type servers that replicate from a single master server that gets all of the writes. I'm pretty sure that we don't have to do it that way for replication to work correctly, but it's how we set it up in the beginning and it stuck.

Check if an image is loaded (no errors) with jQuery

This snippet of code helped me to fix browser caching problems:

$("#my_image").on('load', function() {

    console.log("image loaded correctly"); 
}).each(function() {

     if($(this).prop('complete')) $(this).load();
});

When the browser cache is disabled, only this code doesn't work:

$("#my_image").on('load', function() {
     console.log("image loaded correctly"); 
})

to make it work you have to add:

.each(function() {
     if($(this).prop('complete')) $(this).load();
});

SELECTING with multiple WHERE conditions on same column

Consider using INTERSECT like this:

SELECT contactid WHERE flag = 'Volunteer' 
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'

I think it it the most logistic solution.

Python Requests throwing SSLError

I have found an specific approach for solving a similar issue. The idea is pointing the cacert file stored at the system and used by another ssl based applications.

In Debian (I'm not sure if same in other distributions) the certificate files (.pem) are stored at /etc/ssl/certs/ So, this is the code that work for me:

import requests
verify='/etc/ssl/certs/cacert.org.pem'
response = requests.get('https://lists.cacert.org', verify=verify)

For guessing what pem file choose, I have browse to the url and check which Certificate Authority (CA) has generated the certificate.

EDIT: if you cannot edit the code (because you are running a third app) you can try to add the pem certificate directly into /usr/local/lib/python2.7/dist-packages/requests/cacert.pem (e.g. copying it to the end of the file).

how to change php version in htaccess in server

An addition to the current marked answer:

Place the addhandler inside the following scope, like so:

<IfModule mod_rewrite.c>

   AddHandler application/x-httpd-php71 .php
   RewriteEngine On

   ....

</IfModule>

How to run shell script file using nodejs?

You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.

hi.sh

echo "Hi There!"

node_program.js

const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
        (error, stdout, stderr) => {
            console.log(stdout);
            console.log(stderr);
            if (error !== null) {
                console.log(`exec error: ${error}`);
            }
        });

Here, when I run the nodejs file, it will execute the shell file and the output would be:

Run

node node_program.js

output

Hi There!

You can execute any script just by mentioning the shell command or shell script in exec callback.

Hope this helps! Happy coding :)

Regex to get the words after matching string

You're almost there. Use the following regex (with multi-line option enabled)

\bObject Name:\s+(.*)$

The complete match would be

Object Name:   D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log

while the captured group one would contain

D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log

If you want to capture the file path directly use

(?m)(?<=\bObject Name:).*$

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

Those who updated their device to Android 4.2 Jelly Bean or higher or having a 4.2 JB or higher android powered device, will not found the Developers Options in Settings menu. The Developers Options hide by default on 4.2 jelly bean and later android versions. Follow the below steps to Unhide Developers Options.

  1. Go to Settings>>About (On most Android Smartphone and tablet) OR

Go to Settings>> More/General tab>> About (On Samsung Galaxy S3, Galaxy S4, Galaxy Note 8.0, Galaxy Tab 3 and other galaxy Smartphone and tablet having Android 4.2/4.3 Jelly Bean) OR

Go to Settings>> General>> About (On Samsung Galaxy Note 2, Galaxy Note 3 and some other Galaxy devices having Android 4.3 Jelly Bean or 4.4 KitKat) OR

Go to Settings> About> Software Information> More (On HTC One or other HTC devices having Android 4.2 Jelly Bean or higher) 2. Now Scroll onto Build Number and tap it 7 times repeatedly. A message will appear saying that u are now a developer.

  1. Just return to the previous menu to see developer option.

Credit to www.androidofficer.com

how to send multiple data with $.ajax() jquery

I would recommend using a hash instead of a param string:

data = {id: id, name: name}

Enable CORS in Web API 2

 var cors = new EnableCorsAttribute("*","*","*");
 config.EnableCors(cors);

 var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);

Simple Deadlock Examples

Maybe a simple bank situation.

class Account {
  double balance;

  void withdraw(double amount){
     balance -= amount;
  } 

  void deposit(double amount){
     balance += amount;
  } 

   void transfer(Account from, Account to, double amount){
        sync(from);
        sync(to);

        from.withdraw(amount);
        to.deposit(amount);

        release(to);
        release(from);
    }

}

Obviously, should there be two threads which attempt to run transfer(a, b) and transfer(b, a) at the same time, then a deadlock is going to occur because they try to acquire the resources in reverse order.

This code is also great for looking at solutions to the deadlock as well. Hope this helps!

How to get index in Handlebars each helper?

Arrays:

{{#each array}}
    {{@index}}: {{this}}
{{/each}}

If you have arrays of objects... you can iterate through the children:

{{#each array}}
    //each this = { key: value, key: value, ...}
    {{#each this}}
        //each key=@key and value=this of child object 
        {{@key}}: {{this}}
        //Or get index number of parent array looping
        {{@../index}}
    {{/each}}
{{/each}}

Objects:

{{#each object}}
    {{@key}}: {{this}}
{{/each}} 

If you have nested objects you can access the key of parent object with {{@../key}}

How to implement infinity in Java?

The Double and Float types have the POSITIVE_INFINITY constant.

File.Move Does Not Work - File Already Exists

If file really exists and you want to replace it use below code:

string file = "c:\test\SomeFile.txt"
string moveTo = "c:\test\test\SomeFile.txt"

if (File.Exists(moveTo))
{
    File.Delete(moveTo);
}

File.Move(file, moveTo);

How to copy only a single worksheet to another workbook using vba

To copy a sheet to a workbook called TARGET:

Sheets("xyz").Copy After:=Workbooks("TARGET.xlsx").Sheets("abc")

This will put the copied sheet xyz in the TARGET workbook after the sheet abc Obviously if you want to put the sheet in the TARGET workbook before a sheet, replace Before for After in the code.

To create a workbook called TARGET you would first need to add a new workbook and then save it to define the filename:

Application.Workbooks.Add (xlWBATWorksheet)
ActiveWorkbook.SaveAs ("TARGET")

However this may not be ideal for you as it will save the workbook in a default location e.g. My Documents.

Hopefully this will give you something to go on though.

Generate random string/characters in JavaScript

Try this, what i use every time :

_x000D_
_x000D_
function myFunction() {_x000D_
        var hash = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789";_x000D_
        var random8 = '';_x000D_
        for(var i = 0; i < 5; i++){_x000D_
            random8 += hash[parseInt(Math.random()*hash.length)];_x000D_
        }_x000D_
        console.log(random8);_x000D_
    document.getElementById("demo").innerHTML = "Your 5 character string ===> "+random8;_x000D_
}        _x000D_
        
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>Click the button to genarate 5 character random string .</p>_x000D_
_x000D_
<button onclick="myFunction()">Click me</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What does "select count(1) from table_name" on any database tables mean?

Depending on who you ask, some people report that executing select count(1) from random_table; runs faster than select count(*) from random_table. Others claim they are exactly the same.

This link claims that the speed difference between the 2 is due to a FULL TABLE SCAN vs FAST FULL SCAN.

how to get program files x86 env variable?

On a Windows 64 bit machine, echo %programfiles(x86)% does print C:\Program Files (x86)

How do I make an HTTP request in Swift?

Swift 3.0

Through a small abstraction https://github.com/daltoniam/swiftHTTP

Example

    do {
        let opt = try HTTP.GET("https://google.com")
        opt.start { response in
            if let err = response.error {
                print("error: \(err.localizedDescription)")
                return //also notify app of failure as needed
            }
            print("opt finished: \(response.description)")
            //print("data is: \(response.data)") access the response of the data with response.data
        }
    } catch let error {
        print("got an error creating the request: \(error)")
    }

changing color of h2

Try CSS:

<h2 style="color:#069">Process Report</h2>

If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:

<style type="text/css">
h2 {
    color:#069;
}
</style>

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

In my case, I hadn't agreed to the newest Developer Agreement. Just run Application Loader once, click on [Accept] to agree, then quit the Application Loader and the Upload to App Store should work fine.

Hexadecimal value 0x00 is a invalid character

To add to Sonz's answer above, following worked for us.

//Instead of 
XmlString.Replace("&#x0;", "[0x00]");
// use this
XmlString.Replace("\x00", "[0x00]");

Why use @Scripts.Render("~/bundles/jquery")

You can also use:

@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")

To specify the format of your output in a scenario where you need to use Charset, Type, etc.

m2eclipse error

I had the same problem but with an other cause. The solution was to deactivate Avira Browser Protection (in german Browser-Schutz). I took the solusion from m2e cannot transfer metadata from nexus, but maven command line can. It can be activated again ones maven has the needed plugin.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

You are single quoting your SQL statement which is making the variables text instead of variables.

$sql = "SELECT * 
    FROM $usertable 
    WHERE PartNumber = $partid";

How can I print each command before executing?

set -x is fine.

Another way to print each executed command is to use trap with DEBUG. Put this line at the beginning of your script :

trap 'echo "# $BASH_COMMAND"' DEBUG

You can find a lot of other trap usages here.

Detect click outside element

There are two packages available in the community for this task (both are maintained):

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

How do I set default value of select box in angularjs

It doesn't set the default value because your model isn't bound to the id or name properties, it's bound to each version object. Try setting the versionID to one of the objects and it should work, ie $scope.item.versionID = $scope.versions[2];

If you want to set by the id property then you need to add the select as syntax:

ng-options="version.id as version.name for version in versions"

http://jsfiddle.net/LrhAQ/1/

Import module from subfolder

Had problems even when init.py existed in subfolder and all that was missing was adding 'as' after import

from folder.file import Class as Class
import folder.file as functions

How to create a new branch from a tag?

My branch list (only master now)

branch list

My tag list (have three tags)

tag list

Switch to new branch feature/codec from opus_codec tag

git checkout -b feature/codec opus_codec

switch to branch

Excel to JSON javascript code?

The answers are working fine with xls format but, in my case, it didn't work for xlsx format. Thus I added some code here. it works both xls and xlsx format.

I took the sample from the official sample link.

Hope it may help !

function fileReader(oEvent) {
        var oFile = oEvent.target.files[0];
        var sFilename = oFile.name;

        var reader = new FileReader();
        var result = {};

        reader.onload = function (e) {
            var data = e.target.result;
            data = new Uint8Array(data);
            var workbook = XLSX.read(data, {type: 'array'});
            console.log(workbook);
            var result = {};
            workbook.SheetNames.forEach(function (sheetName) {
                var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
                if (roa.length) result[sheetName] = roa;
            });
            // see the result, caution: it works after reader event is done.
            console.log(result);
        };
        reader.readAsArrayBuffer(oFile);
}

// Add your id of "File Input" 
$('#fileUpload').change(function(ev) {
        // Do something 
        fileReader(ev);
}

About .bash_profile, .bashrc, and where should alias be written in?

.bash_profile is loaded for a "login shell". I am not sure what that would be on OS X, but on Linux that is either X11 or a virtual terminal.

.bashrc is loaded every time you run Bash. That is where you should put stuff you want loaded whenever you open a new Terminal.app window.

I personally put everything in .bashrc so that I don't have to restart the application for changes to take effect.

How to define a relative path in java

I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.

private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className  + ".html";
ExtentReports report;
ExtentTest test;

@BeforeMethod
    //  initialise report variables
    report = new ExtentReports(outputFolder + outputFile);
    test = report.startTest(className);
    // more setup code

@Test
    // test method code with log statements

@AfterMethod
    // takeScreenShot returns the relative path and filename for the image
    String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
    String imagePath = test.addScreenCapture(imgFilename);
    test.log(LogStatus.FAIL, "Added image to report", imagePath);

This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".

This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.

Chris

String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);

How to import large sql file in phpmyadmin

Change your server settings to allow file uploads larger than 12 mb and you should be fine. Usually the server settings are set to 5 to 8 mb for file uploads.

Counting the number of True Booleans in a Python List

After reading all the answers and comments on this question, I thought to do a small experiment.

I generated 50,000 random booleans and called sum and count on them.

Here are my results:

>>> a = [bool(random.getrandbits(1)) for x in range(50000)]
>>> len(a)
50000
>>> a.count(False)
24884
>>> a.count(True)
25116
>>> def count_it(a):
...   curr = time.time()
...   counting = a.count(True)
...   print("Count it = " + str(time.time() - curr))
...   return counting
... 
>>> def sum_it(a):
...   curr = time.time()
...   counting = sum(a)
...   print("Sum it = " + str(time.time() - curr))
...   return counting
... 
>>> count_it(a)
Count it = 0.00121307373046875
25015
>>> sum_it(a)
Sum it = 0.004102230072021484
25015

Just to be sure, I repeated it several more times:

>>> count_it(a)
Count it = 0.0013530254364013672
25015
>>> count_it(a)
Count it = 0.0014507770538330078
25015
>>> count_it(a)
Count it = 0.0013344287872314453
25015
>>> sum_it(a)
Sum it = 0.003480195999145508
25015
>>> sum_it(a)
Sum it = 0.0035257339477539062
25015
>>> sum_it(a)
Sum it = 0.003350496292114258
25015
>>> sum_it(a)
Sum it = 0.003744363784790039
25015

And as you can see, count is 3 times faster than sum. So I would suggest to use count as I did in count_it.

Python version: 3.6.7
CPU cores: 4
RAM size: 16 GB
OS: Ubuntu 18.04.1 LTS

Inner join with count() on three tables

As Frank pointed out, you need to use DISTINCT. Also, since you are using composite primary keys (which is perfectly fine, BTW) you need to make sure that you use the whole key in your joins:

SELECT
    P.pe_name,
    COUNT(DISTINCT O.ord_id) AS num_orders,
    COUNT(I.item_id) AS num_items
FROM
    People P
INNER JOIN Orders O ON
    O.pe_id = P.pe_id
INNER JOIN Items I ON
    I.ord_id = O.ord_id AND
    I.pe_id = O.pe_id
GROUP BY
    P.pe_name

Without I.ord_id = O.ord_id it was joining each item row to every order row for a person.

single line comment in HTML

Let's keep it simple. Loved @digitaldreamer 's answer but it might leave the beginners confused. So, I am going to try and simplify it.

The only HTML comment is <!-- --> It can be used as a single line comment or double, it is really up to the developer.

So, an HTML comment starts with <!-- and ends with -->. It is really that simple. You should not use any other format, to avoid any compatibility issue even if the comment format is legit or not.

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

Create a <ul> and fill it based on a passed array

What are disadvantages of the following solution? Seems to be faster and shorter.

var options = {
    set0: ['Option 1','Option 2'],
    set1: ['First Option','Second Option','Third Option']
};

var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;

Convert DateTime to long and also the other way around

   long dateTime = DateTime.Now.Ticks;
   Console.WriteLine(dateTime);
   Console.WriteLine(new DateTime(dateTime));
   Console.ReadKey();

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,

  • Xpath engines are different in each browser, hence make them inconsistent
  • IE does not have a native xpath engine, therefore selenium injects its own xpath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes.
  • Xpath tend to become complex and hence make hard to read in my opinion

However there are some situations where, you need to use xpath, for example, searching for a parent element or searching element by its text (I wouldn't recommend the later).

You can read blog from Simon here . He also recommends CSS over Xpath.

If you are testing content then do not use selectors that are dependent on the content of the elements. That will be a maintenance nightmare for every locale. Try talking with developers and use techniques that they used to externalize the text in the application, like dictionaries or resource bundles etc. Here is my blog that explains it in detail.

edit 1

Thanks to @parishodak, here is the link which provides the numbers proving that CSS performance is better

Ellipsis for overflow text in dropdown boxes

CSS file

.selectDD {
 overflow: hidden;
 white-space: nowrap;
 text-overflow: ellipsis;     
}

JS file

$(document).ready(function () {
    $("#selectDropdownID").next().children().eq(0).addClass("selectDD");
});

iPhone and WireShark

You can proceed as follow:

  1. Install Charles Web Proxy.
  2. Disable SSL proxying (uncheck the flag in Proxy->Proxy Settings...->SSL
  3. Connect your iDevice to the Charles proxy, as explained here
  4. Sniff the packets via Wireshark or Charles

Socket send and receive byte array

First, do not use DataOutputStream unless it’s really necessary. Second:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

CSS vertical alignment of inline/inline-block elements

Give vertical-align:top; in a & span. Like this:

a, span{
 vertical-align:top;
}

Check this http://jsfiddle.net/TFPx8/10/

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

_x000D_
_x000D_
function textbox()_x000D_
{_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
_x000D_
_x000D_

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

How to change background Opacity when bootstrap modal is open

You can download a custom compiled bootstrap 3, just customize the @modal-backdrop-opacity from:

https://getbootstrap.com/docs/3.4/customize/

Customizing bootstrap 4 requires compiling from source, overriding $modal-backdrop-bg as described in:

https://getbootstrap.com/docs/4.4/getting-started/theming/

In the answers to Bootstrap 4 custom build generator / download there is a NodeJS workflow for compiling Bootstrap 4 from source, alone with some non-official Bootstrap 4 customizers.

How to build a 'release' APK in Android Studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

I had a similar issue/error.. fixed it by moving apply plugin: 'com.google.gms.google-services'
to the end of app level gradle file.

And updated the version of gms:play-services and gms:play-services auth

val() vs. text() for textarea

.val() always works with textarea elements.

.text() works sometimes and fails other times! It's not reliable (tested in Chrome 33)

What's best is that .val() works seamlessly with other form elements too (like input) whereas .text() fails.

MySQL selecting yesterday's date

I adapted one of the above answers from cdhowie as I could not get it to work. This seems to work for me. I suspect it's also possible to do this with the UNIX_TIMESTAMP function been used.

SELECT * FROM your_table

WHERE UNIX_TIMESTAMP(DateVisited) >= UNIX_TIMESTAMP(CAST(NOW() - INTERVAL 1 DAY AS DATE))
  AND UNIX_TIMESTAMP(DateVisited) <= UNIX_TIMESTAMP(CAST(NOW() AS DATE));

How to shrink/purge ibdata1 file in MySQL

In a new version of mysql-server recipes above will crush "mysql" database. In old version it works. In new some tables switches to table type INNODB, and by doing so you will damage them. The easiest way is to:

  • dump all you databases
  • uninstall mysql-server,
  • add in remained my.cnf:
    [mysqld]
    innodb_file_per_table=1
  • erase all in /var/lib/mysql
  • install mysql-server
  • restore users and databases

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

jQuery append text inside of an existing paragraph tag

Try this

$('#add_here').text('new-dynamic-text');

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

Try this:

XmlDocument bodyDoc = new XmlDocument();
bodyDoc.XMLResolver = null;
bodyDoc.Load(body);

Use getElementById on HTMLElement instead of HTMLDocument

Sub Scrape()
    Dim Browser As InternetExplorer
    Dim Document As htmlDocument
    Dim Elements As IHTMLElementCollection
    Dim Element As IHTMLElement

    Set Browser = New InternetExplorer
    Browser.Visible = True
    Browser.navigate "http://www.stackoverflow.com"

    Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
        DoEvents
    Loop

    Set Document = Browser.Document

    Set Elements = Document.getElementById("hmenus").getElementsByTagName("li")
    For Each Element In Elements
        Debug.Print Element.innerText
        'Questions
        'Tags
        'Users
        'Badges
        'Unanswered
        'Ask Question
    Next Element

    Set Document = Nothing
    Set Browser = Nothing
End Sub

PDO's query vs execute

No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:

$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).

Best way to stress test a website

We tried a few applications, both trials of commercial products and freely available ones. Ultimately, it was the trial edition of the Team Test Load Agent software that we tried. It definitely works great and is fairly simple to use. In the long run, it bolstered our argument to move to Team Foundation Server and equip all parts of the department with the appropriate tooling.

The obvious downside, however, is the price.

How to manually install an artifact in Maven 2?

According to maven's Guide to installing 3rd party JARs, the command is:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

You need indeed the packaging option. This answers the original question.

Now, in your context, you are fighting with a jar provided by Sun. You should read the Coping with Sun JARs page too. There, you'll learn how to help maven to provide you better information about Sun jars location and how to add Java.net Maven 2 repository which contains jta-1.0.1B.jar. Add this in your settings.xml (not portable) or pom.xml (portable):

  <repositories>
    <repository>
      <id>maven2-repository.dev.java.net</id>
      <name>Java.net Repository for Maven</name>
      <url>http://download.java.net/maven/2/</url>
      <layout>default</layout>
    </repository>
  </repositories>

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['auth_type'] = 'cookie';

should work.

From the manual:

auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.

How to remove the character at a given index from a string in C?

I know that the question is very old, but I will leave my implementation here:

char    *ft_strdelchr(const char *str,char c)
{
        int   i;
        int   j;
        char  *s;
        char  *newstr;

        i = 0;
        j = 0;
        // cast to char* to be able to modify, bc the param is const
        // you guys can remove this and change the param too
        s = (char*)str;
        // malloc the new string with the necessary length. 
        // obs: strcountchr returns int number of c(haracters) inside s(tring)
        if (!(newstr = malloc(ft_strlen(s) - ft_strcountchr(s, c) + 1 * sizeof(char))))
                return (NULL);
        while (s[i])
        {
                if (s[i] != c)
                {
                        newstr[j] = s[i];
                        j++;
                }
                i++;
        }
        return (newstr);
}

just throw to a new string the characters that are not equal to the character you want to remove.

Error: The 'brew link' step did not complete successfully

I'm a bit late, what worked for me was this:

* npm uninstall npm -g

* brew uninstall node

* brew install node

* sudo rm -rf /usr/local/lib/dtrace/node.d

* brew link node (caused error with permissions)

* sudo chmod 777 /usr/local/lib/dtrace/node.d

* brew link node

Everything was successful after this sequence

Specify sudo password for Ansible

Using ansible 2.4.1.0 and the following shall work:

[all]
17.26.131.10
17.26.131.11
17.26.131.12
17.26.131.13
17.26.131.14

[all:vars]
ansible_connection=ssh
ansible_user=per
ansible_ssh_pass=per
ansible_sudo_pass=per

And just run the playbook with this inventory as:

ansible-playbook -i inventory copyTest.yml

Typescript empty object for a typed variable

user: USER

this.user = ({} as USER)

Error: getaddrinfo ENOTFOUND in nodejs for get call

var http = require('http');

  var options = {     
      host: 'localhost',
      port: 80,
      path: '/broadcast'
    };

  var requestLoop = setInterval(function(){

      http.get (options, function (resp) {
        resp.on('data', function (d) {
          console.log ('data!', d.toString());
        });
        resp.on('end', function (d) {
           console.log ('Finished !');
        });
      }).on('error', function (e) {
          console.log ('error:', e);
      });
  }, 10000);

var dns = require('dns'), cache = {};
dns._lookup = dns.lookup;
dns.lookup = function(domain, family, done) {
    if (!done) {
        done = family;
        family = null;
    }

    var key = domain+family;
    if (key in cache) {
        var ip = cache[key],
            ipv = ip.indexOf('.') !== -1 ? 4 : 6;

        return process.nextTick(function() {
            done(null, ip, ipv);
        });
    }

    dns._lookup(domain, family, function(err, ip, ipv) {
        if (err) return done(err);
        cache[key] = ip;
        done(null, ip, ipv);
    });
};

// Works fine (100%)

How to disable a input in angular2

You could simply do this

<input [disabled]="true" id="name" type="text">

How do you test a public/private DSA keypair?

For DSA keys, use

 openssl dsa -pubin -in dsa.pub -modulus -noout

to print the public keys, then

 openssl dsa -in dsa.key -modulus -noout

to display the public keys corresponding to a private key, then compare them.

Creating a button in Android Toolbar

I have added text in ToolBar :

menu_skip.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_settings"
        android:title="@string/text_skip"
        app:showAsAction="never" />
</menu>

MainActivity.java

@Override
boolean onCreateOptionsMenu(Menu menu) {
    inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_otp_skip, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // action with ID action_refresh was selected
        case R.id.menu_item_skip:
            Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
                    .show();
            break;
        default:
            break;
    }
    return true;
}

How to check SQL Server version

TL;DR

SQLCMD -S (LOCAL) -E -V 16 -Q "IF(ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS INT),0)<11) RAISERROR('You need SQL 2012 or later!',16,1)"
IF ERRORLEVEL 1 GOTO :ExitFail

This uses SQLCMD (comes with SQL Server) to connect to the local server instance using Windows auth, throw an error if a version check fails and return the @@ERROR as the command line ERRORLEVEL if >= 16 (and the second line goes to the :ExitFail label if the aforementioned ERRORLEVEL is >= 1).

Watchas, Gotchas & More Info

For SQL 2000+ you can use the SERVERPROPERTY to determine a lot of this info.

While SQL 2008+ supports the ProductMajorVersion & ProductMinorVersion properties, ProductVersion has been around since 2000 (remembering that if a property is not supported the function returns NULL).

If you are interested in earlier versions you can use the PARSENAME function to split the ProductVersion (remembering the "parts" are numbered right to left i.e. PARSENAME('a.b.c', 1) returns c).

Also remember that PARSENAME('a.b.c', 4) returns NULL, because SQL 2005 and earlier only used 3 parts in the version number!

So for SQL 2008+ you can simply use:

SELECT
    SERVERPROPERTY('ProductVersion') AS ProductVersion,
    CAST(SERVERPROPERTY('ProductMajorVersion')  AS INT) AS ProductMajorVersion,
    CAST(SERVERPROPERTY ('ProductMinorVersion') AS INT) AS ProductMinorVersion;

For SQL 2000-2005 you can use:

SELECT
    SERVERPROPERTY('ProductVersion') AS ProductVersion,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) AS ProductVersion_Major,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 2 ELSE 3 END) AS INT) AS ProductVersion_Minor,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 1 ELSE 2 END) AS INT) AS ProductVersion_Revision,
    CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 0 ELSE 1 END) AS INT) AS ProductVersion_Build;

(the PARSENAME(...,0) is a hack to improve readability)

So a check for a SQL 2000+ version would be:

IF (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) < 10) -- SQL2008
OR (
    (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 3 ELSE 4 END) AS INT) = 10) -- SQL2008
AND (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME), CASE WHEN SERVERPROPERTY('ProductVersion') IS NULL THEN 2 ELSE 1 END) AS INT) < 5)  -- R2 (this may need to be 50)
   )
    RAISERROR('You need SQL 2008R2 or later!', 16, 1);

This is a lot simpler if you're only only interested in SQL 2008+ because SERVERPROPERTY('ProductMajorVersion') returns NULL for earlier versions, so you can use:

IF (ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS INT), 0) < 11) -- SQL2012
    RAISERROR('You need SQL 2012 or later!', 16, 1);

And you can use the ProductLevel and Edition (or EngineEdition) properties to determine RTM / SPn / CTPn and Dev / Std / Ent / etc respectively.

SELECT
    CAST(SERVERPROPERTY('ProductVersion') AS SYSNAME) AS ProductVersion,
    CAST(SERVERPROPERTY('ProductLevel') AS SYSNAME)   AS ProductLevel,
    CAST(SERVERPROPERTY('Edition') AS SYSNAME)        AS Edition,
    CAST(SERVERPROPERTY('EngineEdition') AS INT)      AS EngineEdition;

FYI the major SQL version numbers are:

  • 8 = SQL 2000
  • 9 = SQL 2005
  • 10 = SQL 2008 (and 10.5 = SQL 2008R2)
  • 11 = SQL 2012
  • 12 = SQL 2014
  • 13 = SQL 2016
  • 14 = SQL 2017

And this all works for SQL Azure too!

EDITED: You may also want to check your DB compatibility level since it could be set to a lower compatibility.

IF EXISTS (SELECT * FROM sys.databases WHERE database_id=DB_ID() AND [compatibility_level] < 110)
    RAISERROR('Database compatibility level must be SQL2008R2 or later (110)!', 16, 1)

Directory-tree listing in Python

I know this is an old question. This is a neat way I came across if you are on a liunx machine.

import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

Validating an XML against referenced XSD in C#

A simpler way, if you are using .NET 3.5, is to use XDocument and XmlSchemaSet validation.

XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);

XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
    msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);

See the MSDN documentation for more assistance.

Track a new remote branch created on GitHub

First of all you have to fetch the remote repository:

git fetch remoteName

Than you can create the new branch and set it up to track the remote branch you want:

git checkout -b newLocalBranch remoteName/remoteBranch

You can also use "git branch --track" instead of "git checkout -b" as max specified.

git branch --track newLocalBranch remoteName/remoteBranch

Simple (I think) Horizontal Line in WPF?

Use a Border of height 1 and don't set the Width (i.e. Width = Auto, HorizontalAlignment = Stretch, the default)

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

Define the width as 960px, or whatever you prefer, and you're good to go!

#main {
 margin: 0 auto !important;
 float: none !important;
 text-align: center;
 width: 960px;
}

(I couldn't figure this out until I fixed the width, nothing else worked.)

How to set the locale inside a Debian/Ubuntu Docker container?

Just add

ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8

into your Dockerfile. (You may need to make sure the locales package is installed.) Nothing else is needed for the basic operation. Meanwhile, outside of Ubuntu, locale-gen doesn’t accept any arguments, that’s why none of the ‘fixes’ using it work e.g. on Debian. Ubuntu have patched locale-gen to accept a list of locales to generate but the patch at the moment has not been accepted in Debian of anywhere else.

How to check if an element is off-screen

I know this is kind of late but this plugin should work. http://remysharp.com/2009/01/26/element-in-view-event-plugin/

$('p.inview').bind('inview', function (event, visible) {
if (visible) {
  $(this).text('You can see me!');
} else {
  $(this).text('Hidden again');
}

Java: getMinutes and getHours

Try using Joda Time instead of standard java.util.Date classes. Joda Time library has much better API for handling dates.

DateTime dt = new DateTime();  // current time
int month = dt.getMonth();     // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day

See this question for pros and cons of using Joda Time library.

Joda Time may also be included to some future version of Java as a standard component, see JSR-310.


If you must use traditional java.util.Date and java.util.Calendar classes, see their JavaDoc's for help (java.util.Calendar and java.util.Date).

You can use the traditional classes like this to fetch fields from given Date instance.

Date date = new Date();   // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR);        // gets hour in 12h format
calendar.get(Calendar.MONTH);       // gets month number, NOTE this is zero based!

How to disable Hyper-V in command line?

I tried all of stack overflow and all didn't works. But this works for me:

  1. Open System Configuration
  2. Click Service tab
  3. Uncheck all of Hyper-V related

How to paste text to end of every line? Sublime 2

You can use the Search & Replace feature with this regex ^([\w\d\_\.\s\-]*)$ to find text and the replaced text is "$1".

Implementing Singleton with an Enum (in Java)

This,

public enum MySingleton {
  INSTANCE;   
}

has an implicit empty constructor. Make it explicit instead,

public enum MySingleton {
    INSTANCE;
    private MySingleton() {
        System.out.println("Here");
    }
}

If you then added another class with a main() method like

public static void main(String[] args) {
    System.out.println(MySingleton.INSTANCE);
}

You would see

Here
INSTANCE

enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.

What is the best or most commonly used JMX Console / Client

JRockit Mission Control is becoming Java Mission Control and will be dedicated exclusively to Hotspot. If you are an Oracle customer, you can download the 5.x versions of Java Mission Control from MOS (My Oracle Support). Java Mission Control will eventually be released together with the Oracle JDK. The reason it is not yet generally available is that there are some serious limitations, especially when using the Flight Recorder. However, if you are only interested in using the JMX console, you should be golden!

Java system properties and environment variables

Matplotlib different size subplots

Probably the simplest way is using subplot2grid, described in Customizing Location of Subplot Using GridSpec.

ax = plt.subplot2grid((2, 2), (0, 0))

is equal to

import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])

so bmu's example becomes:

import numpy as np
import matplotlib.pyplot as plt

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

jQuery location href

There's no need of jQuery.

window.location.href = 'http://example.com';

How do I declare and initialize an array in Java?

With local variable type inference you only have to specify the type once:

var values = new int[] { 1, 2, 3 };

Or

int[] values = { 1, 2, 3 }

IOS 7 Navigation Bar text and arrow color

Swift 5/iOS 13

To change color of title in controller:

UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

Non-recursive depth first search algorithm

Just wanted to add my python implementation to the long list of solutions. This non-recursive algorithm has discovery and finished events.


worklist = [root_node]
visited = set()
while worklist:
    node = worklist[-1]
    if node in visited:
        # Node is finished
        worklist.pop()
    else:
        # Node is discovered
        visited.add(node)
        for child in node.children:
            worklist.append(child)

How are ssl certificates verified?

if you're more technically minded, this site is probably what you want: http://www.zytrax.com/tech/survival/ssl.html

warning: the rabbit hole goes deep :).

Relative frequencies / proportions with dplyr

Here is a general function implementing Henrik's solution on dplyr 0.7.1.

freq_table <- function(x, 
                       group_var, 
                       prop_var) {
  group_var <- enquo(group_var)
  prop_var  <- enquo(prop_var)
  x %>% 
    group_by(!!group_var, !!prop_var) %>% 
    summarise(n = n()) %>% 
    mutate(freq = n /sum(n)) %>% 
    ungroup
}

What is the worst programming language you ever worked with?

PROGRESS 4GL (apparently now known as "OpenEdge Advanced Business Language").

PROGRESS is both a language and a database system. The whole language is designed to make it easy to write crappy green-screen data-entry screens. (So start by imagining how well this translates to Windows.) Anything fancier than that, whether pretty screens, program logic, or batch processing... not so much.

I last used version 7, back in the late '90s, so it's vaguely possible that some of this is out-of-date, but I wouldn't bet on it.

  • It was originally designed for text-mode data-entry screens, so on Windows, all screen coordinates are in "character" units, which are some weird number of pixels wide and a different number of pixels high. But of course they default to a proportional font, so the number of "character units" doesn't correspond to the actual number of characters that will fit in a given space.
  • No classes or objects.
  • No language support for arrays or dynamic memory allocation. If you want something resembling an array, you create a temporary in-memory database table, define its schema, and then get a cursor on it. (I saw a bit of code from a later version, where they actually built and shipped a primitive object-oriented system on top of these in-memory tables. Scary.)
  • ISAM database access is built in. (But not SQL. Who needs it?) If you want to increment the Counter field in the current record in the State table, you just say State.Counter = State.Counter + 1. Which isn't so bad, except...
  • When you use a table directly in code, then behind the scenes, they create something resembling an invisible, magic local variable to hold the current cursor position in that table. They guess at which containing block this cursor will be scoped to. If you're not careful, your cursor will vanish when you exit a block, and reset itself later, with no warning. Or you'll start working with a table and find that you're not starting at the first record, because you're reusing the cursor from some other block (or even your own, because your scope was expanded when you didn't expect it).
  • Transactions operate on these wild-guess scopes. Are we having fun yet?
  • Everything can be abbreviated. For some of the offensively long keywords, this might not seem so bad at first. But if you have a variable named Index, you can refer to it as Index or as Ind or even as I. (Typos can have very interesting results.) And if you want to access a database field, not only can you abbreviate the field name, but you don't even have to qualify it with the table name; they'll guess the table too. For truly frightening results, combine this with:
  • Unless otherwise specified, they assume everything is a database access. If you access a variable you haven't declared yet (or, more likely, if you mistype the variable name), there's no compiler error: instead, it goes looking for a database field with that name... or a field that abbreviates to that name.

The guessing is the worst. Between the abbreviations and the field-by-default, you could get some nasty stuff if you weren't careful. (Forgot to declare I as a local variable before using it as a loop variable? No problem, we'll just randomly pick a table, grab its current record, and completely trash an arbitrarily-chosen field whose name starts with I!)

Then add in the fact that an accidental field-by-default access could change the scope it guessed for your tables, thus breaking some completely unrelated piece of code. Fun, yes?

They also have a reporting system built into the language, but I have apparently repressed all memories of it.

When I got another job working with Netscape LiveWire (an ill-fated attempt at server-side JavaScript) and classic ASP (VBScript), I was in heaven.

Disable submit button on form submit

Your code actually works on FF, it doesn't work on Chrome.

This works on FF and Chrome.

$(document).ready(function() {
        // Solution for disabling the submit temporarily for all the submit buttons.
        // Avoids double form submit.
        // Doing it directly on the submit click made the form not to submit in Chrome.
        // This works in FF and Chrome.
        $('form').on('submit', function(e){
          //console.log('submit2', e, $(this).find('[clicked=true]'));
          var submit = $(this).find('[clicked=true]')[0];
          if (!submit.hasAttribute('disabled'))
          {
            submit.setAttribute('disabled', true);
            setTimeout(function(){
              submit.removeAttribute('disabled');
            }, 1000);
          }
          submit.removeAttribute('clicked');
          e.preventDefault();
        });
        $('[type=submit]').on('click touchstart', function(){
          this.setAttribute('clicked', true);
        });
      });
    </script>

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

How to stop a JavaScript for loop?

I know this is a bit old, but instead of looping through the array with a for loop, it would be much easier to use the method <array>.indexOf(<element>[, fromIndex])

It loops through an array, finding and returning the first index of a value. If the value is not contained in the array, it returns -1.

<array> is the array to look through, <element> is the value you are looking for, and [fromIndex] is the index to start from (defaults to 0).

I hope this helps reduce the size of your code!

UIImageView aspect fit and center

You can achieve this by setting content mode of image view to UIViewContentModeScaleAspectFill.

Then use following method method to get the resized uiimage object.

- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
    CGFloat width = imageToResize.size.width;
    CGFloat height = imageToResize.size.height;
    float scaleFactor;
    if(width > height)
    {
        scaleFactor = imageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = imageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
    [imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

Edited Here (Swift Version)

func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
    let width = imageToResize.size.width
    let height = imageToResize.size.height

    var scaleFactor: CGFloat

    if(width > height)
    {
        scaleFactor = onImageView.frame.size.height / height;
    }
    else
    {
        scaleFactor = onImageView.frame.size.width / width;
    }

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
    imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return resizedImage;
}

How to display special characters in PHP

You can have a mix of PHP and HTML in your PHP files... just do something like this...

<?php
$string = htmlentities("Résumé");
?>

<html>
<head></head>
<body>
<p><?= $string ?></p>
</body>
</html>

That should output Résumé just how you want it to.

If you don't have short tags enabled, replace the <?= $string ?> with <?php echo $string; ?>

Correct use for angular-translate in controllers

To make a translation in the controller you could use $translate service:

$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
    vm.si = translations['COMMON.SI'];
    vm.no = translations['COMMON.NO'];
});

That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope event: $translateChangeSuccess and do the same translation there:

    $rootScope.$on('$translateChangeSuccess', function () {
        $translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
            vm.si = translations['COMMON.SI'];
            vm.no = translations['COMMON.NO'];
        });
    });

Of course, you could encapsulate the $translateservice in a method and call it in the controller and in the $translateChangeSucesslistener.

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

How should I set the default proxy to use default credentials?

This will force the DefaultWebProxy to use default credentials, similar effect as done through UseDefaultCredentials = true.

WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

Hence all newly created WebRequest instances will use default proxy which has been configured to use proxy's default credentials.

Put spacing between divs in a horizontal row?

This is because width when provided a % doesn't account for padding/margins. You will need to reduce the amount to possibly 24% or 24.5%. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.

Difference between Iterator and Listiterator?

Iterator is super class of ListIterator.

Here are the differences between them:

  1. With iterator you can move only forward, but with ListIterator you can move backword also while reading the elements.
  2. With ListIterator you can obtain the index at any point while traversing, which is not possible with iterators.
  3. With iterator you can check only for next element available or not, but in listiterator you can check previous and next elements.
  4. With listiterator you can add new element at any point of time, while traversing. Not possible with iterator.
  5. With listiterator you can modify an element while traversing, which is not possible with iterator.

Iterator look and feel:

 public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional-->use only once with next(), 
                         dont use it when u use for:each
    }

ListIterator look and feel:

public interface ListIterator<E> extends Iterator<E> {
    boolean hasNext();
    E next();
    boolean hasPrevious();
    E previous();
    int nextIndex();
    int previousIndex();
    void remove(); //optional
    void set(E e); //optional
    void add(E e); //optional
}

Using malloc for allocation of multi-dimensional arrays with different row lengths

I think a 2 step approach is best, because c 2-d arrays are just and array of arrays. The first step is to allocate a single array, then loop through it allocating arrays for each column as you go. This article gives good detail.

How can I make a Python script standalone executable to run without ANY dependency?

You can use py2exe as already answered and use Cython to convert your key .py files in .pyc, C compiled files, like .dll in Windows and .so on Linux.

It is much harder to revert than common .pyo and .pyc files (and also gain in performance!).

Complex numbers usage in python

In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:

>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)

The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)

The type of a complex number is complex, and you can use the type as a constructor if you prefer:

>>> complex(2,3)
(2+3j)

A complex number has some built-in accessors:

>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)

Several built-in functions support complex numbers:

>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)

The standard module cmath has more functions that handle complex numbers:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

Connect multiple devices to one device via Bluetooth

That is partly possible (for max 2 devices), because device can be connected only to one other device same time. Better solution in your case will be create an TCP server which sends informations to other devices - but that, of course, requires internet connection. Read also about Samsung Chord API - it provides functions which you need, but then every devices have to be connected to one and the same Wi-Fi network

Python loop for inside lambda

To add on to chepner's answer for Python 3.0 you can alternatively do:

x = lambda x: list(map(print, x))

Of course this is only if you have the means of using Python > 3 in the future... Looks a bit cleaner in my opinion, but it also has a weird return value, but you're probably discarding it anyway.

I'll just leave this here for reference.

How does the keyword "use" work in PHP and can I import classes with it?

The use keyword is for aliasing in PHP and it does not import the classes. This really helps
1) When you have classes with same name in different namespaces
2) Avoid using really long class name over and over again.

Get a list of all threads currently running in Java

Get a handle to the root ThreadGroup, like this:

ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parentGroup;
while ((parentGroup = rootGroup.getParent()) != null) {
    rootGroup = parentGroup;
}

Now, call the enumerate() function on the root group repeatedly. The second argument lets you get all threads, recursively:

Thread[] threads = new Thread[rootGroup.activeCount()];
while (rootGroup.enumerate(threads, true ) == threads.length) {
    threads = new Thread[threads.length * 2];
}

Note how we call enumerate() repeatedly until the array is large enough to contain all entries.

Save the plots into a PDF

Never mind got the way to do it.

def plotGraph(X,Y):
     fignum = random.randint(0,sys.maxint)
     fig = plt.figure(fignum)
     ### Plotting arrangements ###
     return fig

------ plotting module ------

----- mainModule ----

 import matplotlib.pyplot as plt
 ### tempDLStats, tempDLlabels are the argument
 plot1 = plotGraph(tempDLstats, tempDLlabels)
 plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
 plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
 plt.show()
 plot1.savefig('plot1.png')
 plot2.savefig('plot2.png')
 plot3.savefig('plot3.png')

----- mainModule -----

Invalid length for a Base-64 char array

    string stringToDecrypt = CypherText.Replace(" ", "+");
    int len = stringToDecrypt.Length;
    byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); 

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

Can't Load URL: The domain of this URL isn't included in the app's domains

Adding my localhost on Valid OAuth redirect URIs at https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/ solved the problem!

And pay attention for one detail here:

In this case http://localhost:3000 is not the same of http://0.0.0.0:3000 or http://127.0.0.1:3000

Make sure you are using exactly the running url of you sandbox server. I spend some time to discover that...

enter image description here

Append data to a POST NSURLRequest

If you don't wish to use 3rd party classes then the following is how you set the post body...

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                             delegate:self];

Simply append your key/value pair to the post string

Getting indices of True values in a boolean list

Simply do this:

def which_index(self):
    return [
        i for i in range(len(self.states))
        if self.states[i] == True
    ]

Git merge without auto commit

If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too

$ git merge --squash v1.0
$ git commit

Tri-state Check box in HTML?

You'll need to use javascript/css to fake it.

Try here for an example: http://www.dynamicdrive.com/forums/archive/index.php/t-26322.html

Disable scrolling in all mobile devices

In page header, add

<meta name="viewport" content="width=device-width, initial-scale=1, minimum-sacle=1, maximum-scale=1, user-scalable=no">

In page stylesheet, add

html, body {
  overflow-x: hidden;
  overflow-y: hidden;
}

It is both html and body!

#ifdef in C#

I would recommend you using the Conditional Attribute!

Update: 3.5 years later

You can use #if like this (example copied from MSDN):

// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
{
    static void Main() 
    {
#if (DEBUG && !VC_V7)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
        Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
        Console.WriteLine("DEBUG and VC_V7 are defined");
#else
        Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
    }
}

Only useful for excluding parts of methods.

If you use #if to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.

If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if with a method that returns a value you have to hide all pieces of code that call it too.

Here is an example:


    // calling Class1.ConditionalMethod() will be ignored at runtime 
    // unless the DEBUG constant is defined


    using System.Diagnostics;
    class Class1 
    {
       [Conditional("DEBUG")]
       public static void ConditionalMethod() {
          Console.WriteLine("Executed Class1.ConditionalMethod");
       }
    }

Summary:

I would use #ifdef in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though. You may want to use #if to avoid dependencies because with Conditional attribute your code is still compiled.

Creating a URL in the controller .NET MVC

I had the same issue, and it appears Gidon's answer has one tiny flaw: it generates a relative URL, which cannot be sent by mail.

My solution looks like this:

string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });

This way, a full URL is generated, and it works even if the application is several levels deep on the hosting server, and uses a port other than 80.

EDIT: I found this useful as well.

change Oracle user account status from EXPIRE(GRACE) to OPEN

In case you know the password of that user, or you would like to guess it, do the following:

  • connect user/password

If this command connects successufully, you will see the message "connected", otherwise you'd see an error message. If you are then successufull logging, that means that you know the password. In that case, just do:

  • alter user NAME_OF_THE_USER identified by OLD_PASSWORD;

and this will reset the password to the same password as before and also reset the account_status for that user.

Get a substring of a char*

Assuming you know the position and the length of the substring:

char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);

You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.

This is a good example of avoiding unnecessary copying by using pointers.

Difference between Static methods and Instance methods

In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.

This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.

class A {
    int a;
    int b;

    public void setParameters(int a, int b){
        this.a = a;
        this.b = b;
    }
    public int add(){
        return this.a + this.b;
   }

    public static returnSum(int s1, int s2){
        return (s1 + s2);
    }
}

In the above example, when you call add() as:

A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3 

B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5

//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10

class B{
    int s=8;
    int t = 8;
    public addition(int s,int t){
       A.returnSum(s,t);//returns 16
    }
}

In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.

How to create a sub array from another array in Java?

The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:

java -version

I'm guessing that you are not running 1.6

Winforms TableLayoutPanel adding rows programmatically

I just looked into my code. In one application, I just add the controls, but without specifying the index, and when done, I just loop through the row styles and set the size type to AutoSize. So just adding them without specifying the indices seems to add the rows as intended (provided the GrowStyle is set to AddRows).

In another application, I clear the controls and set the RowCount property to the needed value. This does not add the RowStyles. Then I add my controls, this time specifying the indices, and add a new RowStyle (RowStyles.Add(new RowStyle(...)) and this also works.

So, pick one of these methods, they both work. I remember the headaches the table layout panel caused me.

AngularJS Directive Restrict A vs E

Element is not supported in IE8 out of the box you have to do some work to make IE8 accept custom tags.

One advantage of using an attribute over an element is that you can apply multiple directives to the same DOM node. This is particularly handy for things like form controls where you can highlight, disable, or add labels etc. with additional attributes without having to wrap the element in a bunch of tags.

Read Excel File in Python

By using pandas we can read excel easily.

import pandas as pd 
from pandas import ExcelWriter
from pandas import ExcelFile 

DataF=pd.read_excel("Test.xlsx",sheet_name='Sheet1')

print("Column headings:")
print(DataF.columns)

Test at :https://repl.it Reference: https://pythonspot.com/read-excel-with-pandas/