Programs & Examples On #Hyde

Hyde is a static website generator written in python with the goal of removing the pain points involved in creating and maintaining static websites.

How to convert String into Hashmap in java

This is one solution. If you want to make it more generic, you can use the StringUtils library.

String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1);           //remove curly brackets
String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();               

for(String pair : keyValuePairs)                        //iterate over the pairs
{
    String[] entry = pair.split("=");                   //split the pairs to get key and value 
    map.put(entry[0].trim(), entry[1].trim());          //add them to the hashmap and trim whitespaces
}

For example you can switch

 value = value.substring(1, value.length()-1);

to

 value = StringUtils.substringBetween(value, "{", "}");

if you are using StringUtils which is contained in apache.commons.lang package.

How to encode a URL in Swift

URLQueryAllowedCharacterSet should not be used for URL encoding of query parameters because this charset includes &, ?, / etc. which serve as delimiters in a URL query, e.g.

/?paramname=paramvalue&paramname=paramvalue

These characters are allowed in URL queries as a whole but not in parameter values.

RFC 3986 specifically talks about unreserved characters, which are different from allowed:

2.3. Unreserved Characters

Characters that are allowed in a URI but do not have a reserved
purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.

  unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"

Accordingly:

extension String {
    var URLEncoded:String {
        var URLEncoded:String {
    let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
    let unreservedCharsSet: CharacterSet = CharacterSet(charactersIn: unreservedChars)
    let encodedString = self.addingPercentEncoding(withAllowedCharacters: unreservedCharsSet)!
    return encodedString
}
    }
}

The code above doesn't make a call to alphanumericCharacterSet because of the enormous size of the charset it returns (103806 characters). And in view of how many Unicode characters alphanumericCharacterSet allows for, using it for the purpose of URL encoding would be simply erroneous.

Usage:

let URLEncodedString = myString.URLEncoded

TypeError: $.browser is undefined

I placed the following html in my code and this cleared up the $.browser error

<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

Hope this helps u

Difference between HashMap, LinkedHashMap and TreeMap

  • HashMap:

    • Order not maintains
    • Faster than LinkedHashMap
    • Used for store heap of objects
  • LinkedHashMap:

    • LinkedHashMap insertion order will be maintained
    • Slower than HashMap and faster than TreeMap
    • If you want to maintain an insertion order use this.
  • TreeMap:

    • TreeMap is a tree-based mapping
    • TreeMap will follow the natural ordering of key
    • Slower than HashMap and LinkedHashMap
    • Use TreeMap when you need to maintain natural(default) ordering

Add a column to a table, if it does not already exist

IF NOT EXISTS (SELECT 1  FROM SYS.COLUMNS WHERE  
OBJECT_ID = OBJECT_ID(N'[dbo].[Person]') AND name = 'DateOfBirth')
BEGIN
ALTER TABLE [dbo].[Person] ADD DateOfBirth DATETIME
END

EXCEL VBA Check if entry is empty or not 'space'

Here is the code to check whether value is present or not.

If Trim(textbox1.text) <> "" Then
     'Your code goes here
Else
     'Nothing
End If

I think this will help.

Which version of CodeIgniter am I currently using?

You should try :

<?php
echo CI_VERSION;
?>

Or check the file system/core/CodeIgniter.php

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

You can do this easily with ReSharper 8 or later. The ctorf, ctorp, and ctorfp snippets generate constructors that populate all the fields, properties, or fields and properties of a class.

AngularJS: Basic example to use authentication in Single Page Application

I answered a similar question here: AngularJS Authentication + RESTful API


I've written an AngularJS module for UserApp that supports protected/public routes, rerouting on login/logout, heartbeats for status checks, stores the session token in a cookie, events, etc.

You could either:

  1. Modify the module and attach it to your own API, or
  2. Use the module together with UserApp (a cloud-based user management API)

https://github.com/userapp-io/userapp-angular

If you use UserApp, you won't have to write any server-side code for the user stuff (more than validating a token). Take the course on Codecademy to try it out.

Here's some examples of how it works:

  • How to specify which routes that should be public, and which route that is the login form:

    $routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
    $routeProvider.when('/home', {templateUrl: 'partials/home.html'});
    

    The .otherwise() route should be set to where you want your users to be redirected after login. Example:

    $routeProvider.otherwise({redirectTo: '/home'});

  • Login form with error handling:

    <form ua-login ua-error="error-msg">
        <input name="login" placeholder="Username"><br>
        <input name="password" placeholder="Password" type="password"><br>
        <button type="submit">Log in</button>
        <p id="error-msg"></p>
    </form>
    
  • Signup form with error handling:

    <form ua-signup ua-error="error-msg">
      <input name="first_name" placeholder="Your name"><br>
      <input name="login" ua-is-email placeholder="Email"><br>
      <input name="password" placeholder="Password" type="password"><br>
      <button type="submit">Create account</button>
      <p id="error-msg"></p>
    </form>
    
  • Log out link:

    <a href="#" ua-logout>Log Out</a>

    (Ends the session and redirects to the login route)

  • Access user properties:

    User properties are accessed using the user service, e.g: user.current.email

    Or in the template: <span>{{ user.email }}</span>

  • Hide elements that should only be visible when logged in:

    <div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>

  • Show an element based on permissions:

    <div ua-has-permission="admin">You are an admin</div>

And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API (if you use UserApp) to check if the token is valid or not.

If you need any help, just let me know!

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

Xcode 11

  1. Navigate to settings of your target and select General.
  2. Look for "Frameworks, Libraries, and Embedded Content"
  3. Keep "Do Not Embed" and make sure that all your targets (if you have more than one) have only set it's own framework and not others targets.

Calculate AUC in R?

Without any additional packages:

true_Y = c(1,1,1,1,2,1,2,1,2,2)
probs = c(1,0.999,0.999,0.973,0.568,0.421,0.382,0.377,0.146,0.11)

getROC_AUC = function(probs, true_Y){
    probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)
    val = unlist(probsSort$x)
    idx = unlist(probsSort$ix)  

    roc_y = true_Y[idx];
    stack_x = cumsum(roc_y == 2)/sum(roc_y == 2)
    stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)    

    auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])
    return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))
}

aList = getROC_AUC(probs, true_Y) 

stack_x = unlist(aList$stack_x)
stack_y = unlist(aList$stack_y)
auc = unlist(aList$auc)

plot(stack_x, stack_y, type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")
axis(1, seq(0.0,1.0,0.1))
axis(2, seq(0.0,1.0,0.1))
abline(h=seq(0.0,1.0,0.1), v=seq(0.0,1.0,0.1), col="gray", lty=3)
legend(0.7, 0.3, sprintf("%3.3f",auc), lty=c(1,1), lwd=c(2.5,2.5), col="blue", title = "AUC")

enter image description here

Get value from text area

You need to be using .val() not .value

$(document).ready(function () {
  if ($("textarea").val() != "") {
    alert($("textarea").val());
  }
});

Set up an HTTP proxy to insert a header

I have had co-workers that have used Burp ("an interactive HTTP/S proxy server for attacking and testing web applications") for this. You also may be able to use Fiddler ("a HTTP Debugging Proxy").

How to determine device screen size category (small, normal, large, xlarge) using code?

Jeff Gilfelt's answer as a static helper method:

private static String getSizeName(Context context) {
    int screenLayout = context.getResources().getConfiguration().screenLayout;
    screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK;

    switch (screenLayout) {
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        return "small";
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        return "normal";
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        return "large";
    case 4: // Configuration.SCREENLAYOUT_SIZE_XLARGE is API >= 9
        return "xlarge";
    default:
        return "undefined";
    }
}

How to make an ng-click event conditional?

I use the && expression which works perfectly for me.

For example,

<button ng-model="vm.slideOneValid" ng-disabled="!vm.slideOneValid" ng-click="vm.slideOneValid && vm.nextSlide()" class="btn btn-light-green btn-medium pull-right">Next</button>

If vm.slideOneValid is false, the second part of the expression is not fired. I know this is putting logic into the DOM, but it's a quick a dirty way to get ng-disabled and ng-click to place nice.

Just remember to add ng-model to the element to make ng-disabled work.

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Yes you can.

You don't have to download both Anaconda.

Only you need to download one of the version of Anaconda and need activate other version of Anaconda python.

If you have Python 3, you can set up a Python 2 kernel like this;

python2 -m pip install ipykernel

python2 -m ipykernel install --user

If you have Python 2,

python3 -m pip install ipykernel

python3 -m ipykernel install --user

Then you will be able to see both version of Python!

If you are using Anaconda Spyder then you should swap version here:

enter image description here

If you are using Jupiter then check here:

enter image description here

Note: If your Jupiter or Anaconda already open after installation you need to restart again. Then you will be able to see.

How to center an element horizontally and vertically

This should works

_x000D_
_x000D_
.center-div {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
    text-align: center;_x000D_
    min-height: 100vh;_x000D_
}
_x000D_
<div class="center-div">Center Div</div>
_x000D_
_x000D_
_x000D_

ASP.NET MVC: Custom Validation by DataAnnotation

To improve Darin's answer, it can be bit shorter:

public class UniqueFileName : ValidationAttribute
{
    private readonly NewsService _newsService = new NewsService();

    public override bool IsValid(object value)
    {
        if (value == null) { return false; }

        var file = (HttpPostedFile) value;

        return _newsService.IsFileNameUnique(file.FileName);
    }
}

Model:

[UniqueFileName(ErrorMessage = "This file name is not unique.")]

Do note that an error message is required, otherwise the error will be empty.

Editor does not contain a main type in Eclipse

For me, classpath entry in .classpath file isn't pointing to the right location. After modifying it to <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/> fixed the issue

URL encode sees “&” (ampersand) as “&amp;” HTML entity

If you did literally this:

encodeURIComponent('&')

Then the result is %26, you can test it here. Make sure the string you are encoding is just & and not &amp; to begin with...otherwise it is encoding correctly, which is likely the case. If you need a different result for some reason, you can do a .replace(/&amp;/g,'&') before the encoding.

How to remove from a map while iterating it?

In short "How do I remove from a map while iterating it?"

  • With old map impl: You can't
  • With new map impl: almost as @KerrekSB suggested. But there are some syntax issues in what he posted.

From GCC map impl (note GXX_EXPERIMENTAL_CXX0X):

#ifdef __GXX_EXPERIMENTAL_CXX0X__
      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // DR 130. Associative erase should return an iterator.
      /**
       *  @brief Erases an element from a %map.
       *  @param  position  An iterator pointing to the element to be erased.
       *  @return An iterator pointing to the element immediately following
       *          @a position prior to the element being erased. If no such 
       *          element exists, end() is returned.
       *
       *  This function erases an element, pointed to by the given
       *  iterator, from a %map.  Note that this function only erases
       *  the element, and that if the element is itself a pointer,
       *  the pointed-to memory is not touched in any way.  Managing
       *  the pointer is the user's responsibility.
       */
      iterator
      erase(iterator __position)
      { return _M_t.erase(__position); }
#else
      /**
       *  @brief Erases an element from a %map.
       *  @param  position  An iterator pointing to the element to be erased.
       *
       *  This function erases an element, pointed to by the given
       *  iterator, from a %map.  Note that this function only erases
       *  the element, and that if the element is itself a pointer,
       *  the pointed-to memory is not touched in any way.  Managing
       *  the pointer is the user's responsibility.
       */
      void
      erase(iterator __position)
      { _M_t.erase(__position); }
#endif

Example with old and new style:

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

using namespace std;
typedef map<int, int> t_myMap;
typedef vector<t_myMap::key_type>  t_myVec;

int main() {

    cout << "main() ENTRY" << endl;

    t_myMap mi;
    mi.insert(t_myMap::value_type(1,1));
    mi.insert(t_myMap::value_type(2,1));
    mi.insert(t_myMap::value_type(3,1));
    mi.insert(t_myMap::value_type(4,1));
    mi.insert(t_myMap::value_type(5,1));
    mi.insert(t_myMap::value_type(6,1));

    cout << "Init" << endl;
    for(t_myMap::const_iterator i = mi.begin(); i != mi.end(); i++)
        cout << '\t' << i->first << '-' << i->second << endl;

    t_myVec markedForDeath;

    for (t_myMap::const_iterator it = mi.begin(); it != mi.end() ; it++)
        if (it->first > 2 && it->first < 5)
            markedForDeath.push_back(it->first);

    for(size_t i = 0; i < markedForDeath.size(); i++)
        // old erase, returns void...
        mi.erase(markedForDeath[i]);

    cout << "after old style erase of 3 & 4.." << endl;
    for(t_myMap::const_iterator i = mi.begin(); i != mi.end(); i++)
        cout << '\t' << i->first << '-' << i->second << endl;

    for (auto it = mi.begin(); it != mi.end(); ) {
        if (it->first == 5)
            // new erase() that returns iter..
            it = mi.erase(it);
        else
            ++it;
    }

    cout << "after new style erase of 5" << endl;
    // new cend/cbegin and lambda..
    for_each(mi.cbegin(), mi.cend(), [](t_myMap::const_reference it){cout << '\t' << it.first << '-' << it.second << endl;});

    return 0;
}

prints:

main() ENTRY
Init
        1-1
        2-1
        3-1
        4-1
        5-1
        6-1
after old style erase of 3 & 4..
        1-1
        2-1
        5-1
        6-1
after new style erase of 5
        1-1
        2-1
        6-1

Process returned 0 (0x0)   execution time : 0.021 s
Press any key to continue.

iTunes Connect: How to choose a good SKU?

You are able to choose one that you like, but it has to be unique.

Every time I have to enter the SKU I use the App identifier (e.g. de.mycompany.myappname) because this is already unique.

Populating a database in a Laravel migration file

This should do what you want.

public function up()
{
    DB::table('user')->insert(array('username'=>'dude', 'password'=>'z19pers!'));
}

How do I reference a cell range from one worksheet to another using excel formulas?

If you wish to concatenate multiple cells from different sheets, and you also want to add a delimiter between the content of each cell, the most straightforward way to do it is:

=CONCATENATE(Sheet1!A4, ", ", Sheet2!A5)

This works only for a limited number of referenced cells, but it is fast if you have only of few of these cells that you want to map.

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

Is it safe to delete the "InetPub" folder?

it is safe to delete the inetpub it is only a cache.

Convert base-2 binary number string to int

If you are using python3.6 or later you can use f-string to do the conversion:

Binary to decimal:

>>> print(f'{0b1011010:#0}')
90

>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90

binary to octal hexa and etc.

>>> f'{0b1011010:#o}'
'0o132'  # octal

>>> f'{0b1011010:#x}'
'0x5a'   # hexadecimal

>>> f'{0b1011010:#0}'
'90'     # decimal

Pay attention to 2 piece of information separated by colon.

In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]

:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal 
:#0 -> converts to decimal as above example

Try changing left side of colon to have octal/hexadecimal/decimal.

"SDK Platform Tools component is missing!"

I don't understand why the files were relocated to /platform-tools from /tools. It seems ALL development tools I have tried, appcelerator for one, have their setup software look for these files in /tools and fail setup. The "work around" involves a few different bits of trickery wherein you either...1) set up a soft link to tell the operating system "if you look for file "x" here it is really over here. or 2) simpler method ... make a copy of all the /platform-tools default (pre-additional android sdk installations) files and place them into the /tools folder. this circumvents the relocation that the newer sdk have done. Then of course YOU MUST SET PATH ENVIRONMENT VARIABLES TO POINT TO THE SDK LOCATION (sometimes to the Android-sdk-[operating system name:Android-sdk-windows or Android-sdk-mac_x86 ect. ] and to the /platform-tools and sometimes to /tools. it is a trial and error pain. But when it finally is working ...it works.

Play sound file in a web-page in the background

If you don't want to show controls then try this code

<audio  autoplay>
 <source src="song.ogg"  type="audio/ogg">
Your browser does not support the audio element.
</audio>

Hide Text with CSS, Best Practice?

I do it like this:

.hidden-text {
  left: 100%;
  display: inline-block;
  position: fixed;
}

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

groovy: safely find a key in a map and return its value

In general, this depends what your map contains. If it has null values, things can get tricky and containsKey(key) or get(key, default) should be used to detect of the element really exists. In many cases the code can become simpler you can define a default value:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x1 = mymap.get('likes', '[nothing specified]')
println "x value: ${x}" }

Note also that containsKey() or get() are much faster than setting up a closure to check the element mymap.find{ it.key == "likes" }. Using closure only makes sense if you really do something more complex in there. You could e.g. do this:

mymap.find{ // "it" is the default parameter
  if (it.key != "likes") return false
  println "x value: ${it.value}" 
  return true // stop searching
}

Or with explicit parameters:

mymap.find{ key,value ->
  (key != "likes")  return false
  println "x value: ${value}" 
  return true // stop searching
}

What is the attribute property="og:title" inside meta tag?

Probably part of Open Graph Protocol for Facebook.

Edit: guess not only Facebook - that's only one example of using it.

How to check the presence of php and apache on ubuntu server through ssh

Another way to find out if a program is installed is by using the which command. It will show the path of the program you're searching for. For example if when your searching for apache you can use the following command:

$ which apache2ctl
/usr/sbin/apache2ctl

And if you searching for PHP try this:

$ which php
/usr/bin/php

If the which command doesn't give any result it means the software is not installed (or is not in the current $PATH):

$ which php
$

iOS how to set app icon and launch images

I use a tool called Prepo to produce all the right image sizes. You simply feed the app you image file and it will spit out each necessary file with an appropriate name.

Once you do this, you can then drag in the appropriate files or simply point to your Prepo exported folder.

How can you make a custom keyboard in Android?

Use KeyboardView:

KeyboardView kbd = new KeyboardView(context);
kbd.setKeyboard(new Keyboard(this, R.xml.custom));

kbd.setOnKeyboardActionListener(new OnKeyboardActionListener() {
    ....
}

now you have kbd which is a normal view.

The nice thing about this is that R.xml.custom refers to /res/xml/custom.xml, which defines in xml the layout of the keyboard. For more information on this file, look here: Keyboard, Keyboard.Row, Keyboard.Key.

Visual studio code terminal, how to run a command with administrator rights?

Here's what I get.

I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.

Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'

PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:

PS g:\labs\myproject> npm install bootstrap@3

Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s

This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.

How can I keep my branch up to date with master with git?

Assuming you're fine with taking all of the changes in master, what you want is:

git checkout <my branch>

to switch the working tree to your branch; then:

git merge master

to merge all the changes in master with yours.

How can I find script's directory?

This is a pretty old thread but I've been having this problem when trying to save files into the current directory the script is in when running a python script from a cron job. getcwd() and a lot of the other path come up with your home directory.

to get an absolute path to the script i used

directory = os.path.abspath(os.path.dirname(__file__))

Google Recaptcha v3 example demo

We use recaptcha-V3 only to see site traffic quality, and used it as non blocking. Since recaptcha-V3 doesn't require to show on site and can be used as hidden but you have to show recaptcha privacy etc links (as recommended)

Script Tag in Head

<script src="https://www.google.com/recaptcha/api.js?onload=ReCaptchaCallbackV3&render='SITE KEY' async defer></script>

Note: "async defer" make sure its non blocking which is our specific requirement

JS Code:

<script>
    ReCaptchaCallbackV3 = function() {
        grecaptcha.ready(function() {
            grecaptcha.execute("SITE KEY").then(function(token) {
                $.ajax({
                    type: "POST",
                    url: `https://api.${window.appInfo.siteDomain}/v1/recaptcha/score`,
                    data: {
                        "token" : token,
                    },
                    success: function(data) {
                        if(data.response.success) {
                            window.recaptchaScore = data.response.score;
                            console.log('user score ' + data.response.score)
                        }
                    },
                    error: function() {
                        console.log('error while getting google recaptcha score!')
                    }
                });

            });
        });
    };
</script> 

HTML/Css Code:

there is no html code since our requirement is just to get score and don't want to show recaptcha badge.

Backend - Laravel Code:

Route:

Route::post('/recaptcha/score', 'Api\\ReCaptcha\\RecaptchaScore@index');


Class:

class RecaptchaScore extends Controller
{
    public function index(Request $request)
    {
        $score = null;

        $response = (new Client())->request('post', 'https://www.google.com/recaptcha/api/siteverify', [
            'form_params' => [
                'response' => $request->get('token'),
                'secret' => 'SECRET HERE',
            ],
        ]);

        $score = json_decode($response->getBody()->getContents(), true);

        if (!$score['success']) {
            Log::warning('Google ReCaptcha Score', [
                'class' => __CLASS__,
                'message' => json_encode($score['error-codes']),
            ]);
        }

        return [
            'response' => $score,
        ];
    }
} 

we get back score and save in variable which we later user when submit form.

Reference: https://developers.google.com/recaptcha/docs/v3 https://developers.google.com/recaptcha/

Cannot declare instance members in a static class in C#

public static class Employee
{
    public static string SomeSetting
    {
        get 
        {
            return ConfigurationManager.AppSettings["SomeSetting"];    
        }
    }
}

Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.

If you feel that you must store a reference to appsettings, try

public static class Employee
{
    private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;

    public static NameValueCollection AppSettings { get { return _appSettings; } }

}

It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

How to dynamically set bootstrap-datepicker's date value?

For Bootstrap 4

If you are using input group in Bootstrap, you need to attach the new date to parent of the textbox, otherwise if you click on the calendar icon and click outside the date will be cleared.

<div class="input-group date" id="my-date-component">
   <input type="text" />
    <div class="input-group-append">
      <span class="input-group-text"><i class="fa fa-calendar"></i></span>
    </div>
</div>

You need to set date to input-group.date.

$('#my-date-component').datepicker("update", new Date("01/10/2014"));

Also check datepicker update method

How to list imported modules?

let say you've imported math and re:

>>import math,re

now to see the same use

>>print(dir())

If you run it before the import and after the import, one can see the difference.

Getting JavaScript object key list

Underscore.js makes the transformation pretty clean:

var keys = _.map(x, function(v, k) { return k; });

Edit: I missed that you can do this too:

var keys = _.keys(x);

How to validate a credit card number

Use this:

function AmexCardnumber(inputtxt) {
  var cardno = /^(?:3[47][0-9]{13})$/;
  return cardno.test(inputtxt);
}

function VisaCardnumber(inputtxt) {
  var cardno = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;
  return cardno.test(inputtxt);
}

function MasterCardnumber(inputtxt) {
  var cardno = /^(?:5[1-5][0-9]{14})$/;
  return cardno.test(inputtxt);
}

function DiscoverCardnumber(inputtxt) {
  var cardno = /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/;
  return cardno.test(inputtxt);
}

function DinerClubCardnumber(inputtxt) {
  var cardno = /^(?:3(?:0[0-5]|[68][0-9])[0-9]{11})$/;
  return cardno.test(inputtxt);
}

function JCBCardnumber(inputtxt) {
  var cardno = /^(?:(?:2131|1800|35\d{3})\d{11})$/;
  return cardno.test(inputtxt);
}

function IsValidCreditCardNumber(cardNumber) {

  var cardType = null;
  if (VisaCardnumber(cardNumber)) {
    cardType = "visa";
  } else if (MasterCardnumber(cardNumber)) {
    cardType = "mastercard";
  } else if (AmexCardnumber(cardNumber)) {
    cardType = "americanexpress";
  } else if (DiscoverCardnumber(cardNumber)) {
    cardType = "discover";
  } else if (DinerClubCardnumber(cardNumber)) {
    cardType = "dinerclub";
  } else if (JCBCardnumber(cardNumber)) {
    cardType = "jcb";
  }

  return cardType;
}

Sending Arguments To Background Worker?

Check out the DoWorkEventArgs.Argument Property:

...
backgroundWorker1.RunWorkerAsync(yourInt);
...

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // Do not access the form's BackgroundWorker reference directly.
    // Instead, use the reference provided by the sender parameter.
    BackgroundWorker bw = sender as BackgroundWorker;

    // Extract the argument.
    int arg = (int)e.Argument;

    // Start the time-consuming operation.
    e.Result = TimeConsumingOperation(bw, arg);

    // If the operation was canceled by the user, 
    // set the DoWorkEventArgs.Cancel property to true.
    if (bw.CancellationPending)
    {
        e.Cancel = true;
    }
}

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Easiest way is to throw a ResponseStatusException

    @RequestMapping(value = "/matches/{matchId}", produces = "application/json")
    @ResponseBody
    public String match(@PathVariable String matchId, @RequestBody String body) {
        String json = matchService.getMatchJson(matchId);
        if (json == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        return json;
    }

did you register the component correctly? For recursive components, make sure to provide the "name" option

In my case (quasar and command quasar dev for testing), I just forgot to restart dev Quasar command.

It seemed to me that components was automatically loaded when any change was done. But in this case, I reused component in another page and I got this message.

String to LocalDate

java.time

Since Java 1.8, you can achieve this without an extra library by using the java.time classes. See Tutorial.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
formatter = formatter.withLocale( putAppropriateLocaleHere );  // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("2005-nov-12", formatter);

The syntax is nearly the same though.

How do I bottom-align grid elements in bootstrap fluid layout

This is based on cfx's solution, but rather than setting the font size to zero in the parent container to remove the inter-column spaces added because of the display: inline-block and having to reset them, I simply added

_x000D_
_x000D_
.row.row-align-bottom > div {_x000D_
    float: none;_x000D_
    display: inline-block;_x000D_
    vertical-align: bottom;_x000D_
    margin-right: -0.25em;_x000D_
}
_x000D_
_x000D_
_x000D_

to the column divs to compensate.

Install / upgrade gradle on Mac OS X

And using ports:

port install gradle

Ports , tested on El Capitan

shift a std_logic_vector of n bit to right or left

There are two ways that you can achieve this. Concatenation, and shift/rotate functions.

  • Concatenation is the "manual" way of doing things. You specify what part of the original signal that you want to "keep" and then concatenate on data to one end or the other. For example: tmp <= tmp(14 downto 0) & '0';

  • Shift functions (logical, arithmetic): These are generic functions that allow you to shift or rotate a vector in many ways. The functions are: sll (shift left logical), srl (shift right logical). A logical shift inserts zeros. Arithmetric shifts (sra/sla) insert the left most or right most bit, but work in the same way as logical shift. Note that for all of these operations you specify what you want to shift (tmp), and how many times you want to perform the shift (n bits)

  • Rotate functions: rol (rotate left), ror (rotate right). Rotating does just that, the MSB ends up in the LSB and everything shifts left (rol) or the other way around for ror.

Here is a handy reference I found (see the first page).

How to obtain the last index of a list?

I guess you want

last_index = len(list1) - 1 

which would store 3 in last_index.

How to use an output parameter in Java?

Java passes by value; there's no out parameter like in C#.

You can either use return, or mutate an object passed as a reference (by value).

Related questions


Code sample

public class FunctionSample {
    static String fReturn() {
        return "Hello!";
    }
    static void fArgNoWorkie(String s) {
        s = "What am I doing???"; // Doesn't "work"! Java passes by value!
    }
    static void fMutate(StringBuilder sb) {
        sb.append("Here you go!");
    }
    public static void main(String[] args) {
        String s = null;

        s = fReturn();
        System.out.println(s); // prints "Hello!"

        fArgNoWorkie(s);
        System.out.println(s); // prints "Hello!"

        StringBuilder sb = new StringBuilder();
        fMutate(sb);
        s = sb.toString();
        System.out.println(s); // prints "Here you go!"
    }

}

See also


As for the code that OP needs help with, here's a typical solution of using a special value (usually null for reference types) to indicate success/failure:

Instead of:

String oPerson= null;
if (CheckAddress("5556", oPerson)) {
   print(oPerson); // DOESN'T "WORK"! Java passes by value; String is immutable!
}

private boolean CheckAddress(String iAddress, String oPerson) {
   // on search succeeded:
   oPerson = something; // DOESN'T "WORK"!
   return true;
   :
   // on search failed:
   return false;
}

Use a String return type instead, with null to indicate failure.

String person = checkAddress("5556");
if (person != null) {
   print(person);
}

private String checkAddress(String address) {
   // on search succeeded:
   return something;
   :
   // on search failed:
   return null;
}

This is how java.io.BufferedReader.readLine() works, for example: it returns instanceof String (perhaps an empty string!), until it returns null to indicate end of "search".

This is not limited to a reference type return value, of course. The key is that there has to be some special value(s) that is never a valid value, and you use that value for special purposes.

Another classic example is String.indexOf: it returns -1 to indicate search failure.

Note: because Java doesn't have a concept of "input" and "output" parameters, using the i- and o- prefix (e.g. iAddress, oPerson) is unnecessary and unidiomatic.


A more general solution

If you need to return several values, usually they're related in some way (e.g. x and y coordinates of a single Point). The best solution would be to encapsulate these values together. People have used an Object[] or a List<Object>, or a generic Pair<T1,T2>, but really, your own type would be best.

For this problem, I recommend an immutable SearchResult type like this to encapsulate the boolean and String search results:

public class SearchResult {
   public final String name;
   public final boolean isFound;

   public SearchResult(String name, boolean isFound) {
      this.name = name;
      this.isFound = isFound;
   }
}

Then in your search function, you do the following:

private SearchResult checkAddress(String address) {
  // on address search succeed
  return new SearchResult(foundName, true);
  :
  // on address search failed
  return new SearchResult(null, false);
}

And then you use it like this:

SearchResult sr = checkAddress("5556");
if (sr.isFound) {
  String name = sr.name;
  //...
}

If you want, you can (and probably should) make the final immutable fields non-public, and use public getters instead.

How to scale down a range of numbers with a known min and max value

Let's say you want to scale a range [min,max] to [a,b]. You're looking for a (continuous) function that satisfies

f(min) = a
f(max) = b

In your case, a would be 1 and b would be 30, but let's start with something simpler and try to map [min,max] into the range [0,1].

Putting min into a function and getting out 0 could be accomplished with

f(x) = x - min   ===>   f(min) = min - min = 0

So that's almost what we want. But putting in max would give us max - min when we actually want 1. So we'll have to scale it:

        x - min                                  max - min
f(x) = ---------   ===>   f(min) = 0;  f(max) =  --------- = 1
       max - min                                 max - min

which is what we want. So we need to do a translation and a scaling. Now if instead we want to get arbitrary values of a and b, we need something a little more complicated:

       (b-a)(x - min)
f(x) = --------------  + a
          max - min

You can verify that putting in min for x now gives a, and putting in max gives b.

You might also notice that (b-a)/(max-min) is a scaling factor between the size of the new range and the size of the original range. So really we are first translating x by -min, scaling it to the correct factor, and then translating it back up to the new minimum value of a.

Hope this helps.

Send JavaScript variable to PHP variable

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Regards

System.Timers.Timer vs System.Threading.Timer

I found a short comparison from MSDN

The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

System.Windows.Forms.Timer, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.

System.Web.UI.Timer, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

OAuth: how to test with local URLs?

Update October 2016: Easiest now: use lvh.me which always points to 127.0.0.1.

Previous Answer:

Since the callback request is issued by the browser, as a HTTP redirect response, you can set up your .hosts file or equivalent to point a domain that is not localhost to 127.0.0.1.

Say for example you register the following callback with Twitter: http://www.publicdomain.com/callback/. Make sure that www.publicdomain.com points to 127.0.0.1 in your hosts file, AND that twitter can do a successful DNS lookup on www.publicdomain.com, i.e the domain needs to exist and the specific callback should probably return a 200 status message if requested.

EDIT:

I just read the following article: http://www.tonyamoyal.com/2009/08/17/how-to-quickly-set-up-a-test-for-twitter-oauth-authentication-from-your-local-machine, which was linked to from this question: Twitter oAuth callbackUrl - localhost development.

To quote the article:

You can use bit.ly, a URL shortening service. Just shorten the [localhost URL such as http//localhost:8080/twitter_callback] and register the shortened URL as the callback in your Twitter app.

This should be easier than fiddling around in the .hosts file.

Note that now (Aug '14) bit.ly is not allowing link forwarding to localhost; however Google link shortener works.

PS edit: (Nov '18): Google link shortener stopped giving support for localhost or 127.0.0.1.

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

It's not fancy I known but you could use a callback class, create a hostbuilder and set the configuration to a static property.

For asp core 2.2:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;

namespace Project
{
    sealed class Program
    {
        #region Variables
        /// <summary>
        /// Last loaded configuration
        /// </summary>
        private static IConfiguration _Configuration;
        #endregion

        #region Properties
        /// <summary>
        /// Default application configuration
        /// </summary>
        internal static IConfiguration Configuration
        {
            get
            {
                // None configuration yet?
                if (Program._Configuration == null)
                {
                    // Create the builder using a callback class
                    IWebHostBuilder builder = WebHost.CreateDefaultBuilder().UseStartup<CallBackConfiguration>();

                    // Build everything but do not initialize it
                    builder.Build();
                }

                // Current configuration
                return Program._Configuration;
            }

            // Update configuration
            set => Program._Configuration = value;
        }
        #endregion

        #region Public
        /// <summary>
        /// Start the webapp
        /// </summary>
        public static void Main(string[] args)
        {
            // Create the builder using the default Startup class
            IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

            // Build everything and run it
            using (IWebHost host = builder.Build())
                host.Run();
        }
        #endregion


        #region CallBackConfiguration
        /// <summary>
        /// Aux class to callback configuration
        /// </summary>
        private class CallBackConfiguration
        {
            /// <summary>
            /// Callback with configuration
            /// </summary>
            public CallBackConfiguration(IConfiguration configuration)
            {
                // Update the last configuration
                Program.Configuration = configuration;
            }

            /// <summary>
            /// Do nothing, just for compatibility
            /// </summary>
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                //
            }
        }
        #endregion
    }
}

So now on you just use the static Program.Configuration at any other class you need it.

What are advantages of Artificial Neural Networks over Support Vector Machines?

One answer I'm missing here: Multi-layer perceptron is able to find relation between features. For example it is necessary in computer vision when a raw image is provided to the learning algorithm and now Sophisticated features are calculated. Essentially the intermediate levels can calculate new unknown features.

Return Index of an Element in an Array Excel VBA

Taking care of whether the array starts at zero or one. Also, when position 0 or 1 is returned by the function, making sure that the same is not confused as True or False returned by the function.

Function array_return_index(arr As Variant, val As Variant, Optional array_start_at_zero As Boolean = True) As Variant

Dim pos
pos = Application.Match(val, arr, False)

If Not IsError(pos) Then
    If array_start_at_zero = True Then
        pos = pos - 1
        'initializing array at 0
    End If
   array_return_index = pos
Else
   array_return_index = False
End If

End Function

Sub array_return_index_test()
Dim pos, arr, val

arr = Array(1, 2, 4, 5)
val = 1

'When array starts at zero
pos = array_return_index(arr, val)
If IsNumeric(pos) Then
MsgBox "Array starting at 0; Value found at : " & pos
Else
MsgBox "Not found"
End If

'When array starts at one
pos = array_return_index(arr, val, False)
If IsNumeric(pos) Then
MsgBox "Array starting at 1; Value found at : " & pos
Else
MsgBox "Not found"
End If



End Sub

Allowing Untrusted SSL Certificates with HttpClient

Or you can use for the HttpClient in the Windows.Web.Http namespace:

var filter = new HttpBaseProtocolFilter();
#if DEBUG
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
#endif
using (var httpClient = new HttpClient(filter)) {
    ...
}

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

How to debug on a real device (using Eclipse/ADT)

With an Android-powered device, you can develop and debug your Android applications just as you would on the emulator.

1. Declare your application as "debuggable" in AndroidManifest.xml.

<application
    android:debuggable="true"
    ... >
    ...
</application>

2. On your handset, navigate to Settings > Security and check Unknown sources

enter image description here

3. Go to Settings > Developer Options and check USB debugging
Note that if Developer Options is invisible you will need to navigate to Settings > About Phone and tap on Build number several times until you are notified that it has been unlocked.

enter image description here

4. Set up your system to detect your device.
Follow the instructions below for your OS:


Windows Users

Install the Google USB Driver from the ADT SDK Manager
(Support for: ADP1, ADP2, Verizon Droid, Nexus One, Nexus S).

enter image description here

For devices not listed above, install an OEM driver for your device


Mac OS X

Your device should automatically work; Go to the next step


Ubuntu Linux

Add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, click here. To set up device detection on Ubuntu Linux:

  1. Log in as root and create this file: /etc/udev/rules.d/51-android.rules.
  2. Use this format to add each vendor to the file:
    SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"
    In this example, the vendor ID is for HTC. The MODE assignment specifies read/write permissions, and GROUP defines which Unix group owns the device node.
  3. Now execute: chmod a+r /etc/udev/rules.d/51-android.rules

Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.


5. Run the project with your connected device.

With Eclipse/ADT: run or debug your application as usual. You will be presented with a Device Chooser dialog that lists the available emulator(s) and connected device(s).

With ADB: issue commands with the -d flag to target your connected device.

Still need help? Click here for the full guide.

Entity Framework - Linq query with order by and group by

You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye

var groupByReference = (from m in context.Measurements
                              .GroupBy(m => m.Reference)
                              .Take(numOfEntries).AsEnumerable()
                               .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
                                             Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
                              .ThenBy(x => x.Avg)
                              .ToList() select m);

Your sql query would look similar (depending on your input) this

SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
    SELECT [t0].[Reference]
    FROM [Measurements] AS [t0]
    GROUP BY [t0].[Reference]
    ) AS [t1]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]

How to customize the configuration file of the official PostgreSQL Docker image?

You can put your custom postgresql.conf in a temporary file inside the container, and overwrite the default configuration at runtime.

To do that :

  • Copy your custom postgresql.conf inside your container
  • Copy the updateConfig.sh file in /docker-entrypoint-initdb.d/

Dockerfile

FROM postgres:9.6

COPY postgresql.conf      /tmp/postgresql.conf
COPY updateConfig.sh      /docker-entrypoint-initdb.d/_updateConfig.sh

updateConfig.sh

#!/usr/bin/env bash

cat /tmp/postgresql.conf > /var/lib/postgresql/data/postgresql.conf

At runtime, the container will execute the script inside /docker-entrypoint-initdb.d/ and overwrite the default configuration with yout custom one.

error LNK2005, already defined?

Presence of int k; in the header file causes symbol k to be defined within each translation unit this header is included to while linker expects it to be defined only once (aka One Definition Rule Violation).

While suggestion involving extern are not wrong, extern is a C-ism and should not be used.

Pre C++17 solution that would allow variable in header file to be defined in multiple translation units without causing ODR violation would be conversion to template:

template<typename x_Dummy = void> class
t_HeaderVariableHolder
{
    public: static int s_k;
};

template<typename x_Dummy> int t_HeaderVariableHolder<x_Dummy>::s_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return t_HeaderVariableHolder<>::s_k;
}

With C++17 things become much simpler as it allows inline variables:

inline int g_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return g_k;
}

Run script on mac prompt "Permission denied"

Check the permissions on your Ruby script (may not have execute permission), your theme file and directory (in case it can't read the theme or tries to create other themes in there), and the directory you're in when you run the script (in case it makes temporary files in the current directory rather then /tmp).

Any one of them could be causing you grief.

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

For add new PCH file follow bellow steps :

(1) Add New fiew - Select iOS - Other and PCH File

(2) add path of this PCH file to your Project - BuildSetting - Apple LLVM 6.0 Language

Add Set Prefix Header Path YourApplicationName(root-path)/filename.pch

Filter Excel pivot table using VBA

I think i am understanding your question. This filters things that are in the column labels or the row labels. The last 2 sections of the code is what you want but im pasting everything so that you can see exactly how It runs start to finish with everything thats defined etc. I definitely took some of this code from other sites fyi.

Near the end of the code, the "WardClinic_Category" is a column of my data and in the column label of the pivot table. Same for the IVUDDCIndicator (its a column in my data but in the row label of the pivot table).

Hope this helps others...i found it very difficult to find code that did this the "proper way" rather than using code similar to the macro recorder.

Sub CreatingPivotTableNewData()


'Creating pivot table
Dim PvtTbl As PivotTable
Dim wsData As Worksheet
Dim rngData As Range
Dim PvtTblCache As PivotCache
Dim wsPvtTbl As Worksheet
Dim pvtFld As PivotField

'determine the worksheet which contains the source data
Set wsData = Worksheets("Raw_Data")

'determine the worksheet where the new PivotTable will be created
Set wsPvtTbl = Worksheets("3N3E")

'delete all existing Pivot Tables in the worksheet
'in the TableRange1 property, page fields are excluded; to select the entire PivotTable report, including the page fields, use the TableRange2 property.
For Each PvtTbl In wsPvtTbl.PivotTables
If MsgBox("Delete existing PivotTable!", vbYesNo) = vbYes Then
PvtTbl.TableRange2.Clear
End If
Next PvtTbl


'A Pivot Cache represents the memory cache for a PivotTable report. Each Pivot Table report has one cache only. Create a new PivotTable cache, and then create a new PivotTable report based on the cache.

'set source data range:
Worksheets("Raw_Data").Activate
Set rngData = wsData.Range(Range("A1"), Range("H1").End(xlDown))


'Creates Pivot Cache and PivotTable:
Worksheets("Raw_Data").Activate
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData.Address, Version:=xlPivotTableVersion12).CreatePivotTable TableDestination:=wsPvtTbl.Range("A1"), TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
Set PvtTbl = wsPvtTbl.PivotTables("PivotTable1")

'Default value of ManualUpdate property is False so a PivotTable report is recalculated automatically on each change.
'Turn this off (turn to true) to speed up code.
PvtTbl.ManualUpdate = True


'Adds row and columns for pivot table
PvtTbl.AddFields RowFields:="VerifyHr", ColumnFields:=Array("WardClinic_Category", "IVUDDCIndicator")

'Add item to the Report Filter
PvtTbl.PivotFields("DayOfWeek").Orientation = xlPageField


'set data field - specifically change orientation to a data field and set its function property:
With PvtTbl.PivotFields("TotalVerified")
.Orientation = xlDataField
.Function = xlAverage
.NumberFormat = "0.0"
.Position = 1
End With

'Removes details in the pivot table for each item
Worksheets("3N3E").PivotTables("PivotTable1").PivotFields("WardClinic_Category").ShowDetail = False

'Removes pivot items from pivot table except those cases defined below (by looping through)
For Each PivotItem In PvtTbl.PivotFields("WardClinic_Category").PivotItems
    Select Case PivotItem.Name
        Case "3N3E"
            PivotItem.Visible = True
        Case Else
            PivotItem.Visible = False
        End Select
    Next PivotItem


'Removes pivot items from pivot table except those cases defined below (by looping through)
For Each PivotItem In PvtTbl.PivotFields("IVUDDCIndicator").PivotItems
    Select Case PivotItem.Name
        Case "UD", "IV"
            PivotItem.Visible = True
        Case Else
            PivotItem.Visible = False
        End Select
    Next PivotItem

'turn on automatic update / calculation in the Pivot Table
PvtTbl.ManualUpdate = False


End Sub

Sql query to insert datetime in SQL Server

Management studio creates scripts like:

insert table1 (foodate) values(CAST(N'2012-06-18 10:34:09.000' AS DateTime))

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

!python 'script.py'

replace script.py with your real file name, DON'T forget ''

Twitter Bootstrap - full width navbar

Put your <nav>element out from the <div class='container-fluid'>. Ex :-

_x000D_
_x000D_
<nav>_x000D_
 ......nav content goes here_x000D_
<nav>_x000D_
_x000D_
<div class="container-fluid">_x000D_
  <div>_x000D_
   ........ other content goes here_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Count number of rows per group and add result to original data frame

Using data.table:

library(data.table)
dt = as.data.table(df)

# or coerce to data.table by reference:
# setDT(df)

dt[ , count := .N, by = .(name, type)]

For pre-data.table 1.8.2 alternative, see edit history.


Using dplyr:

library(dplyr)
df %>%
  group_by(name, type) %>%
  mutate(count = n())

Or simply:

add_count(df, name, type)

Using plyr:

plyr::ddply(df, .(name, type), transform, count = length(num))

The most accurate way to check JS object's type?

Old question I know. You don't need to convert it. See this function:

function getType( oObj )
{
    if( typeof oObj === "object" )
    {
          return ( oObj === null )?'Null':
          // Check if it is an alien object, for example created as {world:'hello'}
          ( typeof oObj.constructor !== "function" )?'Object':
          // else return object name (string)
          oObj.constructor.name;              
    }   

    // Test simple types (not constructed types)
    return ( typeof oObj === "boolean")?'Boolean':
           ( typeof oObj === "number")?'Number':
           ( typeof oObj === "string")?'String':
           ( typeof oObj === "function")?'Function':false;

}; 

Examples:

function MyObject() {}; // Just for example

console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() );         // Function
console.log( getType( {} ));                    // Object
console.log( getType( [] ));                    // Array
console.log( getType( new MyObject() ));        // MyObject

var bTest = false,
    uAny,  // Is undefined
    fTest  function() {};

 // Non constructed standard types
console.log( getType( bTest ));                 // Boolean
console.log( getType( 1.00 ));                  // Number
console.log( getType( 2000 ));                  // Number
console.log( getType( 'hello' ));               // String
console.log( getType( "hello" ));               // String
console.log( getType( fTest ));                 // Function
console.log( getType( uAny ));                  // false, cannot produce
                                                // a string

Low cost and simple.

How to modify a specified commit?

For me it was for removing some credentials from a repo. I tried rebasing and ran into a ton of seemingly unrelated conflicts along the way when trying to rebase --continue. Don't bother attempting to rebase yourself, use the tool called BFG (brew install bfg) on mac.

Trying to create a file in Android: open failed: EROFS (Read-only file system)

Adding

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

in manifest and using same as Martin:

path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); 
File file = new File(path, "/" + fname);

It worked.

How do you check if a JavaScript Object is a DOM Object?

How about Lo-Dash's _.isElement?

$ npm install lodash.iselement

And in the code:

var isElement = require("lodash.iselement");
isElement(document.body);

HTML5 textarea placeholder not appearing

Well, technically it does not have to be on the same line as long as there is no character between the ending ">" from start tag and the starting "<" from the closing tag. That is you need to end with ...></textarea> as in the example below:

<p><label>Comments:<br>
       <textarea id = "comments" rows = "4" cols = "36" 
            placeholder = "Enter comments here"
            class = "valid"></textarea>
    </label>
</p>

Change the value in app.config file dynamically

You have to update your app.config file manually

// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

// Do whatever you need, like modifying the appSettings section

// Save the new setting
xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

And then tell your application to reload any section you modified

ConfigurationManager.RefreshSection("appSettings");

Rotating a Div Element in jQuery

I doubt you can rotate an element using DOM/CSS. Your best bet would be to render to a canvas and rotate that (not sure on the specifics).

Regular Expression Match to test for a valid year

you can go with sth like [^-]\d{4}$: you prevent the minus sign - to be before your 4 digits.
you can also use ^\d{4}$ with ^ to catch the beginning of the string. It depends on your scenario actually...

Generate Java classes from .XSD files...?

To expand on the "use JAXB" comments above,

In Windows "%java_home%\bin\xjc" -p [your namespace] [xsd_file].xsd

e.g., "%java_home%\bin\xjc" -p com.mycompany.quickbooks.obj quickbooks.xsd

Wait a bit, and if you had a well-formed XSD file, you will get some well-formed Java classes

How to move screen without moving cursor in Vim?

I wrote a plugin which enables me to navigate the file without moving the cursor position. It's based on folding the lines between your position and your target position and then jumping over the fold, or abort it and don't move at all.

It's also easy to fast-switch between the cursor on the first line, the last line and cursor in the middle by just clicking j, k or l when you are in the mode of the plugin.

I guess it would be a good fit here.

MySQL compare DATE string with string from DATETIME field

If you want to select all rows where the DATE part of a DATETIME column matches a certain literal, you cannot do it like so:

WHERE startTime = '2010-04-29'

because MySQL cannot compare a DATE and a DATETIME directly. What MySQL does, it extends the given DATE literal with the time '00:00:00'. So your condition becomes

WHERE startTime = '2010-04-29 00:00:00'

Certainly not what you want!

The condition is a range and hence it should be given as range. There are several possibilities:

WHERE startTime BETWEEN '2010-04-29 00:00:00' AND '2010-04-29 23:59:59'
WHERE startTime >= '2010-04-29' AND startTime < ('2010-04-29' + INTERVAL 1 DAY)

There is a tiny possibility for the first to be wrong - when your DATETIME column uses subsecond resolution and there is an appointment at 23:59:59 + epsilon. In general I suggest to use the second variant.

Both variants can use an index on startTime which will become important when the table grows.

How to kill a process in MacOS?

I have experienced that if kill -9 PID doesn't work and you own the process, you can use kill -s kill PID which is kind of surprising as the man page says you can kill -signal_number PID.

How to change color of ListView items on focus and on click

<selector xmlns:android="http://schemas.android.com/apk/res/android" >    
    <item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" /> 
    <item android:drawable="@drawable/YOUR DRAWABLE XML" />
</selector>

Opening new window in HTML for target="_blank"

You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.

How to delete a file or folder?

My personal preference is to work with pathlib objects - it offers a more pythonic and less error-prone way to interact with the filesystem, especially if You develop cross-platform code.

In that case, You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.10.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like "copy", "copy2", "copytree", "rmtree" etc ...

It also wraps shutil.rmtree:

$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib

# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)

# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)

you can find it on github or PyPi


Disclaimer: I'm the author of the pathlib3x library.

jquery .live('click') vs .click()

remember that the use of "live" is for "jQuery 1.3" or higher

in version "jQuery 1.4.3" or higher is used "delegate"

and version "jQuery 1.7 +" or higher is used "on"

$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+

As of jQuery 1.7, the .live() method is deprecated.

check http://api.jquery.com/live/

Regards, Fernando

Selenium Webdriver submit() vs click()

Neither submit() nor click() is good enough. However, it works fine if you follow it with an ENTER key:

search_form = driver.find_element_by_id(elem_id)
search_form.send_keys(search_string)
search_form.click()
from selenium.webdriver.common.keys import Keys
search_form.send_keys(Keys.ENTER)

Tested on Mac 10.11, python 2.7.9, Selenium 2.53.5. This runs in parallel, meaning returns after entering the ENTER key, doesn't wait for page to load.

Inline style to act as :hover in CSS

I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.

I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it

Edit: I just did a quick test with this:

<a href="test.html" style="{color: blue; background: white} 
            :visited {color: green}
            :hover {background: yellow}
            :visited:hover {color: purple}">Test</a>

And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?

Make multiple-select to adjust its height to fit options without scroll bar

Here is a sample package usage, which is quite popular in Laravel community:

{!! Form::select('subdomains[]', $subdomains, null, [
    'id' => 'subdomains',
    'multiple' => true,
    'size' => $subdomains->count(),
    'class' => 'col-12 col-md-4 form-control '.($errors->has('subdomains') ? 'is-invalid' : ''),
]) !!}

Package: https://laravelcollective.com/

JavaScript TypeError: Cannot read property 'style' of null

I met the same problem, the situation is I need to download flash game by embed tag and H5 game by iframe, I need a loading box there, when the flash or H5 download done, let the loading box display none. well, the flash one work well but when things go to iframe, I cannot find the property 'style' of null , so I add a clock to it , and it works

let clock = setInterval(() => {
        clearInterval(clock)
        clock = null
        document.getElementById('loading-box').style.display = 'none'
    }, 200)

How to re import an updated package while in Python Interpreter?

See here for a good explanation of how your dependent modules won't be reloaded and the effects that can have:

http://pyunit.sourceforge.net/notes/reloading.html

The way pyunit solved it was to track dependent modules by overriding __import__ then to delete each of them from sys.modules and re-import. They probably could've just reload'ed them, though.

Setting the User-Agent header for a WebClient request

const string ua = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
Request.Headers["User-Agent"] = ua;
var httpWorkerRequestField = Request.GetType().GetField("_wr", BindingFlags.Instance | BindingFlags.NonPublic);
if (httpWorkerRequestField != null)
{
    var httpWorkerRequest = httpWorkerRequestField.GetValue(Request);
    var knownRequestHeadersField = httpWorkerRequest.GetType().GetField("_knownRequestHeaders", BindingFlags.Instance | BindingFlags.NonPublic);
    if (knownRequestHeadersField != null)
    {
        string[] knownRequestHeaders = (string[])knownRequestHeadersField.GetValue(httpWorkerRequest);
                    knownRequestHeaders[39] = ua;
    }
}

printing all contents of array in C#

There are many ways to do it, the other answers are good, here's an alternative:

Console.WriteLine(string.Join("\n", myArrayOfObjects));

Changing the Git remote 'push to' default

To change which upstream remote is "wired" to your branch, use the git branch command with the upstream configuration flag.

Ensure the remote exists first:

git remote -vv

Set the preferred remote for the current (checked out) branch:

git branch --set-upstream-to <remote-name>

Validate the branch is setup with the correct upstream remote:

git branch -vv

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

Parse rfc3339 date strings in Python?

You can use dateutil.parser.parse (install with python -m pip install python-dateutil) to parse strings into datetime objects.

dateutil.parser.parse will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime which you supply a format string to (see Brent Washburne's answer).

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

print(b.weekday())
# 1 (equal to a Tuesday)

Load jQuery with Javascript and use jQuery

There is an other way to load jQuery dynamically (source). You could also use

document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>');

It's considered bad practice to use document.write, but for sake of completion it's good to mention it.

See Why is document.write considered a "bad practice"? for the reasons. The pro is that document.write does block your page from loading other assests, so there is no need to create a callback function.

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

check if your field with the primary key is set to auto increment

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Some convenience functions:

public static void silentCloseResultSets(Statement st) {
    try {
        while (!(!st.getMoreResults() && (st.getUpdateCount() == -1))) {}
    } catch (SQLException ignore) {}
}
public static void silentCloseResultSets(Statement ...statements) {
    for (Statement st: statements) silentCloseResultSets(st);
}

How do I get Month and Date of JavaScript in 2 digit format?

currentDate(){
        var today = new Date();
        var dateTime =  today.getFullYear()+'-'+
                        ((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
                        (today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
                        (today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
                        (today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
                        (today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());        
            return dateTime;
},

SQL Server - find nth occurrence in a string

DECLARE @x VARCHAR(32) = 'MS-SQL-Server';

SELECT 
SUBSTRING(@x,0,CHARINDEX('-',LTRIM(RTRIM(@x)))) A,
SUBSTRING(@x,CHARINDEX('-',LTRIM(RTRIM(@x)))+1,CHARINDEX('-' 
,LTRIM(RTRIM(@x)))) B,
SUBSTRING(@x,CHARINDEX('-',REVERSE(LTRIM(RTRIM(@x))))+1,LEN(@x)-1) C


A   B   C
MS  SQL Server

jQuery show/hide not working

Demo

_x000D_
_x000D_
$( '.expand' ).click(function() {_x000D_
  $( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
    margin-left:auto;_x000D_
    margin-right:auto;_x000D_
    width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
    height:20px;_x000D_
    background-color:#CCC;_x000D_
    display:block;_x000D_
    border:#333 solid 1px;_x000D_
    margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
 float:right;_x000D_
 height: 100%;_x000D_
 padding-right:5px;_x000D_
 cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
    width: 100%;_x000D_
    height:100px;   _x000D_
    background-color:#0F3;_x000D_
    margin-top: -2px;_x000D_
    display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://api.jquery.com/toggle/
"Display or hide the matched elements."

This is much shorter in code than using show() and hide() methods.

python numpy machine epsilon

Another easy way to get epsilon is:

In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16

Multiple Where clauses in Lambda expressions

You can include it in the same where statement with the && operator...

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty 
    && l.InternalName != String.Empty)

You can use any of the comparison operators (think of it like doing an if statement) such as...

List<Int32> nums = new List<int>();

nums.Add(3);
nums.Add(10);
nums.Add(5);

var results = nums.Where(x => x == 3 || x == 10);

...would bring back 3 and 10.

Maven Java EE Configuration Marker with Java Server Faces 1.2

I too had the same problem.

The solution for me was to add following in the pom.xml as suggested here.

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.0.2</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

How to bind DataTable to Datagrid

You could use DataGrid in WPF

SqlDataAdapter da = new SqlDataAdapter("Select * from Table",con);
DataTable dt = new DataTable("Call Reciept");
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.ItemsSource = dt.DefaultView;

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Angular 2: Get Values of Multiple Checked Checkboxes

Since I spent a long time solving a similar problem, I'm answering to share my experience. My problem was the same, to know, getting many checkboxes value after a specified event has been triggered. I tried a lot of solutions but for me the sexiest is using ViewChildren.

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components: QueryList<any>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

Found here: https://stackoverflow.com/a/40165639/4775727

Potential other solutions for ref, there are a lot of similar topic, none of them purpose this solution...:

The requested resource does not support HTTP method 'GET'

I was experiencing the same issue.. I already had 4 controllers going and working just fine but when I added this one it returned "The requested resource does not support HTTP method 'GET'". I tried everything here and in a couple other relevant articles but was indifferent to the solution since, as Dan B. mentioned in response to the answer, I already had others working fine.

I walked away for a while, came back, and immediately realized that when I added the Controller it was nested under the "Controller" class and not "ApiController" class that my other Controllers were under. I'm assuming I chose the wrong scaffolding option to build the .cs file in Visual Studio. So I included the System.Web.Http namespace, changed the parent class, and everything works without the additional attributes or routing.

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

I feel like this has been well covered, maybe except for the following:

  • Simple KEY / INDEX (or otherwise called SECONDARY INDEX) do increase performance if selectivity is sufficient. On this matter, the usual recommendation is that if the amount of records in the result set on which an index is applied exceeds 20% of the total amount of records of the parent table, then the index will be ineffective. In practice each architecture will differ but, the idea is still correct.

  • Secondary Indexes (and that is very specific to mysql) should not be seen as completely separate and different objects from the primary key. In fact, both should be used jointly and, once this information known, provide an additional tool to the mysql DBA: in Mysql, indexes embed the primary key. It leads to significant performance improvements, specifically when cleverly building implicit covering indexes such as described there.

  • If you feel like your data should be UNIQUE, use a unique index. You may think it's optional (for instance, working it out at application level) and that a normal index will do, but it actually represents a guarantee for Mysql that each row is unique, which incidentally provides a performance benefit.

  • You can only use FULLTEXT (or otherwise called SEARCH INDEX) with Innodb (In MySQL 5.6.4 and up) and Myisam Engines

  • You can only use FULLTEXT on CHAR, VARCHAR and TEXT column types

  • FULLTEXT index involves a LOT more than just creating an index. There's a bunch of system tables created, a completely separate caching system and some specific rules and optimizations applied. See http://dev.mysql.com/doc/refman/5.7/en/fulltext-restrictions.html and http://dev.mysql.com/doc/refman/5.7/en/innodb-fulltext-index.html

How do I vertically align text in a div?

You can do this by setting the display to 'table-cell' and applying a vertical-align: middle;:

    {
        display: table-cell;
        vertical-align: middle;
    }

This is however not supported by all versions of Internet Explorer according to this excerpt I copied from http://www.w3schools.com/cssref/pr_class_display.asp without permission.

Note: The values "inline-table", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row-group", and "inherit" are not supported by Internet Explorer 7 and earlier. Internet Explorer 8 requires a !DOCTYPE. Internet Explorer 9 supports the values.

The following table shows the allowed display values also from http://www.w3schools.com/cssref/pr_class_display.asp.

Enter image description here

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

How to use EOF to run through a text file in C?

One possible C loop would be:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        /*
        ** Do something with c, such as check against '\n'
        ** and increment a line counter.
        */
    }
}

For now, I would ignore feof and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.

Pitfall to avoid: using char for the type of c. getchar returns the next character cast to an unsigned char and then to an int. This means that on most [sane] platforms the value of EOF and valid "char" values in c don't overlap so you won't ever accidentally detect EOF for a 'normal' char.

"Full screen" <iframe>

You can use this piece of code:

  <iframe src="http://example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0%;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

The find command may help

find $PWD -name ex*
find $PWD -name example.log

Lists all the files in or below the current directory with names matching the pattern. You can simplify it if you will only get a few results (e.g. directory near bottom of tree containing few files), just

find $PWD

I use this on Solaris 10, which doesn't have the other utilities mentioned.

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

My issue was that my method was missing the @RequestBody annotation. After adding the annotation I no longer received the 404 exception.

Environment variable to control java.io.tmpdir?

It isn't an environment variable, but still gives you control over the temp dir:

-Djava.io.tmpdir

ex.:

java -Djava.io.tmpdir=/mytempdir

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

How to find files that match a wildcard string in Java?

You could convert your wildcard string to a regular expression and use that with String's matches method. Following your example:

String original = "../Test?/sample*.txt";
String regex = original.replace("?", ".?").replace("*", ".*?");

This works for your examples:

Assert.assertTrue("../Test1/sample22b.txt".matches(regex));
Assert.assertTrue("../Test4/sample-spiffy.txt".matches(regex));

And counter-examples:

Assert.assertTrue(!"../Test3/sample2.blah".matches(regex));
Assert.assertTrue(!"../Test44/sample2.txt".matches(regex));

Maximum filename length in NTFS (Windows XP and Windows Vista)?

This is what the "Unhandled exception" says on framework 4.5 when trying to save a file with a long filename:

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

screenshot

Switch statement: must default be the last case?

One scenario where I would consider it appropriate to have a 'default' located somewhere other than the end of a case statement is in a state machine where an invalid state should reset the machine and proceed as though it were the initial state. For example:

switch(widget_state)
{
  default:  /* Fell off the rails--reset and continue */
    widget_state = WIDGET_START;
    /* Fall through */
  case WIDGET_START:
    ...
    break;
  case WIDGET_WHATEVER:
    ...
    break;
}

an alternative arrangement, if an invalid state should not reset the machine but should be readily identifiable as an invalid state:

switch(widget_state) { case WIDGET_IDLE: widget_ready = 0; widget_hardware_off(); break; case WIDGET_START: ... break; case WIDGET_WHATEVER: ... break; default: widget_state = WIDGET_INVALID_STATE; /* Fall through */ case WIDGET_INVALID_STATE: widget_ready = 0; widget_hardware_off(); ... do whatever else is necessary to establish a "safe" condition }

Code elsewhere may then check for (widget_state == WIDGET_INVALID_STATE) and provide whatever error-reporting or state-reset behavior seems appropriate. For example, the status-bar code could show an error icon, and the "start widget" menu option which is disabled in most non-idle states could be enabled for WIDGET_INVALID_STATE as well as WIDGET_IDLE.

To show only file name without the entire directory path

Use the basename command:

basename /home/user/new/*.txt

How to add `style=display:"block"` to an element using jQuery?

Depending on the purpose of setting the display property, you might want to take a look at

$("#yourElementID").show()

and

$("#yourElementID").hide()

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

First is you have to understand the difference between MyISAM and InnoDB Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:

 ALTER TABLE t1 ENGINE=MyISAM;

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

The latest version of sqlcmd adds the -w option to remove extra space after the field value; however, it does not put quotes around strings, which can be a problem with CSV files when importing a field value that contains a comma.

Why does jQuery or a DOM method such as getElementById not find the element?

If script execution order is not the issue, another possible cause of the problem is that the element is not being selected properly:

  • getElementById requires the passed string to be the ID verbatim, and nothing else. If you prefix the passed string with a #, and the ID does not start with a #, nothing will be selected:

      <div id="foo"></div>
    
      // Error, selected element will be null:
      document.getElementById('#foo')
      // Fix:
      document.getElementById('foo')
    
  • Similarly, for getElementsByClassName, don't prefix the passed string with a .:

      <div class="bar"></div>
    
      // Error, selected element will be undefined:
      document.getElementsByClassName('.bar')[0]
      // Fix:
      document.getElementsByClassName('bar')[0]
    
  • With querySelector, querySelectorAll, and jQuery, to match an element with a particular class name, put a . directly before the class. Similarly, to match an element with a particular ID, put a # directly before the ID:

      <div class="baz"></div>
    
      // Error, selected element will be null:
      document.querySelector('baz')
      $('baz')
      // Fix:
      document.querySelector('.baz')
      $('.baz')
    

    The rules here are, in most cases, identical to those for CSS selectors, and can be seen in detail here.

  • To match an element which has two or more attributes (like two class names, or a class name and a data- attribute), put the selectors for each attribute next to each other in the selector string, without a space separating them (because a space indicates the descendant selector). For example, to select:

      <div class="foo bar"></div>
    

    use the query string .foo.bar. To select

      <div class="foo" data-bar="someData"></div>
    

    use the query string .foo[data-bar="someData"]. To select the <span> below:

      <div class="parent">
        <span data-username="bob"></span>
      </div>
    

    use div.parent > span[data-username="bob"].

  • Capitalization and spelling does matter for all of the above. If the capitalization is different, or the spelling is different, the element will not be selected:

      <div class="result"></div>
    
      // Error, selected element will be null:
      document.querySelector('.results')
      $('.Result')
      // Fix:
      document.querySelector('.result')
      $('.result')
    
  • You also need to make sure the methods have the proper capitalization and spelling. Use one of:

    $(selector)
    document.querySelector
    document.querySelectorAll
    document.getElementsByClassName
    document.getElementsByTagName
    document.getElementById
    

    Any other spelling or capitalization will not work. For example, document.getElementByClassName will throw an error.

  • Make sure you pass a string to these selector methods. If you pass something that isn't a string to querySelector, getElementById, etc, it almost certainly won't work.

  • If the HTML attributes on elements you want to select are surrounded by quotes, they must be plain straight quotes (either single or double); curly quotes like or will not work if you're trying to select by ID, class, or attribute.

Empty set literal?

Yes. The same notation that works for non-empty dict/set works for empty ones.

Notice the difference between non-empty dict and set literals:

{1: 'a', 2: 'b', 3: 'c'} -- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'} -- a tuple of values inside makes a set

So:

{} == zero number of key-value pairs == empty dict
{*()} == empty tuple of values == empty set

However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:

a = set()

Performance:

The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):

>>> %timeit ({*()} & {*()}) | {*()}
214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

>>> %timeit (set() & set()) | set()
252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

... and for completeness, Renato Garcia's frozenset proposal on the above expression is some 60% faster!

>>> ? = frozenset()

>>> %timeit (? & ?) | ?
100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

NB: As ctrueden noticed in comments, {()} is not an empty set. It's a set with 1 element: empty tuple.

How to debug "ImagePullBackOff"?

On GKE, if the pod is dead, it's best to check for the events. It will show in more detail what the error is about.

In my case, I had :

Failed to pull image "gcr.io/project/imagename@sha256:c8e91af54fc17faa1c49e2a05def5cbabf8f0a67fc558eb6cbca138061a8400a":
 rpc error: code = Unknown desc = error pulling image configuration: unknown blob

It turned out the image was damaged somehow. After repushing it and deploying with the new hash, it worked again.

Does reading an entire file leave the file handle open?

Well, if you have to read file line by line to work with each line, you can use

with open('Path/to/file', 'r') as f:
    s = f.readline()
    while s:
        # do whatever you want to
        s = f.readline()

Or even better way:

with open('Path/to/file') as f:
    for line in f:
        # do whatever you want to

Trim last character from a string

Slightly modified version of @Damian Leszczynski - Vash that will make sure that only a specific character will be removed.

public static class StringExtensions
{
    public static string TrimLastCharacter(this string str, char character)
    {
        if (string.IsNullOrEmpty(str) || str[str.Length - 1] != character)
        {
            return str;
        }
        return str.Substring(0, str.Length - 1);
    }
}

The name does not exist in the namespace error in XAML

This problem can also be caused if the assembly that you're referencing isn't actually built. For example, if your xaml is in Assembly1 and you're referencing a class also in Assembly1, but that assembly has errors and isn't building, this error will be shown.

I feel silly about it, but in my case I was tearing asunder a user control and had all sorts of errors in the related classes as a result. As I was attempting to fix them all I started with the errors in question, not realising that xaml relies on built assemblies to find these references (unlike c#/vb code which can work it out even before you build).

What is the difference between window, screen, and document in Javascript?

Window is the main JavaScript object root, aka the global object in a browser, also can be treated as the root of the document object model. You can access it as window

window.screen or just screen is a small information object about physical screen dimensions.

window.document or just document is the main object of the potentially visible (or better yet: rendered) document object model/DOM.

Since window is the global object you can reference any properties of it with just the property name - so you do not have to write down window. - it will be figured out by the runtime.

JavaScript/jQuery: replace part of string?

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

Attach event to dynamic elements in javascript

I have created a small library to help with this: Library source on GitHub

<script src="dynamicListener.min.js"></script>
<script>
// Any `li` or element with class `.myClass` will trigger the callback, 
// even elements created dynamically after the event listener was created.
addDynamicEventListener(document.body, 'click', '.myClass, li', function (e) {
    console.log('Clicked', e.target.innerText);
});
</script>

The functionality is similar to jQuery.on().

The library uses the Element.matches() method to test the target element against the given selector. When an event is triggered the callback is only called if the target element matches the selector given.

Getting 400 bad request error in Jquery Ajax POST

Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object. So the correct version is here:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: JSON.stringify({
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  }),
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

May be it will help someone else.

No value accessor for form control

For anyone experiencing this in angular 9+

This issue can also be experienced if you do not declare or import the component that declares your component.

Lets consider a situation where you intend to use ng-select but you forget to import it Angular will throw the error 'No value accessor...'

I have reproduced this error in the Below stackblitz demo.

Python division

Make at least one of them float, then it will be float division, not integer:

>>> (20.0-10) / (100-10)
0.1111111111111111

Casting the result to float is too late.

Return a value of '1' a referenced cell is empty

=if(a1="","1","0")

In this formula if the cell is empty then the result would be 1 else it would be 0

Using msbuild to execute a File System Publish Profile

Run from the project folder

msbuild /p:DeployOnBuild=true /p:PublishProfile="release-file.pubxml" /p:AspnetMergePath="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools" /p:Configuration=Release

This takes care of web.config Transform and AspnetMergePath

List passed by ref - help me explain this behaviour

Initially, it can be represented graphically as follow:

Init states

Then, the sort is applied myList.Sort(); Sort collection

Finally, when you did: myList' = myList2, you lost the one of the reference but not the original and the collection stayed sorted.

Lost reference

If you use by reference (ref) then myList' and myList will become the same (only one reference).

Note: I use myList' to represent the parameter that you use in ChangeList (because you gave the same name as the original)

How to read input with multiple lines in Java

The easilest way is

import java.util.*;

public class Stdio4 {

public static void main(String[] args) {
    int a=0;
    int arr[] = new int[3];
    Scanner scan = new Scanner(System.in);
    for(int i=0;i<3;i++)
    { 
         a = scan.nextInt();  //Takes input from separate lines
         arr[i]=a;


    }
    for(int i=0;i<3;i++)
    { 
         System.out.println(arr[i]);   //outputs in separate lines also
    }

}

}

React Native TextInput that only accepts numeric characters

For Decimal /Floating point number only try this

    onChangeMyFloatNumber(text){
let newText = '';
let numbers = '0123456789.';

for (var i=0; i < text.length; i++) {
    if(numbers.indexOf(text[i]) > -1 ) {
        newText = newText + text[i];
        if(text[i]=="."){
          numbers = '0123456789'
        }
    }
    else {
        // your call back function
        alert("please enter numbers only");
    }
}
this.setState({ MyFloatNumber: newText });

}

Replace one character with another in Bash

Try this for paths:

echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'

It replaces the space inside the double-quoted string with a + sing, then replaces the + sign with a backslash, then removes/replaces the double-quotes.

I had to use this to replace the spaces in one of my paths in Cygwin.

echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'

How can I hide select options with JavaScript? (Cross browser)

I thought I was bright ;-)

In CSS:

option:disabled {display:none;}

In Firefox and Chrome, a select with only the enabled options were created. Nice.

In IE, the enabled options were shown, the disabled where just blank lines, in their original location. Bad.

In Edge, the enabled options shown at top, followed by blank lines for disabled options. Acceptable.

PHP date() format when inserting into datetime in MySQL

I use the following PHP code to create a variable that I insert into a MySQL DATETIME column.

$datetime = date_create()->format('Y-m-d H:i:s');

This will hold the server's current Date and Time.

Error: Unable to run mksdcard SDK tool

This worked for me on Ubuntu 15.04

sudo aptitude install lib32stdc++6

Firstly, I installed aptitude, which helps in installing other dependencies too.

Determine if Python is running inside virtualenv

  • Updated Nov 2019 (appended).

I routinely use several Anaconda-installed virtual environments (venv). This code snippet/examples enables you to determine whether or not you are in a venv (or your system environment), and to also require a specific venv for your script.

Add to Python script (code snippet):

# ----------------------------------------------------------------------------
# Want script to run in Python 3.5 (has required installed OpenCV, imutils, ... packages):
import os

# First, see if we are in a conda venv { py27: Python 2.7 | py35: Python 3.5 | tf: TensorFlow | thee : Theano }
try:
   os.environ["CONDA_DEFAULT_ENV"]
except KeyError:
   print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
   exit()

# If we are in a conda venv, require the p3 venv:
if os.environ['CONDA_DEFAULT_ENV'] != "py35":
    print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
    exit()

# See also:
# Python: Determine if running inside virtualenv
# http://stackoverflow.com/questions/1871549/python-determine-if-running-inside-virtualenv  
# [ ... SNIP! ... ]

Example:

$ p2
  [Anaconda Python 2.7 venv (source activate py27)]

(py27) $ python  webcam_.py
    Please set the py35 { p3 | Python 3.5 } environment!

(py27) $ p3
  [Anaconda Python 3.5 venv (source activate py35)]

(py35) $ python  webcam.py -n50

    current env: py35
    processing (live): found 2 faces and 4 eyes in this frame
    threaded OpenCV implementation
    num_frames: 50
    webcam -- approx. FPS: 18.59
    Found 2 faces and 4 eyes!
(py35) $

Update 1 -- use in bash scripts:

You can also use this approach in bash scripts (e.g., those that must run in a specific virtual environment). Example (added to bash script):

if [ $CONDA_DEFAULT_ENV ]        ## << note the spaces (important in BASH)!
    then
        printf 'venv: operating in tf-env, proceed ...'
    else
        printf 'Note: must run this script in tf-env venv'
        exit
fi

Update 2 [Nov 2019]

Since my original post I've moved on from Anaconda venv (and Python itself has evolved viz-a-viz virtual environments).

Reexamining this issue, here is some updated Python code that you can insert to test that you are operating in a specific Python virtual environment (venv).

import os, re
try:
    if re.search('py37', os.environ['VIRTUAL_ENV']):
        pass
except KeyError:
    print("\n\tPlease set the Python3 venv [alias: p3]!\n")
    exit()

Here is some explanatory code.

[victoria@victoria ~]$ date; python --version
  Thu 14 Nov 2019 11:27:02 AM PST
  Python 3.8.0

[victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re

>>> re.search('py37', os.environ['VIRTUAL_ENV'])
<re.Match object; span=(20, 24), match='py37'>

>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Please set the Python3 venv [alias: p3]!

>>> [Ctrl-d]
  now exiting EditableBufferInteractiveConsole...

[victoria@victoria ~]$ p3
  [Python 3.7 venv (source activate py37)]

(py37) [victoria@victoria ~]$ python --version
  Python 3.8.0

(py37) [victoria@victoria ~]$ env | grep -i virtual
  VIRTUAL_ENV=/home/victoria/venv/py37

(py37) [victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re
>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Operating in Python3 venv, please proceed!  :-)
>>> 

How can I split a text file using PowerShell?

This is a somewhat easy task for PowerShell, complicated by the fact that the standard Get-Content cmdlet doesn't handle very large files too well. What I would suggest to do is use the .NET StreamReader class to read the file line by line in your PowerShell script and use the Add-Content cmdlet to write each line to a file with an ever-increasing index in the filename. Something like this:

$upperBound = 50MB # calculated by Powershell
$ext = "log"
$rootName = "log_"

$reader = new-object System.IO.StreamReader("C:\Exceptions.log")
$count = 1
$fileName = "{0}{1}.{2}" -f ($rootName, $count, $ext)
while(($line = $reader.ReadLine()) -ne $null)
{
    Add-Content -path $fileName -value $line
    if((Get-ChildItem -path $fileName).Length -ge $upperBound)
    {
        ++$count
        $fileName = "{0}{1}.{2}" -f ($rootName, $count, $ext)
    }
}

$reader.Close()

Shell script : How to cut part of a string

A perl-solution:

perl -nE 'say $1 if /id=(\d+)/' filename

How to detect if CMD is running as Administrator/has elevated privileges?

I know I'm really late to this party, but here's my one liner to determine admin-hood.

It doesn't rely on error level, just on systeminfo:

for /f "tokens=1-6" %%a in ('"net user "%username%" | find /i "Local Group Memberships""') do (set admin=yes & if not "%%d" == "*Administrators" (set admin=no) & echo %admin%)

It returns either yes or no, depending on the user's admin status...

It also sets the value of the variable "admin" to equal yes or no accordingly.

How to convert a plain object into an ES6 Map?

The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:

Converting an Object to a Map

The new Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

const obj = { foo: 'bar', baz: 42 }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Sum of Numbers C++

First, you have two variables of the same name i. This calls for confusion.

Second, you should declare a variable called sum, which is initially zero. Then, in a loop, you should add to it the numbers from 1 upto and including positiveInteger. After that, you should output the sum.

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

How to include a quote in a raw Python string

Just to include new Python f String compatible functionality:

var_a = 10

f"""This is my quoted variable: "{var_a}". """

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

Replace words in the body text

I was trying to replace a really large string and for some reason regular expressions were throwing some errors/exceptions.

So I found this alternative to regular expressions which also runs pretty fast. At least it was fast enough for me:

var search = "search string";
var replacement = "replacement string";

document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)

src: How to replace all occurrences of a string in JavaScript?

Angular2 router (@angular/router), how to set default route?

V2.0.0 and later

See also see https://angular.io/guide/router#the-default-route-to-heroes

RouterConfig = [
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '', redirectTo: '/detail', pathMatch: 'full' },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

There is also the catch-all route

{ path: '**', redirectTo: '/heroes', pathMatch: 'full' },

which redirects "invalid" urls.

V3-alpha (vladivostok)

Use path / and redirectTo

RouterConfig = [
  { path: '/', redirectTo: 'heroes', terminal: true },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '/', redirectTo: 'detail', terminal: true },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

RC.1 @angular/router

The RC router doesn't yet support useAsDefault. As a workaround you can navigate explicitely.

In the root component

export class AppComponent {
  constructor(router:Router) {
    router.navigate(['/Merge']);
  }
}

for other components

export class OtherComponent {
  constructor(private router:Router) {}

  routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
    this.router.navigate(['SomeRoute'], curr);
  }
}

What represents a double in sql server?

float

Or if you want to go old-school:

real

You can also use float(53), but it means the same thing as float.

("real" is equivalent to float(24), not float/float(53).)

The decimal(x,y) SQL Server type is for when you want exact decimal numbers rather than floating point (which can be approximations). This is in contrast to the C# "decimal" data type, which is more like a 128-bit floating point number.

MSSQL's float type is equivalent to the 64-bit double type in .NET. (My original answer from 2011 said there could be a slight difference in mantissa, but I've tested this in 2020 and they appear to be 100% compatible in their binary representation of both very small and very large numbers -- see https://dotnetfiddle.net/wLX5Ox for my test).

To make things more confusing, a "float" in C# is only 32-bit, so it would be more equivalent in SQL to the real/float(24) type in MSSQL than float/float(53).

In your specific use case... All you need is 5 places after the decimal point to represent latitude and longitude within about one-meter precision, and you only need up to three digits before the decimal point for the degrees. Float(24) or decimal(8,5) will best fit your needs in MSSQL, and using float in C# is good enough, you don't need double. In fact, your users will probably thank you for rounding to 5 decimal places rather than having a bunch of insignificant digits coming along for the ride.

How to trigger jQuery change event in code

The parameterless form of the change() method triggers a change event. You can write something like:

$(document).ready(function() {
    $("#yourInitialElementID").change(function() {
        // Do something here...
        $(".yourDropDownClass").change();
    });
});

Jenkins - How to access BUILD_NUMBER environment variable

For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.

Tooltips for cells in HTML table (no Javascript)

if (data[j] =='B'){
    row.cells[j].title="Basic";
}

In Java script conditionally adding title by comparing value of Data. The Table is generated by Java script dynamically.

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

It was not asked precisely to remove accent (only special characters), but I needed to.

The solutions givens here works but they don’t remove accent: é, è, etc.

So, before doing epascarello’s solution, you can also do:

_x000D_
_x000D_
var newString = "développeur & intégrateur";_x000D_
_x000D_
newString = replaceAccents(newString);_x000D_
newString = newString.replace(/[^A-Z0-9]+/ig, "_");_x000D_
alert(newString);_x000D_
_x000D_
/**_x000D_
 * Replaces all accented chars with regular ones_x000D_
 */_x000D_
function replaceAccents(str) {_x000D_
  // Verifies if the String has accents and replace them_x000D_
  if (str.search(/[\xC0-\xFF]/g) > -1) {_x000D_
    str = str_x000D_
      .replace(/[\xC0-\xC5]/g, "A")_x000D_
      .replace(/[\xC6]/g, "AE")_x000D_
      .replace(/[\xC7]/g, "C")_x000D_
      .replace(/[\xC8-\xCB]/g, "E")_x000D_
      .replace(/[\xCC-\xCF]/g, "I")_x000D_
      .replace(/[\xD0]/g, "D")_x000D_
      .replace(/[\xD1]/g, "N")_x000D_
      .replace(/[\xD2-\xD6\xD8]/g, "O")_x000D_
      .replace(/[\xD9-\xDC]/g, "U")_x000D_
      .replace(/[\xDD]/g, "Y")_x000D_
      .replace(/[\xDE]/g, "P")_x000D_
      .replace(/[\xE0-\xE5]/g, "a")_x000D_
      .replace(/[\xE6]/g, "ae")_x000D_
      .replace(/[\xE7]/g, "c")_x000D_
      .replace(/[\xE8-\xEB]/g, "e")_x000D_
      .replace(/[\xEC-\xEF]/g, "i")_x000D_
      .replace(/[\xF1]/g, "n")_x000D_
      .replace(/[\xF2-\xF6\xF8]/g, "o")_x000D_
      .replace(/[\xF9-\xFC]/g, "u")_x000D_
      .replace(/[\xFE]/g, "p")_x000D_
      .replace(/[\xFD\xFF]/g, "y");_x000D_
  }_x000D_
_x000D_
  return str;_x000D_
}
_x000D_
_x000D_
_x000D_

Source: https://gist.github.com/jonlabelle/5375315

Getting HTTP headers with Node.js

I had some problems with http.get; so I switched to the lib request:

var request = require('request');

var url = 'http://blog.mynotiz.de/';

var options = {
    url: url,
    method: 'HEAD'
};

request(options, function (error, response, body) {
        if (error) {
            return console.error('upload failed:', error);
        }

        if (response.headers['content-length']) {
            var file_size = response.headers['content-length'];
            console.log(file_size);
        }
    }
);

SQL changing a value to upper or lower case

SELECT UPPER(firstname) FROM Person

SELECT LOWER(firstname) FROM Person

What is the difference between state and props in React?

In React the states store the data as well as the props. Its difference with the latter is that the stored data can be modified by different changes. These are nothing more than objects written in flat JavaScript, so they can contain data or codes, represent the information you want to model. If you need more details it is recommended that you see these publications Use of the State in React and Use of Props in React

What is the shortcut to Auto import all in Android Studio?

Android Studio --> Preferences --> Editors --> Auto Import

  • Checked Optimize imports on the fly option
  • Checked to Add unambiguous imports on the fly option
  • Click Apply and OK button.

How to process POST data in Node.js?

You can use the express middleware, which now has body-parser built into it. This means all you need to do is the following:

import express from 'express'

const app = express()

app.use(express.json())

app.post('/thing', (req, res) => {
  console.log(req.body) // <-- this will access the body of the post
  res.sendStatus(200)
})

That code example is ES6 with Express 4.16.x

Convert wchar_t to char

A short function I wrote a while back to pack a wchar_t array into a char array. Characters that aren't on the ANSI code page (0-127) are replaced by '?' characters, and it handles surrogate pairs correctly.

size_t to_narrow(const wchar_t * src, char * dest, size_t dest_len){
  size_t i;
  wchar_t code;

  i = 0;

  while (src[i] != '\0' && i < (dest_len - 1)){
    code = src[i];
    if (code < 128)
      dest[i] = char(code);
    else{
      dest[i] = '?';
      if (code >= 0xD800 && code <= 0xD8FF)
        // lead surrogate, skip the next code unit, which is the trail
        i++;
    }
    i++;
  }

  dest[i] = '\0';

  return i - 1;

}

Concat all strings inside a List<string> using LINQ

List<string> strings = new List<string>() { "ABC", "DEF", "GHI" };
string s = strings.Aggregate((a, b) => a + ',' + b);

window.print() not working in IE

The way we typically handle printing is to just open the new window with everything in it that needs to be sent to the printer. Then we have the user actually click on their browsers Print button.

This has always been acceptable in the past, and it sidesteps the security restrictions that Chilln is talking about.

How to change permissions for a folder and its subfolders/files in one step?

For Mac OS X 10.7 (Lion), it is:

chmod -R 755 /directory

And yes, as all other say, be careful when doing this.

How to animate button in android?

Dependency

Add it in your root build.gradle at the end of repositories:

allprojects {
repositories {
    ...
    maven { url "https://jitpack.io" }
}}

and then add dependency dependencies { compile 'com.github.varunest:sparkbutton:1.0.5' }

Usage

XML

<com.varunest.sparkbutton.SparkButton
        android:id="@+id/spark_button"
        android:layout_width="40dp"
        android:layout_height="40dp"
        app:sparkbutton_activeImage="@drawable/active_image"
        app:sparkbutton_inActiveImage="@drawable/inactive_image"
        app:sparkbutton_iconSize="40dp"
        app:sparkbutton_primaryColor="@color/primary_color"
        app:sparkbutton_secondaryColor="@color/secondary_color" />

Java (Optional)

SparkButton button  = new SparkButtonBuilder(context)
            .setActiveImage(R.drawable.active_image)
            .setInActiveImage(R.drawable.inactive_image)
            .setDisabledImage(R.drawable.disabled_image)
            .setImageSizePx(getResources().getDimensionPixelOffset(R.dimen.button_size))
            .setPrimaryColor(ContextCompat.getColor(context, R.color.primary_color))
            .setSecondaryColor(ContextCompat.getColor(context, R.color.secondary_color))
            .build();

How can I get the client's IP address in ASP.NET MVC?

A lot of the code here was very helpful, but I cleaned it up for my purposes and added some tests. Here's what I ended up with:

using System;
using System.Linq;
using System.Net;
using System.Web;

public class RequestHelpers
{
    public static string GetClientIpAddress(HttpRequestBase request)
    {
        try
        {
            var userHostAddress = request.UserHostAddress;

            // Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
            // Could use TryParse instead, but I wanted to catch all exceptions
            IPAddress.Parse(userHostAddress);

            var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(xForwardedFor))
                return userHostAddress;

            // Get a list of public ip addresses in the X_FORWARDED_FOR variable
            var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();

            // If we found any, return the last one, otherwise return the user host address
            return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
        }
        catch (Exception)
        {
            // Always return all zeroes for any failure (my calling code expects it)
            return "0.0.0.0";
        }
    }

    private static bool IsPrivateIpAddress(string ipAddress)
    {
        // http://en.wikipedia.org/wiki/Private_network
        // Private IP Addresses are: 
        //  24-bit block: 10.0.0.0 through 10.255.255.255
        //  20-bit block: 172.16.0.0 through 172.31.255.255
        //  16-bit block: 192.168.0.0 through 192.168.255.255
        //  Link-local addresses: 169.254.0.0 through 169.254.255.255 (http://en.wikipedia.org/wiki/Link-local_address)

        var ip = IPAddress.Parse(ipAddress);
        var octets = ip.GetAddressBytes();

        var is24BitBlock = octets[0] == 10;
        if (is24BitBlock) return true; // Return to prevent further processing

        var is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
        if (is20BitBlock) return true; // Return to prevent further processing

        var is16BitBlock = octets[0] == 192 && octets[1] == 168;
        if (is16BitBlock) return true; // Return to prevent further processing

        var isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
        return isLinkLocalAddress;
    }
}

And here are some NUnit tests against that code (I'm using Rhino Mocks to mock the HttpRequestBase, which is the M<HttpRequestBase> call below):

using System.Web;
using NUnit.Framework;
using Rhino.Mocks;
using Should;

[TestFixture]
public class HelpersTests : TestBase
{
    HttpRequestBase _httpRequest;

    private const string XForwardedFor = "X_FORWARDED_FOR";
    private const string MalformedIpAddress = "MALFORMED";
    private const string DefaultIpAddress = "0.0.0.0";
    private const string GoogleIpAddress = "74.125.224.224";
    private const string MicrosoftIpAddress = "65.55.58.201";
    private const string Private24Bit = "10.0.0.0";
    private const string Private20Bit = "172.16.0.0";
    private const string Private16Bit = "192.168.0.0";
    private const string PrivateLinkLocal = "169.254.0.0";

    [SetUp]
    public void Setup()
    {
        _httpRequest = M<HttpRequestBase>();
    }

    [TearDown]
    public void Teardown()
    {
        _httpRequest = null;
    }

    [Test]
    public void PublicIpAndNullXForwardedFor_Returns_CorrectIp()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void PublicIpAndEmptyXForwardedFor_Returns_CorrectIp()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(string.Empty);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void MalformedUserHostAddress_Returns_DefaultIpAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(MalformedIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(null);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(DefaultIpAddress);
    }

    [Test]
    public void MalformedXForwardedFor_Returns_DefaultIpAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MalformedIpAddress);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(DefaultIpAddress);
    }

    [Test]
    public void SingleValidPublicXForwardedFor_Returns_XForwardedFor()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(MicrosoftIpAddress);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(MicrosoftIpAddress);
    }

    [Test]
    public void MultipleValidPublicXForwardedFor_Returns_LastXForwardedFor()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(GoogleIpAddress + "," + MicrosoftIpAddress);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(MicrosoftIpAddress);
    }

    [Test]
    public void SinglePrivateXForwardedFor_Returns_UserHostAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(Private24Bit);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void MultiplePrivateXForwardedFor_Returns_UserHostAddress()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        const string privateIpList = Private24Bit + "," + Private20Bit + "," + Private16Bit + "," + PrivateLinkLocal;
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(GoogleIpAddress);
    }

    [Test]
    public void MultiplePublicXForwardedForWithPrivateLast_Returns_LastPublic()
    {
        // Arrange
        _httpRequest.Stub(x => x.UserHostAddress).Return(GoogleIpAddress);
        const string privateIpList = Private24Bit + "," + Private20Bit + "," + MicrosoftIpAddress + "," + PrivateLinkLocal;
        _httpRequest.Stub(x => x.ServerVariables[XForwardedFor]).Return(privateIpList);

        // Act
        var ip = RequestHelpers.GetClientIpAddress(_httpRequest);

        // Assert
        ip.ShouldEqual(MicrosoftIpAddress);
    }
}

Pandas: Return Hour from Datetime Column Directly

For posterity: as of 0.15.0, there is a handy .dt accessor you can use to pull such values from a datetime/period series (in the above case, just sales.timestamp.dt.hour!

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

This will work:

DECLARE @MS INT = 235216
select cast(dateadd(ms, @MS, '00:00:00') AS TIME(3))

(where ms is just a number of seconds not a timeformat)

ignoring any 'bin' directory on a git project

Adding **/bin/ to the .gitignore file did the trick for me (Note: bin folder wasn't added to index).

How to convert an NSString into an NSNumber

For strings starting with integers, e.g., @"123", @"456 ft", @"7.89", etc., use -[NSString integerValue].

So, @([@"12.8 lbs" integerValue]) is like doing [NSNumber numberWithInteger:12].

How to left align a fixed width string?

I definitely prefer the format method more, as it is very flexible and can be easily extended to your custom classes by defining __format__ or the str or repr representations. For the sake of keeping it simple, i am using print in the following examples, which can be replaced by sys.stdout.write.

Simple Examples: alignment / filling

#Justify / ALign (left, mid, right)
print("{0:<10}".format("Guido"))    # 'Guido     '
print("{0:>10}".format("Guido"))    # '     Guido'
print("{0:^10}".format("Guido"))    # '  Guido   '

We can add next to the align specifies which are ^, < and > a fill character to replace the space by any other character

print("{0:.^10}".format("Guido"))    #..Guido...

Multiinput examples: align and fill many inputs

print("{0:.<20} {1:.>20} {2:.^20} ".format("Product", "Price", "Sum"))
#'Product............. ...............Price ........Sum.........'

Advanced Examples

If you have your custom classes, you can define it's str or repr representations as follows:

class foo(object):
    def __str__(self):
        return "...::4::.."

    def __repr__(self):
        return "...::12::.."

Now you can use the !s (str) or !r (repr) to tell python to call those defined methods. If nothing is defined, Python defaults to __format__ which can be overwritten as well. x = foo()

print "{0!r:<10}".format(x)    #'...::12::..'
print "{0!s:<10}".format(x)    #'...::4::..'

Source: Python Essential Reference, David M. Beazley, 4th Edition

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Have a look at this for some common errors in setting the java heap. You've probably set the heap size to a larger value than your computer's physical memory.

You should avoid solving this problem by increasing the heap size. Instead, you should profile your application to see where you spend such a large amount of memory.

How to print variable addresses in C?

When you intend to print the memory address of any variable or a pointer, using %d won't do the job and will cause some compilation errors, because you're trying to print out a number instead of an address, and even if it does work, you'd have an intent error, because a memory address is not a number. the value 0xbfc0d878 is surely not a number, but an address.

What you should use is %p. e.g.,

#include<stdio.h>

int main(void) {

    int a;
    a = 5;
    printf("The memory address of a is: %p\n", (void*) &a);
    return 0;
}

Good luck!

Left Outer Join using + sign in Oracle 11g

There is some incorrect information in this thread. I copied and pasted the incorrect information:

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

The above is WRONG!!!!! It's reversed. How I determined it's incorrect is from the following book:

Oracle OCP Introduction to Oracle 9i: SQL Exam Guide. Page 115 Table 3-1 has a good summary on this. I could not figure why my converted SQL was not working properly until I went old school and looked in a printed book!

Here is the summary from this book, copied line by line:

Oracle outer Join Syntax:

from tab_a a, tab_b b,                                       
where a.col_1 + = b.col_1                                     

ANSI/ISO Equivalent:

from tab_a a left outer join  
tab_b b on a.col_1 = b.col_1

Notice here that it's the reverse of what is posted above. I suppose it's possible for this book to have errata, however I trust this book more so than what is in this thread. It's an exam guide for crying out loud...

Combine GET and POST request methods in Spring

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
        @RequestParam(required = false) String parameter1,
        @RequestParam(required = false) String parameter2, 
        BindingResult result, HttpServletRequest request) 
        throws ParseException {

    LONG CODE and SAME LONG CODE with a minor difference
}

if @RequestParam(required = true) then you must pass parameter1,parameter2

Use BindingResult and request them based on your conditions.

The Other way

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
    two @RequestParam parameters, HttpServletRequest request) throws ParseException {

    myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
        BindingResult result) throws ParseException {

    myMethod();

    do here your minor difference
}

private returntype myMethod(){
    LONG CODE
}

If Else If In a Sql Server Function

No one seems to have picked that if (yes=no)>na or (no=na)>yes or (na=yes)>no, you get NULL as the result. Don't believe this is what you are after.

Here's also a more condensed form of the function, which works even if any of yes, no or na_ans is NULL.

USE [***]
GO
/****** Object:  UserDefinedFunction [dbo].[fnActionSq]    Script Date: 02/17/2011 10:21:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fnTally] (@SchoolId nvarchar(50))
RETURNS nvarchar(3)
AS 
BEGIN
return (select (
       select top 1 Result from
       (select 'Yes' Result, yes_ans union all
        select 'No', no_ans union all
        select 'N/A', na_ans) [ ]
        order by yes_ans desc, Result desc)
       from dbo.qrc_maintally
       where school_id = @SchoolId)
End

How to style input and submit button with CSS?

I did it this way based on the answers given here, I hope it helps

.likeLink {
    background: none !important;
    color: #3387c4;
    border: none;
    padding: 0 !important;
    font: inherit;
    cursor: pointer;
}
    .likeLink:hover {
        background: none !important;
        color: #25618c;
        border: none;
        padding: 0 !important;
        font: inherit;
        cursor: pointer;
        text-decoration: underline;
    }

Get an OutputStream into a String

I would use a ByteArrayOutputStream. And on finish you can call:

new String( baos.toByteArray(), codepage );

or better:

baos.toString( codepage );

For the String constructor, the codepage can be a String or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.

The method toString() accepts only a String as a codepage parameter (stand Java 8).

How to check if all of the following items are in a list?

Not OP's case, but - for anyone who wants to assert intersection in dicts and ended up here due to poor googling (e.g. me) - you need to work with dict.items:

>>> a = {'key': 'value'}
>>> b = {'key': 'value', 'extra_key': 'extra_value'}
>>> all(item in a.items() for item in b.items())
True
>>> all(item in b.items() for item in a.items())
False

That's because dict.items returns tuples of key/value pairs, and much like any object in Python, they're interchangeably comparable

Formatting numbers (decimal places, thousands separators, etc) with CSS

Another solution with pure CSS+HTML and the pseudo-class :lang().

Use some HTML to mark up the number with the classes thousands-separator and decimal-separator:

<html lang="es">
  Spanish: 1<span class="thousands-separator">200</span><span class="thousands-separator">000</span><span class="decimal-separator">.</span>50
</html>

Use the lang pseudo-class to format the number.

/* Spanish */
.thousands-separator:lang(es):before{
  content: ".";
}
.decimal-separator:lang(es){
  visibility: hidden;
  position: relative;
}
.decimal-separator:lang(es):before{
  position: absolute;
  visibility: visible;
  content: ",";
}

/* English and Mexican Spanish */
.thousands-separator:lang(en):before, .thousands-separator:lang(es-MX):before{
  content: ",";
}

Codepen: https://codepen.io/danielblazquez/pen/qBqVjGy

How to set background color of a button in Java GUI?

You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

Detect if device is iOS

In order to detect the iOS version, one has to destructure the user agent with a Javascript code like this:

 var res = navigator.userAgent.match(/; CPU.*OS (\d_\d)/);
    if(res) {
        var strVer = res[res.length-1];
        strVer = strVer.replace("_", ".");
        version = strVer * 1;
    }

How to check if any flags of a flag combination are set?

There are two aproaches that I can see that would work for checking for any bit being set.

Aproach A

if (letter != 0)
{
}

This works as long as you don't mind checking for all bits, including non-defined ones too!

Aproach B

if ((letter & Letters.All) != 0)
{
}

This only checks the defined bits, as long as Letters.All represents all of the possible bits.

For specific bits (one or more set), use Aproach B replacing Letters.All with the bits that you want to check for (see below).

if ((letter & Letters.AB) != 0)
{
}

How do I disable text selection with CSS or JavaScript?

Try this CSS code for cross-browser compatibility.

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

Reset all changes after last commit in git

First, reset any changes

This will undo any changes you've made to tracked files and restore deleted files:

git reset HEAD --hard

Second, remove new files

This will delete any new files that were added since the last commit:

git clean -fd

Files that are not tracked due to .gitignore are preserved; they will not be removed

Warning: using -x instead of -fd would delete ignored files. You probably don't want to do this.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go

$ homebrew install mdbtools

Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.

$ ./to_mysql.sh myfile.mdb > myfile.sql

(which btw contains more than 1 table)

Python Pandas : pivot table with aggfunc = count unique distinct

Since none of the answers are up to date with the last version of Pandas, I am writing another solution for this problem:

In [1]:
import pandas as pd

# Set exemple
df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']})

# Pivot
pd.crosstab(index=df2['Y'], columns=df2['Z'], values=df2['X'], aggfunc=pd.Series.nunique)

Out [1]:
Z   Z1  Z2  Z3
Y           
Y1  1.0 1.0 NaN
Y2  NaN NaN 1.0