Programs & Examples On #Percent encoding

Percent-encoding (aka URL encoding) is the way that non-alphabet characters are encoded in URLs and URIs (e.g. spaces turn into %20).

Encode/Decode URLs in C++

Had to do it in a project without Boost. So, ended up writing my own. I will just put it on GitHub: https://github.com/corporateshark/LUrlParser

clParseURL URL = clParseURL::ParseURL( "https://name:[email protected]:80/path/res" );

if ( URL.IsValid() )
{
    cout << "Scheme    : " << URL.m_Scheme << endl;
    cout << "Host      : " << URL.m_Host << endl;
    cout << "Port      : " << URL.m_Port << endl;
    cout << "Path      : " << URL.m_Path << endl;
    cout << "Query     : " << URL.m_Query << endl;
    cout << "Fragment  : " << URL.m_Fragment << endl;
    cout << "User name : " << URL.m_UserName << endl;
    cout << "Password  : " << URL.m_Password << endl;
}

Run a task every x-minutes with Windows Task Scheduler

Some of the links provided are only settings for Windows 2003's version of "Scheduled Tasks"

In Windows Server 2008 the "Tasks" setup only has a box with options for "5 Minutes, 10 minutes, 15 minutes, 30 mins, and 1 hour" (screen shot: http://i46.tinypic.com/2gwx7r8.jpg)... where the Window 2003 was a "enter whatever number you want" textbox.

I thought doing an "Export" and editing the XML from: PT30M to PT2M

and importing that as a new task would "trick" Tasks into repeating every 2 mins, but it didn't like that

My workaround for getting a task to run every 2 mins in Windows 2008 was to (ugggh) setup 30 different "triggers" for my task repeating every hour but staring at :00, :02, :04, :06 and so on and so on.... took me 8-10 mins to setup but I only had to do it once :-)

How to convert std::string to LPCWSTR in C++ (Unicode)

Instead of using a std::string, you could use a std::wstring.

EDIT: Sorry this is not more explanatory, but I have to run.

Use std::wstring::c_str()

Python 3 ImportError: No module named 'ConfigParser'

In Python 3, ConfigParser has been renamed to configparser for PEP 8 compliance. It looks like the package you are installing does not support Python 3.

Inline IF Statement in C#

You can do inline ifs with

return y == 20 ? 1 : 2;

which will give you 1 if true and 2 if false.

Make a phone call programmatically

Tried the Swift 3 option above, but it didnt work. I think you need the following if you are to run against iOS 10+ on Swift 3:

Swift 3 (iOS 10+):

let phoneNumber = mymobileNO.titleLabel.text       
UIApplication.shared.open(URL(string: phoneNumber)!, options: [:], completionHandler: nil)

Spring @Value is not resolving to value from property file

for Sprig-boot User both PropertyPlaceholderConfigurer and the new PropertySourcesPlaceholderConfigurer added in Spring 3.1. so it's straightforward to access properties file. just inject

Note: Make sure your property must not be Static

@Value("${key.value1}")
private String value;

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

removeEventListener has the same signature as addEventListener. All of the arguments must be exactly the same for it to remove the listener.

var onEnded = () => {};
audioNode.addEventListener('ended', onEnded, false);

this.cleanup = () => {
  audioNode.removeEventListener('ended', onEnded, false);
}

And in componentWillUnmount call this.cleanup().

The static keyword and its various uses in C++

What does it mean with local variable? Is that a function local variable?

Yes - Non-global, such as a function local variable.

Because there's also that when you declare a function local as static that it is only initialized once, the first time it enters this function.

Right.

It also only talks about storage duration with regards to class members, what about it being non instance specific, that's also a property of static no? Or is that storage duration?

class R { static int a; }; // << static lives for the duration of the program

that is to say, all instances of R share int R::a -- int R::a is never copied.

Now what about the case with static and file scope?

Effectively a global which has constructor/destructor where appropriate -- initialization is not deferred until access.

How does static relate to the linkage of a variable?

For a function local, it is external. Access: It's accessible to the function (unless of course, you return it).

For a class, it is external. Access: Standard access specifiers apply (public, protected, private).

static can also specify internal linkage, depending on where it's declared (file/namespace).

This whole static keyword is downright confusing

It has too many purposes in C++.

can someone clarify the different uses for it English and also tell me when to initialize a static class member?

It's automatically initialized before main if it's loaded and has a constructor. That might sound like a good thing, but initialization order is largely beyond your control, so complex initialization becomes very difficult to maintain, and you want to minimize this -- if you must have a static, then function local scales much better across libraries and projects. As far as data with static storage duration, you should try to minimize this design, particularly if mutable (global variables). Initialization 'time' also varies for a number of reasons -- the loader and kernel have some tricks to minimize memory footprints and defer initialization, depending on the data in question.

Is there a way to know your current username in mysql?

Use this query:

SELECT USER();

Or

SELECT CURRENT_USER;

Java: parse int value from a char

That's probably the best from the performance point of view, but it's rough:

String element = "el5";
String s;
int x = element.charAt(2)-'0';

It works if you assume your character is a digit, and only in languages always using Unicode, like Java...

Email address validation in C# MVC 4 application: with or without using Regex

Don't.

Use a regex for a quick sanity check, something like .@.., but almost all langauges / frameworks have better methods for checking an e-mail address. Use that.

It is possible to validate an e-mail address with a regex, but it is a long regex. Very long.
And in the end you will be none the wiser. You'll only know that the format is valid, but you still don't know if it's an active e-mail address. The only way to find out, is by sending a confirmation e-mail.

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

identifier "string" undefined?

Because string is defined in the namespace std. Replace string with std::string, or add

using std::string;

below your include lines.

It probably works in main.cpp because some other header has this using line in it (or something similar).

Sending and Parsing JSON Objects in Android

You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

I am in ubuntu 14.04 and mongod is registered as an upstart service. The answers in this post sent me in the right direction. The only adaptation I had to do to make things work with the upstart service was to edit /etc/mongod.conf. Look for the lines that read:

# Enable the HTTP interface (Defaults to port 28017).
# httpinterface = true

Just remove the # in front of httpinterface and restart the mongod service:

sudo restart mongod

Note: You can also enable the rest interface by adding a line that reads rest=true right below the httpinterface line mentioned above.

Search for string and get count in vi editor

:g/xxxx/d

This will delete all the lines with pattern, and report how many deleted. Undo to get them back after.

WAMP shows error 'MSVCR100.dll' is missing when install

When installing Wamperserver 3 on windows 10, it now gives a nice big warning during the install telling you it won't work unless you install many of these packages.

It worked for me after I followed the instructions and then restart the computer and reinstalled.

--- Installation of Wampserver --- BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing. Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 , VC14 and VC15 See --- Visual C++ Packages below.

--- Do not install Wampserver OVER an existing version, follow the advice: - Install a new version of Wampserver: http://forum.wampserver.com/read.php?2,123606 If you install Wampserver over an existing version, not only it will not work, but you risk losing your existing databases.

--- Install Wampserver in a folder at the root of a disk, for example C:\wamp or D:\wamp. Take an installation path that does not include spaces or diacritics; Therefore, no installation in c: \ Program Files\ or C: \ Program Files (x86\ We must BEFORE installing, disable or close some applications: - Close Skype or force not to use port 80 Item No. 04 of the Wampserver TROUBLESHOOTING TIPS:http://forum.wampserver.com/read.php?2,134915 - Disable IIS Item No. 08 of the Wampserver TROUBLESHOOTING TIPS:http://forum.wampserver.com/read.php?2,134915 If these prerequisites are not in place, Press the Cancel button to cancel the installation, then apply the prerequisites and restart the installation. This program requires Administrator privileges to function properly. It will be launched with the "Run as administrator" option. If you do not want a program to have this option, cancel the installation.

--- Visual C++ Packages --- The MSVC runtime libraries VC9, VC10, VC11 are required for Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions with VC11. Runtimes VC13, VC14 is required for PHP 7 and Apache 2.4.17 or more

-- VC9 Packages (Visual C++ 2008 SP1) http://www.microsoft.com/en-us/download/details.aspx?id=5582 http://www.microsoft.com/en-us/download/details.aspx?id=2092

-- VC10 Packages (Visual C++ 2010 SP1) http://www.microsoft.com/en-us/download/details.aspx?id=8328 http://www.microsoft.com/en-us/download/details.aspx?id=13523

-- VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679 -- VC13 Packages Update 5(Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: https://support.microsoft.com/en-us/help/4032938/

-- VC14 Packages (Visual C++ 2015 Update 3) Supersedes by VC15 - VC15 Redistribuable (Visual C++ 2017) https://aka.ms/vs/15/release/VC_redist.x86.exe https://aka.ms/vs/15/release/VC_redist.x64.exe VC2017 (VC15) is backward compatible to VC2015 (VC14). That means, a VC14 module can be used inside a VC15 binary. Because this compatibility the version number of the Redistributable is 14.1x.xx and after you install the Redistributable VC2017, VC2015 is removed but you can still use VC14.

If you have a 64-bit Windows, you must install both 32 and 64bit versions of each VisualC++ package, even if you do not use Wampserver 64 bit To verify that all VC ++ packages are installed and with the latest versions, you can use the tool: http://wampserver.aviatechno.net/files/tools/check_vcredist.exe and you will find all the packages on http://wampserver.aviatechno.net/ in section Visual C++ Redistribuable Packages You must install each package "as an administrator", so right-click the exe file and then run as Administrator. Do not use a previously loaded tool. Make a new download to make sure you are using the correct version.

Warning: Sometimes Microsoft may update the VC ++ package by breaking the download links and without redirect to the new. If the case happens to you, remember that item number 20 below will be updated and the page http://wampserver.aviatechno.net/ section Visual C++ Redistribuable Packages is up to date. This is item number 20 of TROUBLESHOOTING TIPS of Wampserver: http://forum.wampserver.com/read.php?2,134915

How to concatenate two numbers in javascript?

You can return a number by using this trick:
not recommended

[a] + b - 0

Example :

let output = [5] + 6 - 0;
console.log(output); // 56
console.log(typeof output); // number

gson throws MalformedJsonException

From my recent experience, JsonReader#setLenient basically makes the parser very tolerant, even to allow malformed JSON data.

But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply trim the data would avoid the error:

String trimmed = result1.trim();

Then gson.fromJson(trimmed, T) might work. Surely this only covers a special case, so YMMV.

How to change the button text of <input type="file" />?

EDIT: I see now by the comments that you are asking about the button text, and not the file path. My bad. I'll leave my original answer below in case someone else who stumbles upon this question interprets it the way I originally did.

2nd EDIT: I had deleted this answer because I decided that I misunderstood the question and my answer was not relevant. However, comments in another answer indicated that people still wanted to see this answer so I'm undeleting it.

MY ORIGINAL ANSWER (I thought the OP was asking about the path, not the button text):

This is not a supported feature for security reasons. The Opera web browser used to support this but it was removed. Think about what would be possible if this were supported; You could make a page with a file upload input, pre-populate it with a path to some sensitive file and then auto-submit the form using javascript triggered by the onload event. This would happen too fast for the user to do anything about it.

How do I execute a stored procedure in a SQL Agent job?

As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

How to round up integer division and have int result in Java?

Google's Guava library handles this in the IntMath class:

IntMath.divide(numerator, divisor, RoundingMode.CEILING);

Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.

How to remove element from ArrayList by checking its value?

You would need to use an Iterator like so:

Iterator<String> iterator = a.iterator();
while(iterator.hasNext())
{
    String value = iterator.next();
    if ("abcd".equals(value))
    {
        iterator.remove();
        break;
    }
}

That being said, you can use the remove(int index) or remove(Object obj) which are provided by the ArrayList class. Note however, that calling these methods while you are iterating over the loop, will cause a ConcurrentModificationException, so this will not work:

for(String str : a)
{
    if (str.equals("acbd")
    {
        a.remove("abcd");
        break;
    }
}

But this will (since you are not iterating over the contents of the loop):

a.remove("acbd");

If you have more complex objects you would need to override the equals method.

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

I had the same problem and my solution was the following:

Instead of deleting the main applicationhost.config (in your "Documents/IIS Express" folder), check your solution folder for a hidden ".vs" folder with a "config" sub-folder. If that folder exists and it has it's own applicationhost.config file you need to either rename (or delete) that file or edit it and make sure the website(s) configured inside match the ASP.NET web app(s) in your solution that you are trying to debug. Hope this helps.

jQuery Datepicker onchange event issue

$('#inputfield').change(function() { 
    dosomething();
});

How do you calculate the variance, median, and standard deviation in C++ or Java?

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

double stddev = Math.sqrt( variance );

git pull while not in a git directory

You may wrap it in a bash script or git alias:

cd /X/Y && git pull && cd -

How do I use su to execute the rest of the bash script as that user?

This worked for me

I split out my "provisioning" from my "startup".

 # Configure everything else ready to run 
  config.vm.provision :shell, path: "provision.sh"
  config.vm.provision :shell, path: "start_env.sh", run: "always"

then in my start_env.sh

#!/usr/bin/env bash

echo "Starting Server Env"
#java -jar /usr/lib/node_modules/selenium-server-standalone-jar/jar/selenium-server-standalone-2.40.0.jar  &
#(cd /vagrant_projects/myproj && sudo -u vagrant -H sh -c "nohup npm install 0<&- &>/dev/null &;bower install 0<&- &>/dev/null &")
cd /vagrant_projects/myproj
nohup grunt connect:server:keepalive 0<&- &>/dev/null &
nohup apimocker -c /vagrant_projects/myproj/mock_api_data/config.json 0<&- &>/dev/null &

How do I add PHP code/file to HTML(.html) files?

You can't run PHP in .html files because the server does not recognize that as a valid PHP extension unless you tell it to. To do this you need to create a .htaccess file in your root web directory and add this line to it:

AddType application/x-httpd-php .htm .html

This will tell Apache to process files with a .htm or .html file extension as PHP files.

How do I get a UTC Timestamp in JavaScript?

You could also do it utilizing getTimezoneOffset and getTime,

_x000D_
_x000D_
x = new Date()_x000D_
var UTCseconds = (x.getTime() + x.getTimezoneOffset()*60*1000)/1000;_x000D_
_x000D_
console.log("UTCseconds", UTCseconds)
_x000D_
_x000D_
_x000D_

Using a bitmask in C#

I have included an example here which demonstrates how you might store the mask in a database column as an int, and how you would reinstate the mask later on:

public enum DaysBitMask { Mon=0, Tues=1, Wed=2, Thu = 4, Fri = 8, Sat = 16, Sun = 32 }


DaysBitMask mask = DaysBitMask.Sat | DaysBitMask.Thu;
bool test;
if ((mask & DaysBitMask.Sat) == DaysBitMask.Sat)
    test = true;
if ((mask & DaysBitMask.Thu) == DaysBitMask.Thu)
    test = true;
if ((mask & DaysBitMask.Wed) != DaysBitMask.Wed)
    test = true;

// Store the value
int storedVal = (int)mask;

// Reinstate the mask and re-test
DaysBitMask reHydratedMask = (DaysBitMask)storedVal;

if ((reHydratedMask & DaysBitMask.Sat) == DaysBitMask.Sat)
    test = true;
if ((reHydratedMask & DaysBitMask.Thu) == DaysBitMask.Thu)
    test = true;
if ((reHydratedMask & DaysBitMask.Wed) != DaysBitMask.Wed)
    test = true;

How to declare and add items to an array in Python?

I believe you are all wrong. you need to do:

array = array[] in order to define it, and then:

array.append ["hello"] to add to it.

How can I add a hint text to WPF textbox?

This is my simple solution, adapted from Microsoft (https://code.msdn.microsoft.com/windowsapps/How-to-add-a-hint-text-to-ed66a3c6)

    <Grid Background="White" HorizontalAlignment="Right" VerticalAlignment="Top"  >
        <!-- overlay with hint text -->
        <TextBlock Margin="5,2" MinWidth="50" Text="Suche..." 
                   Foreground="LightSteelBlue" Visibility="{Binding ElementName=txtSearchBox, Path=Text.IsEmpty, Converter={StaticResource MyBoolToVisibilityConverter}}" IsHitTestVisible="False"/>
        <!-- enter term here -->
        <TextBox MinWidth="50" Name="txtSearchBox" Background="Transparent" />
    </Grid>

Remove Rows From Data Frame where a Row matches a String

I had a column(A) in a data frame with 3 values in it (yes, no, unknown). I wanted to filter only those rows which had a value "yes" for which this is the code, hope this will help you guys as well --

df <- df [(!(df$A=="no") & !(df$A=="unknown")),]

Escaping backslash in string - javascript

For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.

This question already mentions, and links to other Stack Overflow questions regarding this topic.


Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.

string = string.split("\\");

In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.

So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.

Cannot hide status bar in iOS7

Steps For Hide the status bar in iOS 7:

1.Go to your application info.plist file.

2.And Set, View controller-based status bar appearance : Boolean NO

Hope i solved the status bar issue.....

How do JavaScript closures work?

A closure is basically creating two things : - a function - a private scope that only that function can access

It is like putting some coating around a function.

So to a 6-years-old, it could be explained by giving an analogy. Let's say I build a robot. That robot can do many things. Among those things, I programmed it to count the number of birds he sees in the sky. Each time he has seen 25 birds, he should tell me how many birds he has seen since the beginning.

I don't know how many birds he has seen unless he has told me. Only he knows. That's the private scope. That's basically the robot's memory. Let's say I gave him 4 GB.

Telling me how many birds he has seen is the returned function. I also created that.

That analogy is a bit sucky, but someone could improve it I guess.

filter items in a python dictionary where keys contain a specific string

How about a dict comprehension:

filtered_dict = {k:v for k,v in d.iteritems() if filter_string in k}

One you see it, it should be self-explanatory, as it reads like English pretty well.

This syntax requires Python 2.7 or greater.

In Python 3, there is only dict.items(), not iteritems() so you would use:

filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}

subtract time from date - moment js

There is a simple function subtract which moment library gives us to subtract time from some time. Using it is also very simple.

moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time

//You can do this for days, years, months, hours, minutes, seconds
//You can also subtract multiple things simulatneously

//You can chain it like this.
moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time

//You can also use it as object literal
moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time

Hope this helps!

Remove credentials from Git

Try using the below command.

git credential-manager

Here you can get various options to manage your credentials (check the below screen).

Enter image description here

Or you can even directly try this command:

git credential-manager uninstall

This will start prompting for passwords again on each server interaction request.

Parsing HTTP Response in Python

When I printed response.read() I noticed that b was preprended to the string (e.g. b'{"a":1,..). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string'), I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8'). Once it was in a string type my problem was solved and I was easily able to iterate over the dict.

I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:

from urllib.request import urlopen
import json

# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)

print(json_obj['source_name']) # prints the string with 'source_name' key

LINQ: "contains" and a Lambda query

var depthead = (from s in db.M_Users
                  join m in db.M_User_Types on s.F_User_Type equals m.UserType_Id
                  where m.UserType_Name.ToUpper().Trim().Contains("DEPARTMENT HEAD")
                  select new {s.FullName,s.F_User_Type,s.userId,s.UserCode } 
               ).OrderBy(d => d.userId).ToList();

Model.AvailableDeptHead.Add(new SelectListItem { Text = "Select", Value = "0" });
for (int i = 0; i < depthead.Count; i++)
    Model.AvailableDeptHead.Add(new SelectListItem { Text = depthead[i].UserCode + " - " + depthead[i].FullName, Value = Convert.ToString(depthead[i].userId) });

How to start jenkins on different port rather than 8080 using command prompt in Windows?

In *nix In CentOS/RedHat

vim /etc/sysconfig/jenkins

# Port Jenkins is listening on.
# Set to -1 to disable
#
JENKINS_PORT="8080"

In windows open XML file C:\Program Files (x86)\Jenkins\jenkins.xml

<executable>%BASE%\jre\bin\java</executable>
  <arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --**httpPort=8083**</arguments>
 i made  above bold  to show you change then 
 <executable>%BASE%\jre\bin\java</executable>
  <arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8083</arguments>

now you have to restart it doesnot work unless you restart http://localhost:8080/restart then after restart http://localhost:8083/ all should be well so looks like the all above response which says it does not work We have restart.

Include CSS,javascript file in Yii Framework

In Yii framework, You can include js and css using below method.

Including CSS:

{Yii::app()->request->baseUrl}/css/styles.css

Including JS:

{Yii::app()->request->baseUrl}/js/script.js

Including Image:

{Yii::app()->request->baseUrl}/images/logo.jpg

Note: By using layout concept in yii, You can add css and js instead of specifying in view template.

Truncating Text in PHP?

The obvious thing to do is read the documentation.

But to help: substr($str, $start, $end);

$str is your text

$start is the character index to begin at. In your case, it is likely 0 which means the very beginning.

$end is where to truncate at. Suppose you wanted to end at 15 characters, for example. You would write it like this:

<?php

$text = "long text that should be truncated";
echo substr($text, 0, 15);

?>

and you would get this:

long text that 

makes sense?

EDIT

The link you gave is a function to find the last white space after chopping text to a desired length so you don't cut off in the middle of a word. However, it is missing one important thing - the desired length to be passed to the function instead of always assuming you want it to be 25 characters. So here's the updated version:

function truncate($text, $chars = 25) {
    if (strlen($text) <= $chars) {
        return $text;
    }
    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

So in your case you would paste this function into the functions.php file and call it like this in your page:

$post = the_post();
echo truncate($post, 100);

This will chop your post down to the last occurrence of a white space before or equal to 100 characters. Obviously you can pass any number instead of 100. Whatever you need.

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

Convert normal Java Array or ArrayList to Json Array in android

you need external library

 json-lib-2.2.2-jdk15.jar

List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");

JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);

Google Gson is the best library http://code.google.com/p/google-gson/

Accessing a value in a tuple that is in a list

a = [(0,2), (4,3), (9,9), (10,-1)]
print(list(map(lambda item: item[1], a)))

How Do I Uninstall Yarn

On my Mac neither of these regular methods to uninstall Yarn worked:

brew: brew uninstall yarn

npm: npm uninstall -g yarn

Instead I removed it manually by typing rm -rf ~/.yarn (thanks user elthrasher) and deleting the two symbol links yarn and yarnpkg from usr/local/bin. Afterwards brew install yarn gave me the latest version of Yarn.


Background: The fact that I had a very outdated version of Yarn installed gave me utterly incomprehensible errors while trying to install additional modules to a project set up with Vue CLI Service and Vue UI, which apparently uses Yarn 'under the hood'. I generally use NPM so it took me a while to figure out the cause for my trouble. Naturally googling error messages produced by such module incompatibilities presented no clues. With Yarn updated everything works just perfectly now.

Recording video feed from an IP camera over a network

Why don't you consider www.cameraftp.com? it supports image upload and online viewer

Java Error: illegal start of expression

Remove the public keyword from int[] locations={1,2,3};. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.

If your goal is to use this reference in many a method, you might want to move the declaration outside the method.

Difference between numpy dot() and Python 3.5+ matrix multiplication @

In mathematics, I think the dot in numpy makes more sense

dot(a,b)_{i,j,k,a,b,c} = formula

since it gives the dot product when a and b are vectors, or the matrix multiplication when a and b are matrices


As for matmul operation in numpy, it consists of parts of dot result, and it can be defined as

>matmul(a,b)_{i,j,k,c} = formula

So, you can see that matmul(a,b) returns an array with a small shape, which has smaller memory consumption and make more sense in applications. In particular, combining with broadcasting, you can get

matmul(a,b)_{i,j,k,l} = formula

for example.


From the above two definitions, you can see the requirements to use those two operations. Assume a.shape=(s1,s2,s3,s4) and b.shape=(t1,t2,t3,t4)

  • To use dot(a,b) you need

    1. t3=s4;
  • To use matmul(a,b) you need

    1. t3=s4
    2. t2=s2, or one of t2 and s2 is 1
    3. t1=s1, or one of t1 and s1 is 1

Use the following piece of code to convince yourself.

Code sample

import numpy as np
for it in xrange(10000):
    a = np.random.rand(5,6,2,4)
    b = np.random.rand(6,4,3)
    c = np.matmul(a,b)
    d = np.dot(a,b)
    #print 'c shape: ', c.shape,'d shape:', d.shape

    for i in range(5):
        for j in range(6):
            for k in range(2):
                for l in range(3):
                    if not c[i,j,k,l] == d[i,j,k,j,l]:
                        print it,i,j,k,l,c[i,j,k,l]==d[i,j,k,j,l] #you will not see them

Error message Strict standards: Non-static method should not be called statically in php

I think this may answer your question.

Non-static method ..... should not be called statically

If the method is not static you need to initialize it like so:

$var = new ClassName();
$var->method();

Or, in PHP 5.4+, you can use this syntax:

(new ClassName)->method();

PHP cURL HTTP CODE return 0

check the curl_error after the curl_getinfo to find out the hidden errors.

if(curl_errno($ch)){   
    echo 'Curl error: ' . curl_error($ch);
}

How do you round UP a number in Python?

If working with integers, one way of rounding up is to take advantage of the fact that // rounds down: Just do the division on the negative number, then negate the answer. No import, floating point, or conditional needed.

rounded_up = -(-numerator // denominator)

For example:

>>> print(-(-101 // 5))
21

Retrofit 2 - Dynamic URL

You can use this :

@GET("group/{id}/users")

Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

For more information see documentation https://square.github.io/retrofit/

MySQL Multiple Where Clause

SELECT a.image_id 
FROM list a
INNER JOIN list b
   ON a.image_id = b.image_id
   AND b.style_id = 25
   AND b.style_value = 'big'
INNER JOIN list c
   ON a.image_id = c.image_id
   AND c.style_id = 27
   AND c.style_value = 'round'
WHERE a.style_id = 24 
   AND a.style_value = 'red'

Difference between array_push() and $array[] =

array_push — Push one or more elements onto the end of array

Take note of the words "one or more elements onto the end" to do that using $arr[] you would have to get the max size of the array

How to get the current location latitude and longitude in android

try this, hope it will help you to get the current location, every time the location changes.

public class MyClass implements LocationListener {
    double currentLatitude, currentLongitude;

    public void onLocationChanged(Location location) {
        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();
    }
}

Example of waitpid() in use?

Syntax of waitpid():

pid_t waitpid(pid_t pid, int *status, int options);

The value of pid can be:

  • < -1: Wait for any child process whose process group ID is equal to the absolute value of pid.
  • -1: Wait for any child process.
  • 0: Wait for any child process whose process group ID is equal to that of the calling process.
  • > 0: Wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

  • WNOHANG: Return immediately if no child has exited.
  • WUNTRACED: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED: Also return if a stopped child has been resumed by delivery of SIGCONT.

For more help, use man waitpid.

Does Hive have a String split function?

There does exist a split function based on regular expressions. It's not listed in the tutorial, but it is listed on the language manual on the wiki:

split(string str, string pat)
   Split str around pat (pat is a regular expression) 

In your case, the delimiter "|" has a special meaning as a regular expression, so it should be referred to as "\\|".

Print the address or pointer for value in C

Since you already seem to have solved the basic pointer address display, here's how you would check the address of a double pointer:

char **a;
char *b;
char c = 'H';

b = &c;
a = &b;

You would be able to access the address of the double pointer a by doing:

printf("a points at this memory location: %p", a);
printf("which points at this other memory location: %p", *a);

mysql update query with sub query

You can check your eav_attributes table to find the relevant attribute IDs for each image role, such as; eav_attributes

Then you can use those to set whichever role to any other role for all products like so;

UPDATE catalog_product_entity_varchar AS `v` INNER JOIN (SELECT `value`,`entity_id` FROM `catalog_product_entity_varchar` WHERE `attribute_id`=86) AS `j` ON `j`.`entity_id`=`v`.entity_id SET `v`.`value`=j.`value` WHERE `v`.attribute_id = 85 AND `v`.`entity_id`=`j`.`entity_id`

The above will set all your 'base' roles to the 'small' image of the same product.

Asserting successive calls to a mock method

I always have to look this one up time and time again, so here is my answer.


Asserting multiple method calls on different objects of the same class

Suppose we have a heavy duty class (which we want to mock):

In [1]: class HeavyDuty(object):
   ...:     def __init__(self):
   ...:         import time
   ...:         time.sleep(2)  # <- Spends a lot of time here
   ...:     
   ...:     def do_work(self, arg1, arg2):
   ...:         print("Called with %r and %r" % (arg1, arg2))
   ...:  

here is some code that uses two instances of the HeavyDuty class:

In [2]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(13, 17)
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(23, 29)
   ...:    


Now, here is a test case for the heavy_work function:

In [3]: from unittest.mock import patch, call
   ...: def test_heavy_work():
   ...:     expected_calls = [call.do_work(13, 17),call.do_work(23, 29)]
   ...:     
   ...:     with patch('__main__.HeavyDuty') as MockHeavyDuty:
   ...:         heavy_work()
   ...:         MockHeavyDuty.return_value.assert_has_calls(expected_calls)
   ...:  

We are mocking the HeavyDuty class with MockHeavyDuty. To assert method calls coming from every HeavyDuty instance we have to refer to MockHeavyDuty.return_value.assert_has_calls, instead of MockHeavyDuty.assert_has_calls. In addition, in the list of expected_calls we have to specify which method name we are interested in asserting calls for. So our list is made of calls to call.do_work, as opposed to simply call.

Exercising the test case shows us it is successful:

In [4]: print(test_heavy_work())
None


If we modify the heavy_work function, the test fails and produces a helpful error message:

In [5]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(113, 117)  # <- call args are different
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(123, 129)  # <- call args are different
   ...:     

In [6]: print(test_heavy_work())
---------------------------------------------------------------------------
(traceback omitted for clarity)

AssertionError: Calls not found.
Expected: [call.do_work(13, 17), call.do_work(23, 29)]
Actual: [call.do_work(113, 117), call.do_work(123, 129)]


Asserting multiple calls to a function

To contrast with the above, here is an example that shows how to mock multiple calls to a function:

In [7]: def work_function(arg1, arg2):
   ...:     print("Called with args %r and %r" % (arg1, arg2))

In [8]: from unittest.mock import patch, call
   ...: def test_work_function():
   ...:     expected_calls = [call(13, 17), call(23, 29)]    
   ...:     with patch('__main__.work_function') as mock_work_function:
   ...:         work_function(13, 17)
   ...:         work_function(23, 29)
   ...:         mock_work_function.assert_has_calls(expected_calls)
   ...:    

In [9]: print(test_work_function())
None


There are two main differences. The first one is that when mocking a function we setup our expected calls using call, instead of using call.some_method. The second one is that we call assert_has_calls on mock_work_function, instead of on mock_work_function.return_value.

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Try this:

<div id="wrapper">
    <div class="float left">left</div>
    <div class="float right">right</div>
</div>

#wrapper {
   width:500px; 
   height:300px; 
   position:relative;
}

.float {
   background-color:black; 
   height:300px; 
   margin:0; 
   padding:0; 
   color:white;
}

.left {
   background-color:blue; 
   position:fixed; 
   width:400px;
}

.right {
   float:right; 
   width:100px;
}

jsFiddle: http://jsfiddle.net/khA4m

How to get time difference in minutes in PHP

Subtract the times and divide by 60.

Here is an example which calculate elapsed time from 2019/02/01 10:23:45 in minutes:

$diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;

How to use regex with find command?

Try to use single quotes (') to avoid shell escaping of your string. Remember that the expression needs to match the whole path, i.e. needs to look like:

 find . -regex '\./[a-f0-9-]*.jpg'

Apart from that, it seems that my find (GNU 4.4.2) only knows basic regular expressions, especially not the {36} syntax. I think you'll have to make do without it.

How do you create a Marker with a custom icon for google maps API v3?

Try

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      icon: 'http://imageshack.us/a/img826/9489/x1my.png',
      map: map
    });

from here

https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom

Least common multiple for 3 or more numbers

And the Scala version:

def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
def gcd(nums: Iterable[Int]): Int = nums.reduce(gcd)
def lcm(a: Int, b: Int): Int = if (a == 0 || b == 0) 0 else a * b / gcd(a, b)
def lcm(nums: Iterable[Int]): Int = nums.reduce(lcm)

What is code coverage and how do YOU measure it?

Code coverage is simply a measure of the code that is tested. There are a variety of coverage criteria that can be measured, but typically it is the various paths, conditions, functions, and statements within a program that makeup the total coverage. The code coverage metric is the just a percentage of tests that execute each of these coverage criteria.

As far as how I go about tracking unit test coverage on my projects, I use static code analysis tools to keep track.

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

Update: I've since written a very detailed explanation of the various ways you can install Ruby gems on a Mac. My original recommendation to use a script still stands, but my article goes into more detail: https://www.moncefbelyamani.com/the-definitive-guide-to-installing-ruby-gems-on-a-mac/

You are correct that macOS won't let you change anything with the Ruby version that comes installed with your Mac. However, it's possible to install gems like bundler using a separate version of Ruby that doesn't interfere with the one provided by Apple.

Using sudo to install gems, or changing permissions of system files and directories is strongly discouraged, even if you know what you are doing. Can we please stop providing this bad advice? Here's a detailed article I wrote showing how sudo gem install can wipe out your computer: https://www.moncefbelyamani.com/why-you-should-never-use-sudo-to-install-ruby-gems/

The solution involves two main steps:

  1. Install a separate version of Ruby that does not interfere with the one that came with your Mac.
  2. Update your PATH such that the location of the new Ruby version is first in the PATH. Some tools do this automatically for you. If you're not familiar with the PATH and how it works, read my guide.

There are several ways to install Ruby on a Mac. The best way that I recommend, and that I wish was more prevalent in the various installation instructions out there, is to use an automated script that will set up a proper Ruby environment for you. This drastically reduces the chances of running into an error due to inadequate instructions that make the user do a bunch of stuff manually and leaving it up to them to figure out all the necessary steps.

The other route you can take is to spend extra time doing everything manually and hoping for the best. First, you will want to install Homebrew, which installs the prerequisite command line tools, and makes it easy to install other necessary tools.

Then, the two easiest ways to install a separate version of Ruby are:

If you would like the flexibility of easily switching between many Ruby versions [RECOMMENDED]

Choose one of these four options:

  • chruby and ruby-install - my personal recommendations and the ones that are automatically installed by my script. These can be installed with Homebrew:
brew install chruby ruby-install

If you chose chruby and ruby-install, you can then install the latest Ruby like this:

ruby-install ruby

Once you've installed everything and configured your .zshrc or .bash_profile according to the instructions from the tools above, quit and restart Terminal, then switch to the version of Ruby that you want. In the case of chruby, it would be something like this:

chruby 2.7.2

Whether you need to configure .zshrc or .bash_profile depends on which shell you are using. If you're not sure, read this guide: https://www.moncefbelyamani.com/which-shell-am-i-using-how-can-i-switch/

If you know for sure you don't need more than one version of Ruby at the same time (besides the one that came with macOS)

  • Install ruby with Homebrew:
brew install ruby

Then update your PATH by running (replace 2.7.0 with your newly installed version):

echo 'export PATH="/usr/local/opt/ruby/bin:/usr/local/lib/ruby/gems/2.7.0/bin:$PATH"' >> ~/.zshrc

Then "refresh" your shell for these changes to take effect:

source ~/.zshrc

Or you can open a new terminal tab, or quit and restart Terminal.

Replace .zshrc with .bash_profile if you are using Bash. If you're not sure which shell you are using, read this guide: https://www.moncefbelyamani.com/which-shell-am-i-using-how-can-i-switch/

To check that you're now using the non-system version of Ruby, you can run the following commands:

which ruby

It should be something other than /usr/bin/ruby

ruby -v

It should be something other than 2.6.3 if you're on macOS Catalina. As of today, 2.7.2 is the latest Ruby version.

Once you have this new version of Ruby installed, you can now install bundler (or any other gem):

gem install bundler

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

If you're running IIS 6 and above, make sure the application pool your MVC app. is using is set to Integrated Managed Pipeline Mode. I had mine set to Classic by mistake and the same error occurred.

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

Since you have not specified you are connected to a server from the device or emulator so I guess you are using your application in the emulator.

If you are referring your localhost on your system from the Android emulator then you have to use http://10.0.2.2:8080/ Because Android emulator runs in a Virtual Machine therefore here 127.0.0.1 or localhost will be emulator's own loopback address.

Refer: Emulator Networking

Change WPF controls from a non-main thread using Dispatcher.Invoke

japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => { 
    this.progressBar.Value = 50;
  }));

Information for other users who want to know about performance:

If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.

if(Application.Current.Dispatcher.CheckAccess())
{
    this.progressBar.Value = 50;
}
else
{
    Application.Current.Dispatcher.BeginInvoke(
      DispatcherPriority.Background,
      new Action(() => { 
        this.progressBar.Value = 50;
      }));
}

Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.

Fastest way to copy a file in Node.js

benweet's solution, but also checking the visibility of the file before copy:

function copy(from, to) {
    return new Promise(function (resolve, reject) {
        fs.access(from, fs.F_OK, function (error) {
            if (error) {
                reject(error);
            } else {
                var inputStream = fs.createReadStream(from);
                var outputStream = fs.createWriteStream(to);

                function rejectCleanup(error) {
                    inputStream.destroy();
                    outputStream.end();
                    reject(error);
                }

                inputStream.on('error', rejectCleanup);
                outputStream.on('error', rejectCleanup);

                outputStream.on('finish', resolve);

                inputStream.pipe(outputStream);
            }
        });
    });
}

Python: download a file from an FTP server

requests library doesn't support ftp links.

To download a file from FTP server you could:

import urllib 

urllib.urlretrieve('ftp://server/path/to/file', 'file')
# if you need to pass credentials:
#   urllib.urlretrieve('ftp://username:password@server/path/to/file', 'file')

Or:

import shutil
import urllib2
from contextlib import closing

with closing(urllib2.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

Python3:

import shutil
import urllib.request as request
from contextlib import closing

with closing(request.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

If you look at the PHP constant PATH_SEPARATOR, you will see it being ":" for you.

If you break apart your string ".:/usr/share/pear:/usr/share/php" using that character, you will get 3 parts.

  • . (this means the current directory your code is in)
  • /usr/share/pear
  • /usr/share/php

Any attempts to include()/require() things, will look in these directories, in this order.

It is showing you that in the error message to let you know where it could NOT find the file you were trying to require()

For your first require, if that is being included from your index.php, then you dont need the dir stuff, just do...

require_once ( 'db/config.php');

Install pdo for postgres Ubuntu

Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):

apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql

or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:

apt-get install php5-pgsql

Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:

dpkg -s libpq-dev

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

I found the game library Allegro easy to use back in the day. Might be worth a look.

Select something that has more/less than x character

If your experiencing the same problem while querying a DB2 database, you'll need to use the below query.

SELECT * 
FROM OPENQUERY(LINK_DB,'SELECT
CITY,
cast(STATE as varchar(40)) 
FROM DATABASE')

Where does git config --global get written to?

I was also looking for the global .gitconfig on my Windows machine and found this neat trick using git.

Do a: git config --global -e and then, if you are lucky, you will get a text editor loaded with your global .gitconfig file. Simply lookup the folder from there (or try a save as...), et voilà! :-)

How do you find the first key in a dictionary?

The dict type is an unordered mapping, so there is no such thing as a "first" element.

What you want is probably collections.OrderedDict.

How to remove backslash on json_encode() function?

the solution that does work is this:

$str = preg_replace('/\\\"/',"\"", $str);

However you have to be extremely careful here because you need to make sure that all your values have their quotes escaped (which is generally true anyway, but especially so now that you will be stripping all the escapes from PHP's idiotic (and dysfunctional) "helper" functionality of adding unnecessary backslashes in front of all your object ids and values).

So, php, by default, double escapes your values that have a quote in them, so if you have a value of My name is "Joe" in your DB, php will bring this back as My name is \\"Joe\\".

This may or may not be useful to you. If it's not you can then take the extra step of replacing the leading slash there like this:

$str = preg_replace('/\\\\\"/',"\"", $str);

yeah... it's ugly... but it works.

You're then left with something that vaguely resembles actual JSON.

How can I make the computer beep in C#?

It is confirmed that Windows 7 and newer versions (at least 64bit or both) do not use system speaker and instead they route the call to the default sound device.

So, using system.beep() in win7/8/10 will not produce sound using internal system speaker. Instead, you'll get a beep sound from external speakers if they are available.

Can two or more people edit an Excel document at the same time?

No, sadly:

The Excel 2010 client application does not support co-authoring workbooks in SharePoint Server 2010. However, the Excel client application does support non-real-time co-authoring workbooks stored locally or on network (UNC) paths by using the Shared Workbook feature. Co-authoring workbooks in SharePoint is supported by using the Microsoft Excel Web App, included with Office Web Apps

From Co-authoring overview (SharePoint Server 2010)

...and not for SharePoint 2013 either. Though it works for pretty much all other Office documents. Go figure.

PHP - count specific array values

You can do this with array_keys and count.

$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));

Output:

3

Stopping an Android app from console

pkill NAMEofAPP

Non rooted marshmallow, termux & terminal emulator.

What is the difference between Cygwin and MinGW?

Cygwin uses a DLL, cygwin.dll, (or maybe a set of DLLs) to provide a POSIX-like runtime on Windows.

MinGW compiles to a native Win32 application.

If you build something with Cygwin, any system you install it to will also need the Cygwin DLL(s). A MinGW application does not need any special runtime.

How can I pass parameters to a partial view in mvc 4

One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.

In your Partial calling side

@Html.Partial("ParitalAction", "String data to pass to partial")

And then binding the model with Partial View like this

@model string

and the using its value in Partial View like this

@Model

You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.

Hope it helps,

Convert object string to JSON

Maybe you have to try this:

str = jQuery.parseJSON(str)

Difference between \w and \b regular expression meta characters

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Simply put: \b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".

In all flavors, the characters [a-zA-Z0-9_] are word characters. These are also matched by the short-hand character class \w. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.

\w stands for "word character", usually [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

\W is short for [^\w], the negated version of \w.

Is there a jQuery unfocus method?

Based on your question, I believe the answer is how to trigger a blur, not just (or even) set the event:

 $('#textArea').trigger('blur');

What is the 'open' keyword in Swift?

Open is an access level, was introduced to impose limitations on class inheritance on Swift.

This means that the open access level can only be applied to classes and class members.

In Classes

An open class can be subclassed in the module it is defined in and in modules that import the module in which the class is defined.

In Class members

The same applies to class members. An open method can be overridden by subclasses in the module it is defined in and in modules that import the module in which the method is defined.

THE NEED FOR THIS UPDATE

Some classes of libraries and frameworks are not designed to be subclassed and doing so may result in unexpected behavior. Native Apple library also won't allow overriding the same methods and classes,

So after this addition they will apply public and private access levels accordingly.

For more details have look at Apple Documentation on Access Control

Adding line break in C# Code behind page

C# doesn't have an explicit line break character. You statements end with a semicolon so you can span your statements over many lines. These are both the same:

public string GenerateString()
{
    return "abc" + "def";
}

public string GenerateString()
{
    return
        "abc" +
        "def";
}

Filter Pyspark dataframe column with None value

isNull()/isNotNull() will return the respective rows which have dt_mvmt as Null or !Null.

method_1 = df.filter(df['dt_mvmt'].isNotNull()).count()
method_2 = df.filter(df.dt_mvmt.isNotNull()).count()

Both will return the same result

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Download it from here:

http://www.iis.net/downloads/microsoft/url-rewrite

or if you already have Web Platform Installer on your machine you can install it from there.

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

Make the class serializable by implementing the interface java.io.Serializable.

  • java.io.Serializable - Marker Interface which does not have any methods in it.
  • Purpose of Marker Interface - to tell the ObjectOutputStream that this object is a serializable object.

How do I increase the RAM and set up host-only networking in Vagrant?

You can easily increase your VM's RAM by modifying the memory property of config.vm.provider section in your vagrant file.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "4096"
end

This allocates about 4GB of RAM to your VM. You can change this according to your requirement. For example, following setting would allocate 2GB of RAM to your VM.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "2048"
end

Try removing the config.vm.customize ["modifyvm", :id, "--memory", 1024] in your file, and adding the above code.

For the network configuration, try modifying the config.vm.network :hostonly, "199.188.44.20" in your file toconfig.vm.network "private_network", ip: "199.188.44.20"

How do you manually execute SQL commands in Ruby On Rails using NuoDB

The working command I'm using to execute custom SQL statements is:

results = ActiveRecord::Base.connection.execute("foo")

with "foo" being the sql statement( i.e. "SELECT * FROM table").

This command will return a set of values as a hash and put them into the results variable.

So on my rails application_controller.rb I added this:

def execute_statement(sql)
  results = ActiveRecord::Base.connection.execute(sql)

  if results.present?
    return results
  else
    return nil
  end
end

Using execute_statement will return the records found and if there is none, it will return nil.

This way I can just call it anywhere on the rails application like for example:

records = execute_statement("select * from table")

"execute_statement" can also call NuoDB procedures, functions, and also Database Views.

Looking for a short & simple example of getters/setters in C#

This is a basic example of an object "Article" with getters and setters:

  public class Article
    {

        public String title;
        public String link;
        public String description;

        public string getTitle()
        {
            return title;
        }

        public void setTitle(string value)
        {
            title = value;
        }

        public string getLink()
        {
            return link;
        }

        public void setLink(string value)
        {
            link = value;
        }
        public string getDescription()
        {
            return description;
        }

        public void setDescription(string value)
        {
            description = value;
        }
    }

Class constructor type in typescript?

Solution from typescript interfaces reference:

interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
    tick();
}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
    return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("beep beep");
    }
}
class AnalogClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("tick tock");
    }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

So the previous example becomes:

interface AnimalConstructor {
    new (): Animal;
}

class Animal {
    constructor() {
        console.log("Animal");
    }
}

class Penguin extends Animal {
    constructor() {
        super();
        console.log("Penguin");
    }
}

class Lion extends Animal {
    constructor() {
        super();
        console.log("Lion");
    }
}

class Zoo {
    AnimalClass: AnimalConstructor // AnimalClass can be 'Lion' or 'Penguin'

    constructor(AnimalClass: AnimalConstructor) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

Why Anaconda does not recognize conda command?

Try restarting the terminal, I had the same issue, worked after restarting the terminal.

Connecting to TCP Socket from browser using javascript

This will be possible via the navigator interface as shown below:

navigator.tcpPermission.requestPermission({remoteAddress:"127.0.0.1", remotePort:6789}).then(
  () => {
    // Permission was granted
    // Create a new TCP client socket and connect to remote host
    var mySocket = new TCPSocket("127.0.0.1", 6789);

    // Send data to server
    mySocket.writeable.write("Hello World").then(
        () => {

            // Data sent sucessfully, wait for response
            console.log("Data has been sent to server");
            mySocket.readable.getReader().read().then(
                ({ value, done }) => {
                    if (!done) {
                        // Response received, log it:
                        console.log("Data received from server:" + value);
                    }

                    // Close the TCP connection
                    mySocket.close();
                }
            );
        },
        e => console.error("Sending error: ", e)
    );
  }
);

More details are outlined in the w3.org tcp-udp-sockets documentation.

http://raw-sockets.sysapps.org/#interface-tcpsocket

https://www.w3.org/TR/tcp-udp-sockets/

Another alternative is to use Chrome Sockets

Creating connections

chrome.sockets.tcp.create({}, function(createInfo) {
  chrome.sockets.tcp.connect(createInfo.socketId,
    IP, PORT, onConnectedCallback);
});

Sending data

chrome.sockets.tcp.send(socketId, arrayBuffer, onSentCallback);

Receiving data

chrome.sockets.tcp.onReceive.addListener(function(info) {
  if (info.socketId != socketId)
    return;
  // info.data is an arrayBuffer.
});

You can use also attempt to use HTML5 Web Sockets (Although this is not direct TCP communication):

var connection = new WebSocket('ws://IPAddress:Port');

connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

http://www.html5rocks.com/en/tutorials/websockets/basics/

Your server must also be listening with a WebSocket server such as pywebsocket, alternatively you can write your own as outlined at Mozilla

JavaScript: function returning an object

Both styles, with a touch of tweaking, would work.

The first method uses a Javascript Constructor, which like most things has pros and cons.

 // By convention, constructors start with an upper case letter
function MakePerson(name,age) {
  // The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
  this.name = name;
  this.age = age;
  this.occupation = "Hobo";
}
var jeremy = new MakePerson("Jeremy", 800);

On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.

function makePerson(name2, age2) {
  var name = name2;
  var age = age2;

  return {
    name: name,
    age: age
  };
}

Is it a good practice to use try-except-else in Python?

Is it a good practice to use try-except-else in python?

The answer to this is that it is context dependent. If you do this:

d = dict()
try:
    item = d['item']
except KeyError:
    item = 'default'

It demonstrates that you don't know Python very well. This functionality is encapsulated in the dict.get method:

item = d.get('item', 'default')

The try/except block is a much more visually cluttered and verbose way of writing what can be efficiently executing in a single line with an atomic method. There are other cases where this is true.

However, that does not mean that we should avoid all exception handling. In some cases it is preferred to avoid race conditions. Don't check if a file exists, just attempt to open it, and catch the appropriate IOError. For the sake of simplicity and readability, try to encapsulate this or factor it out as apropos.

Read the Zen of Python, understanding that there are principles that are in tension, and be wary of dogma that relies too heavily on any one of the statements in it.

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

I had the same problem as the current .NET SDK does not support targeting .NET Core 3.1. Either target .NET Core 1.1 or lower, or use a version of the .NET SDK that supports .NET Core 3.1

1) Make sure .Net core SDK installed on your machine. Download .NET!

2) set PATH environment variables as below Path

Java Enum Methods - return opposite direction enum

Create an abstract method, and have each of your enumeration values override it. Since you know the opposite while you're creating it, there's no need to dynamically generate or create it.

It doesn't read nicely though; perhaps a switch would be more manageable?

public enum Direction {
    NORTH(1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.SOUTH;
        }
    },
    SOUTH(-1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.NORTH;
        }
    },
    EAST(-2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.WEST;
        }
    },
    WEST(2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.EAST;
        }
    };

    Direction(int code){
        this.code=code;
    }
    protected int code;

    public int getCode() {
        return this.code;
    }

    public abstract Direction getOppositeDirection();
}

Most concise way to convert a Set<T> to a List<T>

Try this for Set:

Set<String> listOfTopicAuthors = .....
List<String> setList = new ArrayList<String>(listOfTopicAuthors); 

Try this for Map:

Map<String, String> listOfTopicAuthors = .....
// List of values:
List<String> mapValueList = new ArrayList<String>(listOfTopicAuthors.values());
// List of keys:
List<String> mapKeyList = new ArrayList<String>(listOfTopicAuthors.KeySet());

SMTP connect() failed PHPmailer - PHP

<?php

use PHPMailer\PHPMailer\PHPMailer;

require_once "PHPMailer/src/Exception.php";
require_once "PHPMailer/src/PHPMailer.php";
require_once "PHPMailer/src/SMTP.php";



$mail = new PHPMailer();

$mail ->isSMTP();
$mail ->Host ="smtp.gmail.com";
$mail -> SMTPAuth = true;
$mail ->Username = '[email protected]';
$mail ->Password = 'password';
//$mail ->SMTPSecure=PHPMailer::ENCRYPTION_STARTTLS;
$mail ->Port = '587';
$mail ->SMTPSecure ='tls';
$mail ->isHTML(true);

$mail ->setFrom('[email protected]','email send name');

$mail ->addAddress('[email protected]');
$mail ->Subject = 'HelloWorld';
$mail ->Body = 'a test email';


$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);



if ($mail->send()){
    echo "Message has been sent successfully";
}else{
    echo "Mailer Error: " . $mail->ErrorInfo;
}

?>

make sure that you configure less secure app settings in gmail using this link https://www.google.com/settings/security/lesssecureapps and make sure you downloaded PHPMailer-master.zip from github

working fine with MAMP server locally :)

Setting the default active profile in Spring-boot

If you're using maven I would do something like this:

Being production your default profile:

<properties>
    <activeProfile>production</activeProfile>
</properties>

And as an example of other profiles:

<profiles>
    <!--Your default profile... selected if none specified-->
    <profile>
        <id>production</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <activeProfile>production</activeProfile>
        </properties>
    </profile>

    <!--Profile 2-->
    <profile>
        <id>development</id>
        <properties>
            <activeProfile>development</activeProfile>
        </properties>
    </profile>

    <!--Profile 3-->
    <profile>
        <id>otherprofile</id>
        <properties>
            <activeProfile>otherprofile</activeProfile>
        </properties>
    </profile>
<profiles>

In your application.properties you'll have to set:

spring.profiles.active=@activeProfile@

This works for me every time, hope it solves your problem.

How to copy a java.util.List into another java.util.List

re: indexOutOfBoundsException, your sublist args are the problem; you need to end the sublist at size-1. Being zero-based, the last element of a list is always size-1, there is no element in the size position, hence the error.

Can I nest a <button> element inside an <a> using HTML5?

No.

The following solution relies on JavaScript.

<button type="button" onclick="location.href='http://www.stackoverflow.com'">ABC</button>

If the button is to be placed inside an existing <form> with method="post", then ensure the button has the attribute type="button" otherwise the button will submit the POST operation. In this way you can have a <form> that contains a mixture of GET and POST operation buttons.

What exactly is Apache Camel?

A diagram is better than thousands of description. This Diagram illustrates the architecture of Camel.

enter image description here

How does the ARM architecture differ from x86?

Neither has anything specific to keyboard or mobile, other than the fact that for years ARM has had a pretty substantial advantage in terms of power consumption, which made it attractive for all sorts of battery operated devices.

As far as the actual differences: ARM has more registers, supported predication for most instructions long before Intel added it, and has long incorporated all sorts of techniques (call them "tricks", if you prefer) to save power almost everywhere it could.

There's also a considerable difference in how the two encode instructions. Intel uses a fairly complex variable-length encoding in which an instruction can occupy anywhere from 1 up to 15 byte. This allows programs to be quite small, but makes instruction decoding relatively difficult (as in: decoding instructions fast in parallel is more like a complete nightmare).

ARM has two different instruction encoding modes: ARM and THUMB. In ARM mode, you get access to all instructions, and the encoding is extremely simple and fast to decode. Unfortunately, ARM mode code tends to be fairly large, so it's fairly common for a program to occupy around twice as much memory as Intel code would. Thumb mode attempts to mitigate that. It still uses quite a regular instruction encoding, but reduces most instructions from 32 bits to 16 bits, such as by reducing the number of registers, eliminating predication from most instructions, and reducing the range of branches. At least in my experience, this still doesn't usually give quite as dense of coding as x86 code can get, but it's fairly close, and decoding is still fairly simple and straightforward. Lower code density means you generally need at least a little more memory and (generally more seriously) a larger cache to get equivalent performance.

At one time Intel put a lot more emphasis on speed than power consumption. They started emphasizing power consumption primarily on the context of laptops. For laptops their typical power goal was on the order of 6 watts for a fairly small laptop. More recently (much more recently) they've started to target mobile devices (phones, tablets, etc.) For this market, they're looking at a couple of watts or so at most. They seem to be doing pretty well at that, though their approach has been substantially different from ARM's, emphasizing fabrication technology where ARM has mostly emphasized micro-architecture (not surprising, considering that ARM sells designs, and leaves fabrication to others).

Depending on the situation, a CPU's energy consumption is often more important than its power consumption though. At least as I'm using the terms, power consumption refers to power usage on a (more or less) instantaneous basis. Energy consumption, however, normalizes for speed, so if (for example) CPU A consumes 1 watt for 2 seconds to do a job, and CPU B consumes 2 watts for 1 second to do the same job, both CPUs consume the same total amount of energy (two watt seconds) to do that job--but with CPU B, you get results twice as fast.

ARM processors tend to do very well in terms of power consumption. So if you need something that needs a processor's "presence" almost constantly, but isn't really doing much work, they can work out pretty well. For example, if you're doing video conferencing, you gather a few milliseconds of data, compress it, send it, receive data from others, decompress it, play it back, and repeat. Even a really fast processor can't spend much time sleeping, so for tasks like this, ARM does really well.

Intel's processors (especially their Atom processors, which are actually intended for low power applications) are extremely competitive in terms of energy consumption. While they're running close to their full speed, they will consume more power than most ARM processors--but they also finish work quickly, so they can go back to sleep sooner. As a result, they can combine good battery life with good performance.

So, when comparing the two, you have to be careful about what you measure, to be sure that it reflects what you honestly care about. ARM does very well at power consumption, but depending on the situation you may easily care more about energy consumption than instantaneous power consumption.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)

Programmatically go back to previous ViewController in Swift

In the case where you presented a UIViewController from within a UIViewController i.e...

// Main View Controller
self.present(otherViewController, animated: true)

Simply call the dismiss function:

// Other View Controller
self.dismiss(animated: true)

Count work days between two dates

Using a date table:

    DECLARE 
        @StartDate date = '2014-01-01',
        @EndDate date = '2014-01-31'; 
    SELECT 
        COUNT(*) As NumberOfWeekDays
    FROM dbo.Calendar
    WHERE CalendarDate BETWEEN @StartDate AND @EndDate
      AND IsWorkDay = 1;

If you don't have that, you can use a numbers table:

    DECLARE 
    @StartDate datetime = '2014-01-01',
    @EndDate datetime = '2014-01-31'; 
    SELECT 
    SUM(CASE WHEN DATEPART(dw, DATEADD(dd, Number-1, @StartDate)) BETWEEN 2 AND 6 THEN 1 ELSE 0 END) As NumberOfWeekDays
    FROM dbo.Numbers
    WHERE Number <= DATEDIFF(dd, @StartDate, @EndDate) + 1 -- Number table starts at 1, we want a 0 base

They should both be fast and it takes out the ambiguity/complexity. The first option is the best but if you don't have a calendar table you can allways create a numbers table with a CTE.

Simple PHP calculator

You need to get the values the same way to get the calculator operation which looks like:

<?php
if($_POST['group1'] == add) {
echo "$_POST['first']+ $_POST['second'];
}
... and so on
?>

Or, to make it easier, just do:

    <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Answer</title>
</head>
<body>
<p>The answer is: 
<?php
$first = $_POST['first'];
$second= $_POST['second'];

if($_POST['group1'] == add) {
echo "$first + $second";
}
else if($_POST['group1'] == subtract) {
echo "$first - $second";
}
else if($_POST['group1'] == times) {
echo "$first * $second";
}
else($_POST['group1'] == divide) {
echo "$first / $second";
}
?>
</p> 
</body>
</html>

How to create global variables accessible in all views using Express / Node.JS?

For Express 4.0 I found that using application level variables works a little differently & Cory's answer did not work for me.

From the docs: http://expressjs.com/en/api.html#app.locals

I found that you could declare a global variable for the app in

app.locals

e.g

app.locals.baseUrl = "http://www.google.com"

And then in your application you can access these variables & in your express middleware you can access them in the req object as

req.app.locals.baseUrl

e.g.

console.log(req.app.locals.baseUrl)
//prints out http://www.google.com

How can I pass some data from one controller to another peer controller

You need to use

 $rootScope.$broadcast()

in the controller that must send datas. And in the one that receive those datas, you use

 $scope.$on

Here is a fiddle that i forked a few time ago (I don't know who did it first anymore

http://jsfiddle.net/patxy/RAVFM/

IIS: Idle Timeout vs Recycle

IIS now has

Idle Time-out Action : Suspend setting

Suspending is just freezes the process and it is much more efficient than the destroying the process.

Overlay with spinner

Here is simple overlay div without using any gif, This can be applied over another div.

<style>
.loader {
  position: relative;
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 70px;
  height: 70px;
  left:50%;
  top:50%;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
}
#overlay{
    position: absolute;
    top:0px;
    left:0px;
    width: 100%;
    height: 100%;
    background: black;
    opacity: .5;
}
.container{
    position:relative;
    height: 300px;
    width: 200px;
    border:1px solid
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

<h2>How To Create A Loader</h2>

<div class="container">
  <h3>Overlay over this div</h3>
  <div id="overlay">
      <div class="loader"></div>
  </div>
<div>

How to check if a number is a power of 2

In C, I tested the i && !(i & (i - 1) trick and compared it with __builtin_popcount(i), using gcc on Linux, with the -mpopcnt flag to be sure to use the CPU's POPCNT instruction. My test program counted the # of integers between 0 and 2^31 that were a power of two.

At first I thought that i && !(i & (i - 1) was 10% faster, even though I verified that POPCNT was used in the disassembly where I used__builtin_popcount.

However, I realized that I had included an if statement, and branch prediction was probably doing better on the bit twiddling version. I removed the if and POPCNT ended up faster, as expected.

Results:

Intel(R) Core(TM) i7-4771 CPU max 3.90GHz

Timing (i & !(i & (i - 1))) trick
30

real    0m13.804s
user    0m13.799s
sys     0m0.000s

Timing POPCNT
30

real    0m11.916s
user    0m11.916s
sys     0m0.000s

AMD Ryzen Threadripper 2950X 16-Core Processor max 3.50GHz

Timing (i && !(i & (i - 1))) trick
30

real    0m13.675s
user    0m13.673s
sys 0m0.000s

Timing POPCNT
30

real    0m13.156s
user    0m13.153s
sys 0m0.000s

Note that here the Intel CPU seems slightly slower than AMD with the bit twiddling, but has a much faster POPCNT; the AMD POPCNT doesn't provide as much of a boost.

popcnt_test.c:

#include "stdio.h"

// Count # of integers that are powers of 2 up to 2^31;
int main() {
  int n;
  for (int z = 0; z < 20; z++){
      n = 0;
      for (unsigned long i = 0; i < 1<<30; i++) {
       #ifdef USE_POPCNT
        n += (__builtin_popcount(i)==1); // Was: if (__builtin_popcount(i) == 1) n++;
       #else
        n += (i && !(i & (i - 1)));  // Was: if (i && !(i & (i - 1))) n++;
       #endif
      }
  }

  printf("%d\n", n);
  return 0;
}

Run tests:

gcc popcnt_test.c -O3 -o test.exe
gcc popcnt_test.c -O3 -DUSE_POPCNT -mpopcnt -o test-popcnt.exe

echo "Timing (i && !(i & (i - 1))) trick"
time ./test.exe

echo
echo "Timing POPCNT"
time ./test-opt.exe

How to pass an ArrayList to a varargs method parameter?

Source article: Passing a list as an argument to a vararg method


Use the toArray(T[] arr) method.

.getMap(locations.toArray(new WorldLocation[locations.size()]))

(toArray(new WorldLocation[0]) also works, but you would allocate a zero-length array for no reason.)


Here's a complete example:

public static void method(String... strs) {
    for (String s : strs)
        System.out.println(s);
}

...
    List<String> strs = new ArrayList<String>();
    strs.add("hello");
    strs.add("world");
    
    method(strs.toArray(new String[strs.size()]));
    //     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...

Twitter bootstrap float div right

<p class="pull-left">Text left</p>
<p class="text-right">Text right in same line</p>

This work for me.

edit: An example with your snippet:

_x000D_
_x000D_
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.css');_x000D_
 .container {_x000D_
    margin-top: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
    <div class="row-fluid">_x000D_
        <div class="span6 pull-left">_x000D_
            <p>Text left</p>_x000D_
        </div>_x000D_
        <div class="span6 text-right">_x000D_
            <p>text right</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to obtain the last path segment of a URI

In Java 7+ a few of the previous answers can be combined to allow retrieval of any path segment from a URI, rather than just the last segment. We can convert the URI to a java.nio.file.Path object, to take advantage of its getName(int) method.

Unfortunately, the static factory Paths.get(uri) is not built to handle the http scheme, so we first need to separate the scheme from the URI's path.

URI uri = URI.create("http://base_path/some_segment/id");
Path path = Paths.get(uri.getPath());
String last = path.getFileName().toString();
String secondToLast = path.getName(path.getNameCount() - 2).toString();

To get the last segment in one line of code, simply nest the lines above.

Paths.get(URI.create("http://base_path/some_segment/id").getPath()).getFileName().toString()

To get the second-to-last segment while avoiding index numbers and the potential for off-by-one errors, use the getParent() method.

String secondToLast = path.getParent().getFileName().toString();

Note the getParent() method can be called repeatedly to retrieve segments in reverse order. In this example, the path only contains two segments, otherwise calling getParent().getParent() would retrieve the third-to-last segment.

How to get last 7 days data from current datetime to last 7 days in sql server

I don't think you have data for every single day for the past seven days. Days for which no data exist, will obviously not show up.

Try this and validate that you have data for EACH day for the past 7 days

SELECT DISTINCT CreatedDate
FROM News 
WHERE CreatedDate >= DATEADD(day,-7, GETDATE())
ORDER BY CreatedDate

EDIT - Copied from your comment

i have dec 19th -1 row data,18th -2 rows,17th -3 rows,16th -3 rows,15th -3 rows,12th -2 rows, 11th -4 rows,9th -1 row,8th -1 row

You don't have data for all days. That is your problem and not the query. If you execute the query today - 22nd - you will only get data for 19th, 18th,17th,16th and 15th. You have no data for 20th, 21st and 22nd.

EDIT - To get data for the last 7 days, where data is available you can try

select id,    
NewsHeadline as news_headline,    
NewsText as news_text,    
state,    
CreatedDate as created_on      
from News    
WHERE CreatedDate IN (SELECT DISTINCT TOP 7 CreatedDate from News
order by createddate DESC)

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

The error does not say much and lot of things can be wrong. One thing that was wrong in my case was following

-x.DargName=108352123

Which is clearly wrong and should have been

-Dx.argName=108352123

Using an HTML button to call a JavaScript function

SIMPLE ANSWER:

   onclick="functionName(ID.value);

Where ID is the ID of the input field.

How to set an iframe src attribute from a variable in AngularJS

select template; iframe controller, ng model update

index.html

angularapp.controller('FieldCtrl', function ($scope, $sce) {
        var iframeclass = '';
        $scope.loadTemplate = function() {
            if ($scope.template.length > 0) {
                // add iframe classs
                iframeclass = $scope.template.split('.')[0];
                iframe.classList.add(iframeclass);
                $scope.activeTemplate = $sce.trustAsResourceUrl($scope.template);
            } else {
                iframe.classList.remove(iframeclass);
            };
        };

    });
    // custom directive
    angularapp.directive('myChange', function() {
        return function(scope, element) {
            element.bind('input', function() {
                // the iframe function
                iframe.contentWindow.update({
                    name: element[0].name,
                    value: element[0].value
                });
            });
        };
    });

iframe.html

   window.update = function(data) {
        $scope.$apply(function() {
            $scope[data.name] = (data.value.length > 0) ? data.value: defaults[data.name];
        });
    };

Check this link: http://plnkr.co/edit/TGRj2o?p=preview

Input type "number" won't resize

Incorrect usage.

Input type number it's made to have selectable value via arrows up and down.

So basically you are looking for "width" CSS style.

Input text historically is formatted with monospaced font, so size it's also the width it takes.

Input number it's new and "size" property has no sense at all*. A typical usage:

<input type="number" name="quantity" min="1" max="5">

w3c docs

to fix, add a style:

<input type="number" name="email" style="width: 7em">

EDIT: if you want a range, you have to set type="range" and not ="number"

EDIT2: *size is not an allowed value (so, no sense). Check out official W3C specifications

Note: The size attribute works with the following input types: text, search, tel, url, email, and password.

Tip: To specify the maximum number of characters allowed in the element, use the maxlength attribute.

Docker error : no space left on device

Seems like there are a few ways this can occur. The issue I had was that the docker disk image had hit its maximum size (Docker Whale -> Preferences -> Disk if you want to view what size that is in OSX).

I upped the limit and and was good to go. I'm sure cleaning up unused images would work as well.

Change icon on click (toggle)

Here is a very easy way of doing that

 $(function () {
    $(".glyphicon").unbind('click');
    $(".glyphicon").click(function (e) {
        $(this).toggleClass("glyphicon glyphicon-chevron-up glyphicon glyphicon-chevron-down");
});

Hope this helps :D

Is it possible to set UIView border properties from interface builder?

You can make a category of UIView and add this in .h file of category

@property (nonatomic) IBInspectable UIColor *borderColor;
@property (nonatomic) IBInspectable CGFloat borderWidth;
@property (nonatomic) IBInspectable CGFloat cornerRadius;

Now add this in .m file

@dynamic borderColor,borderWidth,cornerRadius;

and this as well in . m file

-(void)setBorderColor:(UIColor *)borderColor{
    [self.layer setBorderColor:borderColor.CGColor];
}

-(void)setBorderWidth:(CGFloat)borderWidth{
    [self.layer setBorderWidth:borderWidth];
}

-(void)setCornerRadius:(CGFloat)cornerRadius{
    [self.layer setCornerRadius:cornerRadius];
}

now you will see this in your storyboard for all UIView subclasses (UILabel, UITextField, UIImageView etc)

enter image description here

Thats it.. No Need to import category anywhere, just add the category's files in the project and see these properties in the storyboard.

What is a plain English explanation of "Big O" notation?

Big O notation is a way of describing how quickly an algorithm will run given an arbitrary number of input parameters, which we'll call "n". It is useful in computer science because different machines operate at different speeds, and simply saying that an algorithm takes 5 seconds doesn't tell you much because while you may be running a system with a 4.5 Ghz octo-core processor, I may be running a 15 year old, 800 Mhz system, which could take longer regardless of the algorithm. So instead of specifying how fast an algorithm runs in terms of time, we say how fast it runs in terms of number of input parameters, or "n". By describing algorithms in this way, we are able to compare the speeds of algorithms without having to take into account the speed of the computer itself.

Best Regular Expression for Email Validation in C#

Email Validation Regex

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+.)+[a-z]{2,5}$

Or

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+[.])+[a-z]{2,5}$

Demo Link:

https://regex101.com/r/kN4nJ0/53

Does Hibernate create tables in the database automatically

yes you can use

<property name="hbm2ddl.auto" value="create"/>

What are static factory methods?

Readability can be improved by static factory methods:

Compare

public class Foo{
  public Foo(boolean withBar){
    //...
  }
}

//...

// What exactly does this mean?
Foo foo = new Foo(true);
// You have to lookup the documentation to be sure.
// Even if you remember that the boolean has something to do with a Bar
// you might not remember whether it specified withBar or withoutBar.

to

public class Foo{
  public static Foo createWithBar(){
    //...
  }

  public static Foo createWithoutBar(){
    //...
  }
}

// ...

// This is much easier to read!
Foo foo = Foo.createWithBar();

Fitting a density curve to a histogram in R

I had the same problem but Dirk's solution didn't seem to work. I was getting this warning messege every time

"prob" is not a graphical parameter

I read through ?hist and found about freq: a logical vector set TRUE by default.

the code that worked for me is

hist(x,freq=FALSE)
lines(density(x),na.rm=TRUE)

How can I INSERT data into two tables simultaneously in SQL Server?

You could write a stored procedure that iterates over the transaction that you have proposed. The iterator would be the cursor for the table that contains the source data.

How to format a DateTime in PowerShell

Do this if you absolutely need to use the -Format option:

$dateStr = Get-Date $date -Format "yyyMMdd"

However

$dateStr = $date.toString('yyyMMdd')

is probably more efficient.. :)

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

Most frequently it is:

in cmd.exe write

python -m pip install --user [name of your module here without brackets]

How to run Python script on terminal?

You need python installed on your system. Then you can run this in the terminal in the correct directory:

python gameover.py

Disable time in bootstrap date time picker

I know this is late, but the answer is simply removing "time" from the word, datetimepicker to change it to datepicker. You can format it with dateFormat.

      jQuery( "#datetimepicker4" ).datepicker({
        dateFormat: "MM dd, yy",
      });

How to set a background image in Xcode using swift?

SWIFT 4

view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage

basic authorization command for curl

How do I set up the basic authorization?

All you need to do is use -u, --user USER[:PASSWORD]. Behind the scenes curl builds the Authorization header with base64 encoded credentials for you.

Example:

curl -u username:password -i -H 'Accept:application/json' http://example.com

How to get the insert ID in JDBC?

  1. Create Generated Column

    String generatedColumns[] = { "ID" };
    
  2. Pass this geneated Column to your statement

    PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
    
  3. Use ResultSet object to fetch the GeneratedKeys on Statement

    ResultSet rs = stmtInsert.getGeneratedKeys();
    
    if (rs.next()) {
        long id = rs.getLong(1);
        System.out.println("Inserted ID -" + id); // display inserted record
    }
    

How to implement class constructor in Visual Basic?

Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.

Instance constructor:

Public Sub New()

End Sub

Shared constructor:

Shared Sub New()

End Sub

How do I check if a PowerShell module is installed?

Just revisiting this as it's something I just faced and there is some incorrect stuff in the answers (though it's mentioned in the comments).

First thing though. The original questions asks how to tell if a PowerShell module is installed. We need to talk about the word installed! You don't install PowerShell modules (not in the traditional way you install software anyway).

PowerShell modules are either available (i.e. they are on the PowerShell module path), or they are imported (they are imported into your session and you can call the functions contained). This is how to check your module path, in case you want to know where to store a module:

$env:psmodulepath

I'd argue that it's becoming common to use C:\Program Files\WindowsPowerShell\Modules; more often due to it being available to all users, but if you want to lock down your modules to your own session, include them in your profile. C:\Users\%username%\Documents\WindowsPowerShell\Modules;

Alright, back to the two states.

Is the module available (using available to mean installed in the original question)?

Get-Module -Listavailable -Name <modulename>

This tells you if a module is available for import.

Is the module imported? (I'm using this as the answer for the word 'exists' in the original question).

Get-module -Name <modulename>

This will either return an empty load of nothing if the module is not imported, or a one line description of the module if it is. As ever on Stack Overflow, try the commands above on your own modules.

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

To answer your question, Hibernate is an implementation of the JPA standard. Hibernate has its own quirks of operation, but as per the Hibernate docs

By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.

So Hibernate will always load any object using a lazy fetching strategy, no matter what type of relationship you have declared. It will use a lazy proxy (which should be uninitialized but not null) for a single object in a one-to-one or many-to-one relationship, and a null collection that it will hydrate with values when you attempt to access it.

It should be understood that Hibernate will only attempt to fill these objects with values when you attempt to access the object, unless you specify fetchType.EAGER.

JavaScript code to stop form submission

Lots of hard ways to do an easy thing:

<form name="foo" onsubmit="return false">

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

What are the special dollar sign shell variables?

Take care with some of the examples; $0 may include some leading path as well as the name of the program. Eg save this two line script as ./mytry.sh and the execute it.

#!/bin/bash

echo "parameter 0 --> $0" ; exit 0

Output:

parameter 0 --> ./mytry.sh

This is on a current (year 2016) version of Bash, via Slackware 14.2

Export HTML table to pdf using jspdf

We can separate out section of which we need to convert in PDF

For example, if table is in class "pdf-table-wrap"

After this, we need to call html2canvas function combined with jsPDF

following is sample code

var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
    onrendered: function(canvas) {
        document.body.appendChild(canvas);
        var ctx = canvas.getContext('2d');
        var imgData = canvas.toDataURL("image/png", 1.0);
        var width = canvas.width;
        var height = canvas.clientHeight;
        pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));

    }
});
setTimeout(function() {
    //jsPDF code to save file
    pdf.save('sample.pdf');
}, 0);

Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/

What are good grep tools for Windows?

GREP for Windows

I've been using it forever and luckily it's still available. It's super fast and very small.

How to initialize a nested struct?

Define your Proxy struct separately, outside of Configuration, like this:

type Proxy struct {
    Address string
    Port    string
}

type Configuration struct {
    Val string
    P   Proxy
}

c := &Configuration{
    Val: "test",
    P: Proxy{
        Address: "addr",
        Port:    "80",
    },
}

See http://play.golang.org/p/7PELCVsQIc

Finding all objects that have a given property inside a collection

I have been using Google Collections (now called Guava) for this kind of problem. There is a class called Iterables that can take an interface called Predicate as a parameter of a method that is really helpful.

Cat theOne = Iterables.find(cats, new Predicate<Cat>() {
    public boolean apply(Cat arg) { return arg.age() == 3; }
});

Check it here!

JQuery .each() backwards

If you don't want to save method into jQuery.fn you can use

[].reverse.call($('li'));

Removing elements with Array.map in JavaScript

TLDR: Use map (returning undefined when needed) and then filter.


First, I believe that a map + filter function is useful since you don't want to repeat a computation in both. Swift originally called this function flatMap but then renamed it to compactMap.

For example, if we don't have a compactMap function, we might end up with computation defined twice:

  let array = [1, 2, 3, 4, 5, 6, 7, 8];
  let mapped = array
  .filter(x => {
    let computation = x / 2 + 1;
    let isIncluded = computation % 2 === 0;
    return isIncluded;
  })
  .map(x => {
    let computation = x / 2 + 1;
    return `${x} is included because ${computation} is even`
  })

  // Output: [2 is included because 2 is even, 6 is included because 4 is even]

Thus compactMap would be useful to reduce duplicate code.

A really simple way to do something similar to compactMap is to:

  1. Map on real values or undefined.
  2. Filter out all the undefined values.

This of course relies on you never needing to return undefined values as part of your original map function.

Example:

  let array = [1, 2, 3, 4, 5, 6, 7, 8];
  let mapped = array
  .map(x => {
    let computation = x / 2 + 1;
    let isIncluded = computation % 2 === 0;
    if (isIncluded) {
      return `${x} is included because ${computation} is even`
    } else {
      return undefined
    }
  })
  .filter(x => typeof x !== "undefined")

addEventListener, "change" and option selection

The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.

function start(){
      document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
      }

function addActivityItem(){
      //option is selected
      alert("yeah");
}

window.addEventListener("load", start, false);

How to coerce a list object to type 'double'

If you want to convert all elements of a to a single numeric vector and length(a) is greater than 1 (OK, even if it is of length 1), you could unlist the object first and then convert.

as.numeric(unlist(a))
# [1]  10  38  66 101 129 185 283 374

Bear in mind that there aren't any quality controls here. Also, X$Days a mighty odd name.

stdcall and cdecl

It's specified in the function type. When you have a function pointer, it's assumed to be cdecl if not explicitly stdcall. This means that if you get a stdcall pointer and a cdecl pointer, you can't exchange them. The two function types can call each other without issues, it's just getting one type when you expect the other. As for speed, they both perform the same roles, just in a very slightly different place, it's really irrelevant.

How to fix "ImportError: No module named ..." error in Python?

Example solution for adding the library to your PYTHONPATH.

  1. Add the following line into your ~/.bashrc or just run it directly:

    export PYTHONPATH="$PYTHONPATH:$HOME/.python"
    
  2. Then link your required library into your ~/.python folder, e.g.

    ln -s /home/user/work/project/foo ~/.python/
    

Using GregorianCalendar with SimpleDateFormat

Why such complications?

public static GregorianCalendar convertFromDMY(String dd_mm_yy) throws ParseException 
{
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = fmt.parse(dd_mm_yy);
    GregorianCalendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    return cal;
}

How to get an input text value in JavaScript

<script>
function subadd(){
subadd= parseFloat(document.forms[0][0].value) + parseFloat(document.forms[0][1].value) 
window.alert(subadd)  
}
</script>

<body>
<form>
<input type="text" >+
<input type="text" >
<input type="button" value="add" onclick="subadd()">
</form>
</body>

How do you reset the stored credentials in 'git credential-osxkeychain'?

From Terminal: (You need to enter the following three lines)

 $ git credential-osxkeychain erase ?
 host=github.com  ?
 protocol=https   ?
 ?
 ?

NOTE: after you enter “protocol=https” above you need to press ~~RETURN~~ TWICE (Each '?' is equivalent to a 'press enter/return' )

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

Do not assume your unix_socket which would be different from one to another, try to find it.

First of all, get your unix_socket location.

$ mysql -u root -p

Enter your mysql password and login your mysql server from command line.

mysql> show variables like '%sock%';
+---------------+---------------------------------------+
| Variable_name | Value                                 |
+---------------+---------------------------------------+
| socket        | /opt/local/var/run/mysql5/mysqld.sock |
+---------------+---------------------------------------+

Your unix_soket could be diffrent.

Then change your php.ini, find your php.ini file from

<? phpinfo();

You maybe install many php with different version, so please don't assume your php.ini file location, get it from your 'phpinfo';

Change your php.ini:

mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock

mysqli.default_socket = /opt/local/var/run/mysql5/mysqld.sock

pdo_mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock

Then restart your apache or php-fpm.

How to implement linear interpolation?

def interpolate(x1: float, x2: float, y1: float, y2: float, x: float):
    """Perform linear interpolation for x between (x1,y1) and (x2,y2) """

    return ((y2 - y1) * x + x2 * y1 - x1 * y2) / (x2 - x1)

Mercurial undo last commit

hg rollback is what you want.

In TortoiseHg, the hg rollback is accomplished in the commit dialog. Open the commit dialog and select "Undo".

alt text

SQL: How do I SELECT only the rows with a unique value on certain column?

Sorry you're not using PostgreSQL...

SELECT DISTINCT ON contract, activity * FROM thetable ORDER BY contract, activity

http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT

Oh wait. You only want values with exactly one...

SELECT contract, activity, count() FROM thetable GROUP BY contract, activity HAVING count() = 1

How to get terminal's Character Encoding

To see the current locale information use locale command. Below is an example on RHEL 7.8

[usr@host ~]$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Angular2 Routing with Hashtag to page anchor

A little late but here's an answer I found that works:

<a [routerLink]="['/path']" fragment="test" (click)="onAnchorClick()">Anchor</a>

And in the component:

constructor( private route: ActivatedRoute, private router: Router ) {}

  onAnchorClick ( ) {
    this.route.fragment.subscribe ( f => {
      const element = document.querySelector ( "#" + f )
      if ( element ) element.scrollIntoView ( element )
    });
  }

The above doesn't automatically scroll to the view if you land on a page with an anchor already, so I used the solution above in my ngInit so that it could work with that as well:

ngOnInit() {
    this.router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = this.router.parseUrl(this.router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(element); }
        }
      }
    });
  }

Make sure to import Router, ActivatedRoute and NavigationEnd at the beginning of your component and it should be all good to go.

Source

HTML checkbox onclick called in Javascript

jQuery has a function that can do this:

  1. include the following script in your head:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
    

    (or just download the jQuery.js file online and include it locally)

  2. use this script to toggle the check box when the input is clicked:

    var toggle = false;
    $("#INPUTNAMEHERE").click(function() {
            $("input[type=checkbox]").attr("checked",!toggle);
            toggle = !toggle;
    }); 
    

That should do what you want if I understood what you were trying to do.

jQuery + client-side template = "Syntax error, unrecognized expression"

I had the same error:
"Syntax error, unrecognized expression: // "
It is known bug at JQuery, so i needed to think on workaround solution,
What I did is:
I changed "script" tag to "div"
and added at angular this code
and the error is gone...

app.run(['$templateCache', function($templateCache) {
    var url = "survey-input.html";
    content = angular.element(document.getElementById(url)).html()
    $templateCache.put(url, content);
}]);

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

The problem for me seems to have been how the user has been setup on my local machine to. Using the command
git push -u origin master
was causing the error. Removing the switch -u to have
git push origin master
solved it for me. It can be scary to imagine how user setup can result in an error related to LibreSSL.

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

How do I suspend painting for a control and its children?

Based on ng5000's answer, I like using this extension:

        #region Suspend
        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
        private const int WM_SETREDRAW = 11;
        public static IDisposable BeginSuspendlock(this Control ctrl)
        {
            return new suspender(ctrl);
        }
        private class suspender : IDisposable
        {
            private Control _ctrl;
            public suspender(Control ctrl)
            {
                this._ctrl = ctrl;
                SendMessage(this._ctrl.Handle, WM_SETREDRAW, false, 0);
            }
            public void Dispose()
            {
                SendMessage(this._ctrl.Handle, WM_SETREDRAW, true, 0);
                this._ctrl.Refresh();
            }
        }
        #endregion

Use:

using (this.BeginSuspendlock())
{
    //update GUI
}

Remove tracking branches no longer on remote

I came up with this bash script. It always keep the branches develop, qa, master.

git-clear() {
  git pull -a > /dev/null

  local branches=$(git branch --merged | grep -v 'develop' | grep -v 'master' | grep -v 'qa' | sed 's/^\s*//')
  branches=(${branches//;/ })

  if [ -z $branches ]; then
    echo 'No branches to delete...'
    return;
  fi

  echo $branches

  echo 'Do you want to delete these merged branches? (y/n)'
  read yn
  case $yn in
      [^Yy]* ) return;;
  esac

  echo 'Deleting...'

  git remote prune origin
  echo $branches | xargs git branch -d
  git branch -vv
}

How to set auto increment primary key in PostgreSQL?

If you want to do this in pgadmin, it is much easier. It seems in postgressql, to add a auto increment to a column, we first need to create a auto increment sequence and add it to the required column. I did like this.

1) Firstly you need to make sure there is a primary key for your table. Also keep the data type of the primary key in bigint or smallint. (I used bigint, could not find a datatype called serial as mentioned in other answers elsewhere)

2)Then add a sequence by right clicking on sequence-> add new sequence. If there is no data in the table, leave the sequence as it is, don't make any changes. Just save it. If there is existing data, add the last or highest value in the primary key column to the Current value in Definitions tab as shown below. enter image description here

3)Finally, add the line nextval('your_sequence_name'::regclass) to the Default value in your primary key as shown below.

enter image description here Make sure the sequence name is correct here. This is all and auto increment should work.

Fatal error: Call to a member function fetch_assoc() on a non-object

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

extract date only from given timestamp in oracle sql

If you want the value from your timestamp column to come back as a date datatype, use something like this:

select trunc(my_timestamp_column,'dd') as my_date_column from my_table;

Parse json string using JSON.NET

If your keys are dynamic I would suggest deserializing directly into a DataTable:

    class SampleData
    {
        [JsonProperty(PropertyName = "items")]
        public System.Data.DataTable Items { get; set; }
    }

    public void DerializeTable()
    {
        const string json = @"{items:["
            + @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
            + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
            + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
        var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
        var table = sampleData.Items;

        // write tab delimited table without knowing column names
        var line = string.Empty;
        foreach (DataColumn column in table.Columns)            
            line += column.ColumnName + "\t";                       
        Console.WriteLine(line);

        foreach (DataRow row in table.Rows)
        {
            line = string.Empty;
            foreach (DataColumn column in table.Columns)                
                line += row[column] + "\t";                                   
            Console.WriteLine(line);
        }

        // Name   Age   Job    
        // AAA    22    PPP    
        // BBB    25    QQQ    
        // CCC    38    RRR    
    }

You can determine the DataTable column names and types dynamically once deserialized.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Error Message : Cannot find or open the PDB file

If this happens in visual studio then clean your project and run it again.

Build --> Clean Solution

Run (or F5)

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

From the documentation (MySQL 8) :

      Type | Maximum length
-----------+-------------------------------------
  TINYTEXT |           255 (2 8−1) bytes
      TEXT |        65,535 (216−1) bytes = 64 KiB
MEDIUMTEXT |    16,777,215 (224−1) bytes = 16 MiB
  LONGTEXT | 4,294,967,295 (232−1) bytes =  4 GiB

Note that the number of characters that can be stored in your column will depend on the character encoding.

How do I get an OAuth 2.0 authentication token in C#

You may use the following code to get the bearer token.

private string GetBearerToken()
{
    var client = new RestClient("https://service.endpoint.com");
    client.Authenticator = new HttpBasicAuthenticator("abc", "123");
    var request = new RestRequest("api/oauth2/token", Method.POST);
    request.AddHeader("content-type", "application/json");
    request.AddParameter("application/json", "{ \"grant_type\":\"client_credentials\" }", 
    ParameterType.RequestBody);
    var responseJson = _client.Execute(request).Content;
    var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
    if(token.Length == 0)
    {
        throw new AuthenticationException("API authentication failed.");
    }
    return token;
}

Setting Windows PowerShell environment variables

Most answers aren't addressing UAC. This covers UAC issues.

First install PowerShell Community Extensions: choco install pscx via http://chocolatey.org/ (you may have to restart your shell environment).

Then enable pscx

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser #allows scripts to run from the interwebs, such as pcsx

Then use Invoke-Elevated

Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR

auto create database in Entity Framework Core

If you want both of EnsureCreated and Migrate use this code:

     using (var context = new YourDbContext())
            {
                if (context.Database.EnsureCreated())
                {
                    //auto migration when database created first time

                    //add migration history table

                    string createEFMigrationsHistoryCommand = $@"
USE [{context.Database.GetDbConnection().Database}];
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
CREATE TABLE [dbo].[__EFMigrationsHistory](
    [MigrationId] [nvarchar](150) NOT NULL,
    [ProductVersion] [nvarchar](32) NOT NULL,
 CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY CLUSTERED 
(
    [MigrationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY];
";
                    context.Database.ExecuteSqlRaw(createEFMigrationsHistoryCommand);

                    //insert all of migrations
                    var dbAssebmly = context.GetType().GetAssembly();
                    foreach (var item in dbAssebmly.GetTypes())
                    {
                        if (item.BaseType == typeof(Migration))
                        {
                            string migrationName = item.GetCustomAttributes<MigrationAttribute>().First().Id;
                            var version = typeof(Migration).Assembly.GetName().Version;
                            string efVersion = $"{version.Major}.{version.Minor}.{version.Build}";
                            context.Database.ExecuteSqlRaw("INSERT INTO __EFMigrationsHistory(MigrationId,ProductVersion) VALUES ({0},{1})", migrationName, efVersion);
                        }
                    }
                }
                context.Database.Migrate();
            }

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Modulus works to get bottom bits (only), although I think value & 0x1ffff expresses "take the bottom 17 bits" more directly than value % 131072, and so is easier to understand as doing that.

The top 17 bits of a 32-bit unsigned value would be value & 0xffff8000 (if you want them still in their positions at the top), or value >> 15 if you want the top 17 bits of the value in the bottom 17 bits of the result.

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

The issue here is that ng-repeat creates its own scope, so when you do selected=$index it creates a new a selected property in that scope rather than altering the existing one. To fix this you have two options:

Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:

$scope.selected = {value: 0};

<a ng-click="selected.value = $index">A{{$index}}</a>

See plunker

or

Use the $parent variable to access the correct property. Though less recommended as it increases coupling between scopes

<a ng-click="$parent.selected = $index">A{{$index}}</a>

See plunker

Check that a variable is a number in UNIX shell

if echo $var | egrep -q '^[0-9]+$'; then
    # $var is a number
else
    # $var is not a number
fi

What is the difference between git clone and checkout?

git clone is to fetch your repositories from the remote git server.

git checkout is to checkout your desired status of your repository (like branches or particular files).

E.g., you are currently on master branch and you want to switch into develop branch.

git checkout develop_branch

E.g., you want to checkout to a particular status of a particular file

git checkout commit_point_A -- <filename>

Here is a good reference for you to learn Git, lets you understand much more easily.

How to wait 5 seconds with jQuery?

Built in javascript setTimeout.

setTimeout(
  function() 
  {
    //do something special
  }, 5000);

UPDATE: you want to wait since when the page has finished loading, so put that code inside your $(document).ready(...); script.

UPDATE 2: jquery 1.4.0 introduced the .delay method. Check it out. Note that .delay only works with the jQuery effects queues.

Date query with ISODate in mongodb doesn't seem to work

In the MongoDB shell:

db.getCollection('sensorevents').find({from:{$gt: new ISODate('2015-08-30 16:50:24.481Z')}})

In my nodeJS code ( using Mongoose )

    SensorEvent.Model.find( {
        from: { $gt: new Date( SensorEventListener.lastSeenSensorFrom ) }
    } )

I am querying my sensor events collection to return values where the 'from' field is greater than the given date