Programs & Examples On #Log4perl

Log::Log4perl is a Perl module that lets you remote-control and fine-tune the logging behaviour of your system from the outside.

PHP date() format when inserting into datetime in MySQL

From the comments of php's date() manual page:

<?php $mysqltime = date ('Y-m-d H:i:s', $phptime); ?>

You had the 'Y' correct - that's a full year, but 'M' is a three character month, while 'm' is a two digit month. Same issue with 'D' instead of 'd'. 'G' is a 1 or 2 digit hour, where 'H' always has a leading 0 when needed.

Get all validation errors from Angular 2 FormGroup

This is solution with FormGroup inside supports ( like here )

Tested on: Angular 4.3.6

get-form-validation-errors.ts

import { AbstractControl, FormGroup, ValidationErrors } from '@angular/forms';

export interface AllValidationErrors {
  control_name: string;
  error_name: string;
  error_value: any;
}

export interface FormGroupControls {
  [key: string]: AbstractControl;
}

export function getFormValidationErrors(controls: FormGroupControls): AllValidationErrors[] {
  let errors: AllValidationErrors[] = [];
  Object.keys(controls).forEach(key => {
    const control = controls[ key ];
    if (control instanceof FormGroup) {
      errors = errors.concat(getFormValidationErrors(control.controls));
    }
    const controlErrors: ValidationErrors = controls[ key ].errors;
    if (controlErrors !== null) {
      Object.keys(controlErrors).forEach(keyError => {
        errors.push({
          control_name: key,
          error_name: keyError,
          error_value: controlErrors[ keyError ]
        });
      });
    }
  });
  return errors;
}

Using example:

if (!this.formValid()) {
  const error: AllValidationErrors = getFormValidationErrors(this.regForm.controls).shift();
  if (error) {
    let text;
    switch (error.error_name) {
      case 'required': text = `${error.control_name} is required!`; break;
      case 'pattern': text = `${error.control_name} has wrong pattern!`; break;
      case 'email': text = `${error.control_name} has wrong email format!`; break;
      case 'minlength': text = `${error.control_name} has wrong length! Required length: ${error.error_value.requiredLength}`; break;
      case 'areEqual': text = `${error.control_name} must be equal!`; break;
      default: text = `${error.control_name}: ${error.error_name}: ${error.error_value}`;
    }
    this.error = text;
  }
  return;
}

Remove substring from the string

If it is a the end of the string, you can also use chomp:

"hello".chomp("llo")     #=> "he"

How to check if an appSettings key exists?

I think the LINQ expression may be best:

   const string MyKey = "myKey"

   if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey))
          {
              // Key exists
          }

Uncaught ReferenceError: $ is not defined

The solution:

1) Use Google CDN to load jQuery

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

2) As far as I know about the Cycle Plugin, It is compatible with jQuery v1.5-v1.7 because most of the methods were deprecated in jQuery 1.8+ . This is the reason I've used v1.5 of Google CDN jquery in point 1. Most of the examples on cycle plugin use jquery 1.5.

3) Clear Your browser cache, It is the main culprit most of the times.

4) PLease check the loading of jquery using the code below

if(typeof jQuery!=='undefined'){
    console.log('jQuery Loaded');
}
else{
    console.log('not loaded yet');
}

Major Edit:

The reason for the error is fairly simple:

You have called the cycle method before the jquery is loaded.

call cycle plugin on DOM ready..

$(document).ready(function(){
    $('#slider').cycle({ 
        fx:     'scrollHorz', 
        speed:  'fast', 

        next:   '#next', 
        prev:   '#prev' 
    });  
});

How to set aliases in the Git Bash for Windows?

There is two easy way to set the alias.

  1. Using Bash
  2. Updating .gitconfig file

Using Bash

Open bash terminal and type git command. For instance:

$ git config --global alias.a add
$ git config --global alias.aa 'add .'
$ git config --global alias.cm 'commit -m'
$ git config --global alias.s status
---
---

It will eventually add those aliases on .gitconfig file.

Updating .gitconfig file

Open .gitconfig file located at 'C:\Users\username\.gitconfig' in Windows environment. Then add following lines:

[alias]  
a = add  
aa = add . 
cm = commit -m 
gau = add --update 
au = add --update
b = branch
---
---

Writing binary number system in C code

Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b prefix:

int foo = 0b1010;

If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:

#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
        unsigned long long i = 0;
        while (*s) {
                i <<= 1;
                i += *s++ - '0';
        }
        return i;
}

And then you can use it like this:

int foo = B(1010);

If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.

Proof:

The following code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>


#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
    unsigned long long i = 0;
    while (*s) {
        i <<= 1;
        i += *s++ - '0';
    }
    return i;
}

int main()
{
    int foo = B(001100101);

    printf("%d\n", foo);

    return 0;
}

has been compiled using clang -o baz.S baz.c -Wall -O3 -S, and it produced the following assembly:

    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    leaq    L_.str1(%rip), %rdi
    movl    $101, %esi               ## <= This line!
    xorb    %al, %al
    callq   _printf
    xorl    %eax, %eax
    popq    %rbp
    ret
    .cfi_endproc

    .section    __TEXT,__cstring,cstring_literals
L_.str1:                                ## @.str1
    .asciz   "%d\n"


.subsections_via_symbols

So clang completely eliminated the call to the function, and replaced its return value with 101. Neat, huh?

Filter by process/PID in Wireshark

Use Microsoft Message Analyzer v1.4

Navigate to ProcessId from the field chooser.

Etw
-> EtwProviderMsg
--> EventRecord
---> Header
----> ProcessId

Right click and Add as Column

How do I pass a variable to the layout using Laravel' Blade templating?

In the Blade Template : define a variable like this

@extends('app',['title' => 'Your Title Goes Here'])
@section('content')

And in the app.blade.php or any other of your choice ( I'm just following default Laravel 5 setup )

<title>{{ $title or 'Default title Information if not set explicitly' }}</title>

This is my first answer here. Hope it works.Good luck!

Best way to remove the last character from a string built with stringbuilder

Just use

string.Join(",", yourCollection)

This way you don't need the StringBuilder and the loop.




Long addition about async case. As of 2019, it's not a rare setup when the data are coming asynchronously.

In case your data are in async collection, there is no string.Join overload taking IAsyncEnumerable<T>. But it's easy to create one manually, hacking the code from string.Join:

public static class StringEx
{
    public static async Task<string> JoinAsync<T>(string separator, IAsyncEnumerable<T> seq)
    {
        if (seq == null)
            throw new ArgumentNullException(nameof(seq));

        await using (var en = seq.GetAsyncEnumerator())
        {
            if (!await en.MoveNextAsync())
                return string.Empty;

            string firstString = en.Current?.ToString();

            if (!await en.MoveNextAsync())
                return firstString ?? string.Empty;

            // Null separator and values are handled by the StringBuilder
            var sb = new StringBuilder(256);
            sb.Append(firstString);

            do
            {
                var currentValue = en.Current;
                sb.Append(separator);
                if (currentValue != null)
                    sb.Append(currentValue);
            }
            while (await en.MoveNextAsync());
            return sb.ToString();
        }
    }
}

If the data are coming asynchronously but the interface IAsyncEnumerable<T> is not supported (like the mentioned in comments SqlDataReader), it's relatively easy to wrap the data into an IAsyncEnumerable<T>:

async IAsyncEnumerable<(object first, object second, object product)> ExtractData(
        SqlDataReader reader)
{
    while (await reader.ReadAsync())
        yield return (reader[0], reader[1], reader[2]);
}

and use it:

Task<string> Stringify(SqlDataReader reader) =>
    StringEx.JoinAsync(
        ", ",
        ExtractData(reader).Select(x => $"{x.first} * {x.second} = {x.product}"));

In order to use Select, you'll need to use nuget package System.Interactive.Async. Here you can find a compilable example.

Using margin:auto to vertically-align a div

.black {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,.5);
}
.message {
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background:yellow;
    width:200px;
    padding:10px;
}

 - 


----------


<div class="black">
<div class="message">
    This is a popup message.
</div>

How do I create a foreign key in SQL Server?

I always use this syntax to create the foreign key constraint between 2 tables

Alter Table ForeignKeyTable
Add constraint `ForeignKeyTable_ForeignKeyColumn_FK`
`Foreign key (ForeignKeyColumn)` references `PrimaryKeyTable (PrimaryKeyColumn)`

i.e.

Alter Table tblEmployee
Add constraint tblEmployee_DepartmentID_FK
foreign key (DepartmentID) references tblDepartment (ID)

How can I disable a tab inside a TabControl?

Cast your TabPage to a Control, then set the Enabled property to false.

((Control)this.tabPage).Enabled = false;

Therefore, the tabpage's header will still be enabled but its contents will be disabled.

Named placeholders in string formatting

Another example of Apache Common StringSubstitutor for simple named placeholder.

String template = "Welcome to {theWorld}. My name is {myName}.";

Map<String, String> values = new HashMap<>();
values.put("theWorld", "Stackoverflow");
values.put("myName", "Thanos");

String message = StringSubstitutor.replace(template, values, "{", "}");

System.out.println(message);

// Welcome to Stackoverflow. My name is Thanos.

Regular expression which matches a pattern, or is an empty string

An alternative would be to place your regexp in non-capturing parentheses. Then make that expression optional using the ? qualifier, which will look for 0 (i.e. empty string) or 1 instances of the non-captured group.

For example:

/(?: some regexp )?/

In your case the regular expression would look something like this:

/^(?:[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+)?$/

No | "or" operator necessary!

Here is the Mozilla documentation for JavaScript Regular Expression syntax.

UIDevice uniqueIdentifier deprecated - What to do now?

I would also suggest changing over from uniqueIdentifier to this open source library (2 simple categories really) that utilize the device’s MAC Address along with the App Bundle Identifier to generate a unique ID in your applications that can be used as a UDID replacement.

Keep in mind that unlike the UDID this number will be different for every app.

You simply need to import the included NSString and UIDevice categories and call [[UIDevice currentDevice] uniqueDeviceIdentifier] like so:

#import "UIDevice+IdentifierAddition.h"
#import "NSString+MD5Addition.h"
NSString *iosFiveUDID = [[UIDevice currentDevice] uniqueDeviceIdentifier]

You can find it on Github here:

UIDevice with UniqueIdentifier for iOS 5


Here are the categories (just the .m files - check the github project for the headers):

UIDevice+IdentifierAddition.m

#import "UIDevice+IdentifierAddition.h"
#import "NSString+MD5Addition.h"

#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

@interface UIDevice(Private)

- (NSString *) macaddress;

@end

@implementation UIDevice (IdentifierAddition)

////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Private Methods

// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb.
- (NSString *) macaddress{
    
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", 
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    
    return outstring;
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Public Methods

- (NSString *) uniqueDeviceIdentifier{
    NSString *macaddress = [[UIDevice currentDevice] macaddress];
    NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];  
    NSString *stringToHash = [NSString stringWithFormat:@"%@%@",macaddress,bundleIdentifier];
    NSString *uniqueIdentifier = [stringToHash stringFromMD5];  
    return uniqueIdentifier;
}

- (NSString *) uniqueGlobalDeviceIdentifier{
    NSString *macaddress = [[UIDevice currentDevice] macaddress];
    NSString *uniqueIdentifier = [macaddress stringFromMD5];    
    return uniqueIdentifier;
}

@end

NSString+MD5Addition.m:

#import "NSString+MD5Addition.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString(MD5Addition)

- (NSString *) stringFromMD5{
    
    if(self == nil || [self length] == 0)
        return nil;
    
    const char *value = [self UTF8String];
    
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);
    
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    return [outputString autorelease];
}

@end

Use Toast inside Fragment

        public void onClick(View v) {
            Context context = v.getContext();
            CharSequence text = "Message";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

If you are using tinker and want to log the SQL query formed you can do

$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.5 — cli) by Justin Hileman
>>> DB::listen(function ($query) { dump($query->sql); dump($query->bindings); dump($query->time); });
=> null
>>> App\User::find(1)
"select * from `users` where `users`.`id` = ? limit 1"
array:1 [
  0 => 1
]
6.99
=> App\User {#3131
     id: 1,
     name: "admin",
     email: "[email protected]",
     created_at: "2019-01-11 19:06:23",
     updated_at: "2019-01-11 19:06:23",
   }
>>>

how to convert string into time format and add two hours

Being a fan of the Joda Time library, here's how you can do it that way using a Joda DateTime:

import org.joda.time.format.*;
import org.joda.time.*;

...    

String dateString = "2009-04-17 10:41:33";

// parse the string
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = formatter.parseDateTime(dateString);

// add two hours
dateTime = dateTime.plusHours(2); // easier than mucking about with Calendar and constants

System.out.println(dateTime);

If you still need to use java.util.Date objects before/after this conversion, the Joda DateTime API provides some easy toDate() and toCalendar() methods for easy translation.

The Joda API provides so much more in the way of convenience over the Java Date/Calendar API.

How to put two divs on the same line with CSS in simple_form in rails?

You can't float or set the width of an inline element. Remove display: inline; from both classes and your markup should present fine.

EDIT: You can set the width, but it will cause the element to be rendered as a block.

Convert URL to File or Blob for FileReader.readAsDataURL

Try this I learned this from @nmaier when I was mucking around with converting to ico: Well i dont really understand what array buffer is but it does what we need:

function previewFile(file) {

  var reader  = new FileReader();

  reader.onloadend = function () {
    console.log(reader.result); //this is an ArrayBuffer
  }
  reader.readAsArrayBuffer(file);
}

notice how i just changed your readAsDataURL to readAsArrayBuffer.

Here is the example @nmaier gave me: https://stackoverflow.com/a/24253997/1828637

it has a fiddle

if you want to take this and make a file out of it i would think you would use file-output-stream in the onloadend

How do I set the timeout for a JAX-WS webservice client?

Not sure if this will help in your context...

Can the soap object be cast as a BindingProvider ?

MyWebServiceSoap soap;
MyWebService service = new MyWebService("http://www.google.com");
soap = service.getMyWebServiceSoap();
// set timeouts here
((BindingProvider)soap).getRequestContext().put("com.sun.xml.internal.ws.request.timeout", 10000);
    soap.sendRequestToMyWebService();

On the other hand if you are wanting to set the timeout on the initialization of the MyWebService object then this will not help.

This worked for me when wanting to timeout the individual WebService calls.

How to have EditText with border in Android Lollipop

You can do it using xml.

Create an xml layout and name it like my_edit_text_border.xml

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ffffff"/>
            <corners android:radius="5dp" />
            <stroke
                android:width="2dp"
                android:color="#949494"
                />
        </shape>
    </item>
</selector>

Add background to your Edittext

<EditText
 android:id="@+id/editText1"
 ..
 android:background="@layout/my_edit_text_border">

Split a vector into chunks

split(x,matrix(1:n,n,length(x))[1:length(x)])

perhaps this is more clear, but the same idea:
split(x,rep(1:n, ceiling(length(x)/n),length.out = length(x)))

if you want it ordered,throw a sort around it

How to plot multiple functions on the same figure, in Matplotlib?

Perhaps a more pythonic way of doing so.

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, t, b, t, c)
plt.show()

enter image description here

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

Just run the contents through parseFloat(). It will return NaN on invalid input.

Android Studio Image Asset Launcher Icon Background Color

Android Studio 3.5.3 It works with this configuration.

enter image description here

enter image description here

enter image description here

Jar mismatch! Fix your dependencies

Don't Include the android-support-v4 in the library , instead you can add it to your project as an external jar using build path menu > add external jar

Sometimes you have to clean your project.

Object of custom type as dictionary key

An alternative in Python 2.6 or above is to use collections.namedtuple() -- it saves you writing any special methods:

from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
    def __new__(cls, name, location, length):
        obj = MyThingBase.__new__(cls, name, location)
        obj.length = length
        return obj

a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False

How to use XPath in Python?

You can use:

PyXML:

from xml.dom.ext.reader import Sax2
from xml import xpath
doc = Sax2.FromXmlFile('foo.xml').documentElement
for url in xpath.Evaluate('//@Url', doc):
  print url.value

libxml2:

import libxml2
doc = libxml2.parseFile('foo.xml')
for url in doc.xpathEval('//@Url'):
  print url.content

How to retrieve a single file from a specific revision in Git?

In addition to all the options listed by other answers, you can use git reset with the Git object (hash, branch, HEAD~x, tag, ...) of interest and the path of your file:

git reset <hash> /path/to/file

In your example:

git reset 27cf8e8 my_file.txt

What this does is that it will revert my_file.txt to its version at the commit 27cf8e8 in the index while leaving it untouched (so in its current version) in the working directory.

From there, things are very easy:

  • you can compare the two versions of your file with git diff --cached my_file.txt
  • you can get rid of the old version of the file with git restore --staged file.txt (or, prior to Git v2.23, git reset file.txt) if you decide that you don't like it
  • you can restore the old version with git commit -m "Restore version of file.txt from 27cf8e8" and git restore file.txt (or, prior to Git v2.23, git checkout -- file.txt)
  • you can add updates from the old to the new version only for some hunks by running git add -p file.txt (then git commit and git restore file.txt).

Lastly, you can even interactively pick and choose which hunk(s) to reset in the very first step if you run:

git reset -p 27cf8e8 my_file.txt

So git reset with a path gives you lots of flexibility to retrieve a specific version of a file to compare with its currently checked-out version and, if you choose to do so, to revert fully or only for some hunks to that version.


Edit: I just realized that I am not answering your question since what you wanted wasn't a diff or an easy way to retrieve part or all of the old version but simply to cat that version.

Of course, you can still do that after resetting the file with:

git show :file.txt

to output to standard output or

git show :file.txt > file_at_27cf8e8.txt

But if this was all you wanted, running git show directly with git show 27cf8e8:file.txt as others suggested is of course much more direct.

I am going to leave this answer though because running git show directly allows you to get that old version instantly, but if you want to do something with it, it isn't nearly as convenient to do so from there as it is if you reset that version in the index.

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

Working on .Net Core 2.2 and 3.0 as of now.

To get the projects root directory within a Controller:

  • Create a property for the hosting environment

    private readonly IHostingEnvironment _hostingEnvironment;
    
  • Add Microsoft.AspNetCore.Hosting to your controller

    using Microsoft.AspNetCore.Hosting;
    
  • Register the service in the constructor

    public HomeController(IHostingEnvironment hostingEnvironment) {
        _hostingEnvironment = hostingEnvironment;
    }
    
  • Now, to get the projects root path

    string projectRootPath = _hostingEnvironment.ContentRootPath;
    

To get the "wwwroot" path, use

_hostingEnvironment.WebRootPath

What is the use of "using namespace std"?

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

Not Able To Debug App In Android Studio

In my case near any line a red circle appeared with a cross and red line with a message: "No executable code found at line ..." like in Android studio gradle breakpoint No executable code found at line.

A problem appeared after updating of build.gradle. We included Kotlin support, so a number of methods exceeded 64K. Problem lines:

buildTypes {
    debug {
        minifyEnabled true

Change them to:

buildTypes {
    debug {
        minifyEnabled false
        debuggable true

Then sync a gradle with a button "Sync Project with Gradle Files". If after restarting of your application you will get an error: "Error:The number of method references in a .dex file cannot exceed 64K. Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html", then, like in The number of method references in a .dex file cannot exceed 64k API 17 add the following lines to build.gradle:

android {

    defaultConfig {
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
    implementation 'com.android.support:multidex:1.0.2'
}

UPDATE

According to https://developer.android.com/studio/build/multidex.html do the following to enable multidex support below Android 5.0. Else it won't start in these devices.

Open AndroidManifest and find tag <application>. Near android:name= is a reference to an Application class. Open this class. Extend Application class with MultiDexApplication so:

public class MyApplication extends MultiDexApplication { ... }

If no Application class set, write so:

<application
        android:name="android.support.multidex.MultiDexApplication" >
    ...
</application>

"Please try running this command again as Root/Administrator" error when trying to install LESS

I was getting this issue for instaling expo cli and I fixed by just following four steps mentioned in the npm documentation here.

Problem is some version of npm fail to locate folder for global installations of package. Following these steps we can create or modify the .profile file in Home directory of user and give it a proper PATH there so it works like a charm.

Try this it helped me and I spent around an hour for this issue. My node version was 6.0

Steps I follow

Back up your computer. On the command line, in your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file and add this line:

export PATH=~/.npm-global/bin:$PATH

On the command line, update your system variables:

source ~/.profile

To test your new configuration, install a package globally without using sudo:

npm install -g jshint

android.content.res.Resources$NotFoundException: String resource ID #0x0

The evaluated value for settext was integer so it went to see a resource attached to it but it was not found, you wanted to set text so it should be string so convert integer into string by attaching .toStringe or String.valueOf(int) will solve your problem!

Email address validation using ASP.NET MVC data type attributes

As per the above this will fix server side validation of an Email Address:

[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }

However...

If you are using JQuery client side validation you should know that the Email validates differently server side (model validation) to client side (JQuery validation). In that test@example (a top level domain email address) would fail server side but would validate fine on the client side.

To fix this disparity you can override the default client side email validation as follows:

$.validator.methods.email = function (value, element) {
    return this.optional(element) || /^[a-z0-9._]+@[a-z]+\.[a-z.]+/.test(value);
}

Remove pandas rows with duplicate indices

I would suggest using the duplicated method on the Pandas Index itself:

df3 = df3[~df3.index.duplicated(keep='first')]

While all the other methods work, the currently accepted answer is by far the least performant for the provided example. Furthermore, while the groupby method is only slightly less performant, I find the duplicated method to be more readable.

Using the sample data provided:

>>> %timeit df3.reset_index().drop_duplicates(subset='index', keep='first').set_index('index')
1000 loops, best of 3: 1.54 ms per loop

>>> %timeit df3.groupby(df3.index).first()
1000 loops, best of 3: 580 µs per loop

>>> %timeit df3[~df3.index.duplicated(keep='first')]
1000 loops, best of 3: 307 µs per loop

Note that you can keep the last element by changing the keep argument to 'last'.

It should also be noted that this method works with MultiIndex as well (using df1 as specified in Paul's example):

>>> %timeit df1.groupby(level=df1.index.names).last()
1000 loops, best of 3: 771 µs per loop

>>> %timeit df1[~df1.index.duplicated(keep='last')]
1000 loops, best of 3: 365 µs per loop

Set drawable size programmatically

jkhouw1 answer is correct one, but it lacks some details, see below:

It is much easier for at least API > 21. Assume that we have VectorDrawable from resources (example code to retrieve it):

val iconResource = context.resources.getIdentifier(name, "drawable", context.packageName)
val drawable = context.resources.getDrawable(iconResource, null)

For that VectorDrawable just set desired size:

drawable.setBounds(0, 0, size, size)

And show drawable in button:

button.setCompoundDrawables(null, drawable, null, null)

That's it. But note to use setCompoundDrawables (not Intrinsic version)!

String date to xmlgregoriancalendar conversion

tl;dr

  • Use modern java.time classes as much as possible, rather than the terrible legacy classes.
  • Always specify your desired/expected time zone or offset-from-UTC rather than rely implicitly on JVM’s current default.

Example code (without exception-handling):

XMLGregorianCalendar xgc = 
    DatatypeFactory                           // Data-type converter.
    .newInstance()                            // Instantiate a converter object.
    .newXMLGregorianCalendar(                 // Converter going from `GregorianCalendar` to `XMLGregorianCalendar`.
        GregorianCalendar.from(               // Convert from modern `ZonedDateTime` class to legacy `GregorianCalendar` class.
            LocalDate                         // Modern class for representing a date-only, without time-of-day and without time zone.
            .parse( "2014-01-07" )            // Parsing strings in standard ISO 8601 format is handled by default, with no need for custom formatting pattern. 
            .atStartOfDay( ZoneOffset.UTC )   // Determine the first moment of the day as seen in UTC. Returns a `ZonedDateTime` object.
        )                                     // Returns a `GregorianCalendar` object.
    )                                         // Returns a `XMLGregorianCalendar` object.
;

Parsing date-only input string into an object of XMLGregorianCalendar class

Avoid the terrible legacy date-time classes whenever possible, such as XMLGregorianCalendar, GregorianCalendar, Calendar, and Date. Use only modern java.time classes.

When presented with a string such as "2014-01-07", parse as a LocalDate.

LocalDate.parse( "2014-01-07" )

To get a date with time-of-day, assuming you want the first moment of the day, specify a time zone. Let java.time determine the first moment of the day, as it is not always 00:00:00.0 in some zones on some dates.

LocalDate.parse( "2014-01-07" )
         .atStartOfDay( ZoneId.of( "America/Montreal" ) )

This returns a ZonedDateTime object.

ZonedDateTime zdt = 
        LocalDate
        .parse( "2014-01-07" )
        .atStartOfDay( ZoneId.of( "America/Montreal" ) )
;

zdt.toString() = 2014-01-07T00:00-05:00[America/Montreal]

But apparently, you want the start-of-day as seen in UTC (an offset of zero hours-minutes-seconds). So we specify ZoneOffset.UTC constant as our ZoneId argument.

ZonedDateTime zdt = 
        LocalDate
        .parse( "2014-01-07" )
        .atStartOfDay( ZoneOffset.UTC )
;

zdt.toString() = 2014-01-07T00:00Z

The Z on the end means UTC (an offset of zero), and is pronounced “Zulu”.

If you must work with legacy classes, convert to GregorianCalendar, a subclass of Calendar.

GregorianCalendar gc = GregorianCalendar.from( zdt ) ;

gc.toString() = java.util.GregorianCalendar[time=1389052800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=0,WEEK_OF_YEAR=2,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]

Apparently, you really need an object of the legacy class XMLGregorianCalendar. If the calling code cannot be updated to use java.time, convert.

XMLGregorianCalendar xgc = 
        DatatypeFactory
        .newInstance()
        .newXMLGregorianCalendar( gc ) 
;

Actually, that code requires a try-catch.

try
{
    XMLGregorianCalendar xgc =
            DatatypeFactory
                    .newInstance()
                    .newXMLGregorianCalendar( gc );
}
catch ( DatatypeConfigurationException e )
{
    e.printStackTrace();
}

xgc = 2014-01-07T00:00:00.000Z

Putting that all together, with appropriate exception-handling.

// Given an input string such as "2014-01-07", return a `XMLGregorianCalendar` object
// representing first moment of the day on that date as seen in UTC. 
static public XMLGregorianCalendar getXMLGregorianCalendar ( String input )
{
    Objects.requireNonNull( input );
    if( input.isBlank() ) { throw new IllegalArgumentException( "Received empty/blank input string for date argument. Message # 11818896-7412-49ba-8f8f-9b3053690c5d." ) ; }
    XMLGregorianCalendar xgc = null;
    ZonedDateTime zdt = null;

    try
    {
        zdt =
                LocalDate
                        .parse( input )
                        .atStartOfDay( ZoneOffset.UTC );
    }
    catch ( DateTimeParseException e )
    {
        throw new IllegalArgumentException( "Faulty input string for date does not comply with standard ISO 8601 format. Message # 568db0ef-d6bf-41c9-8228-cc3516558e68." );
    }

    GregorianCalendar gc = GregorianCalendar.from( zdt );
    try
    {
        xgc =
                DatatypeFactory
                        .newInstance()
                        .newXMLGregorianCalendar( gc );
    }
    catch ( DatatypeConfigurationException e )
    {
        e.printStackTrace();
    }

    Objects.requireNonNull( xgc );
    return xgc ;
}

Usage.

String input = "2014-01-07";
XMLGregorianCalendar xgc = App.getXMLGregorianCalendar( input );

Dump to console.

System.out.println( "xgc = " + xgc );

xgc = 2014-01-07T00:00:00.000Z

Modern date-time classes versus legacy

Table of date-time types in Java, both modern and legacy

Date-time != String

Do not conflate a date-time value with its textual representation. We parse strings to get a date-time object, and we ask the date-time object to generate a string to represent its value. The date-time object has no ‘format’, only strings have a format.

So shift your thinking into two separate modes: model and presentation. Determine the date-value you have in mind, applying appropriate time zone, as the model. When you need to display that value, generate a string in a particular format as expected by the user.

Avoid legacy date-time classes

The Question and other Answers all use old troublesome date-time classes now supplanted by the java.time classes.

ISO 8601

Your input string "2014-01-07" is in standard ISO 8601 format.

The T in the middle separates date portion from time portion.

The Z on the end is short for Zulu and means UTC.

Fortunately, the java.time classes use the ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2014-01-07" ) ;

ld.toString(): 2014-01-07

Start of day ZonedDateTime

If you want to see the first moment of that day, specify a ZoneId time zone to get a moment on the timeline, a ZonedDateTime. The time zone is crucial because the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Never assume the day begins at 00:00:00. Anomalies such as Daylight Saving Time (DST) means the day may begin at another time-of-day such as 01:00:00. Let java.time determine the first moment.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;

zdt.toString(): 2014-01-07T00:00:00Z

For your desired format, generate a string using the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME and then replace the T in the middle with a SPACE.

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " ) ; 

2014-01-07 00:00:00


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How do I release memory used by a pandas dataframe?

Reducing memory usage in Python is difficult, because Python does not actually release memory back to the operating system. If you delete objects, then the memory is available to new Python objects, but not free()'d back to the system (see this question).

If you stick to numeric numpy arrays, those are freed, but boxed objects are not.

>>> import os, psutil, numpy as np
>>> def usage():
...     process = psutil.Process(os.getpid())
...     return process.get_memory_info()[0] / float(2 ** 20)
... 
>>> usage() # initial memory usage
27.5 

>>> arr = np.arange(10 ** 8) # create a large array without boxing
>>> usage()
790.46875
>>> del arr
>>> usage()
27.52734375 # numpy just free()'d the array

>>> arr = np.arange(10 ** 8, dtype='O') # create lots of objects
>>> usage()
3135.109375
>>> del arr
>>> usage()
2372.16796875  # numpy frees the array, but python keeps the heap big

Reducing the Number of Dataframes

Python keep our memory at high watermark, but we can reduce the total number of dataframes we create. When modifying your dataframe, prefer inplace=True, so you don't create copies.

Another common gotcha is holding on to copies of previously created dataframes in ipython:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'foo': [1,2,3,4]})

In [3]: df + 1
Out[3]: 
   foo
0    2
1    3
2    4
3    5

In [4]: df + 2
Out[4]: 
   foo
0    3
1    4
2    5
3    6

In [5]: Out # Still has all our temporary DataFrame objects!
Out[5]: 
{3:    foo
 0    2
 1    3
 2    4
 3    5, 4:    foo
 0    3
 1    4
 2    5
 3    6}

You can fix this by typing %reset Out to clear your history. Alternatively, you can adjust how much history ipython keeps with ipython --cache-size=5 (default is 1000).

Reducing Dataframe Size

Wherever possible, avoid using object dtypes.

>>> df.dtypes
foo    float64 # 8 bytes per value
bar      int64 # 8 bytes per value
baz     object # at least 48 bytes per value, often more

Values with an object dtype are boxed, which means the numpy array just contains a pointer and you have a full Python object on the heap for every value in your dataframe. This includes strings.

Whilst numpy supports fixed-size strings in arrays, pandas does not (it's caused user confusion). This can make a significant difference:

>>> import numpy as np
>>> arr = np.array(['foo', 'bar', 'baz'])
>>> arr.dtype
dtype('S3')
>>> arr.nbytes
9

>>> import sys; import pandas as pd
>>> s = pd.Series(['foo', 'bar', 'baz'])
dtype('O')
>>> sum(sys.getsizeof(x) for x in s)
120

You may want to avoid using string columns, or find a way of representing string data as numbers.

If you have a dataframe that contains many repeated values (NaN is very common), then you can use a sparse data structure to reduce memory usage:

>>> df1.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 39681584 entries, 0 to 39681583
Data columns (total 1 columns):
foo    float64
dtypes: float64(1)
memory usage: 605.5 MB

>>> df1.shape
(39681584, 1)

>>> df1.foo.isnull().sum() * 100. / len(df1)
20.628483479893344 # so 20% of values are NaN

>>> df1.to_sparse().info()
<class 'pandas.sparse.frame.SparseDataFrame'>
Int64Index: 39681584 entries, 0 to 39681583
Data columns (total 1 columns):
foo    float64
dtypes: float64(1)
memory usage: 543.0 MB

Viewing Memory Usage

You can view the memory usage (docs):

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 39681584 entries, 0 to 39681583
Data columns (total 14 columns):
...
dtypes: datetime64[ns](1), float64(8), int64(1), object(4)
memory usage: 4.4+ GB

As of pandas 0.17.1, you can also do df.info(memory_usage='deep') to see memory usage including objects.

batch script - read line by line

The "call" solution has some problems.

It fails with many different contents, as the parameters of a CALL are parsed twice by the parser.
These lines will produce more or less strange problems

one
two%222
three & 333
four=444
five"555"555"
six"&666
seven!777^!
the next line is empty

the end

Therefore you shouldn't use the value of %%a with a call, better move it to a variable and then call a function with only the name of the variable.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
    set "myVar=%%a"
    call :processLine myVar
)
goto :eof

:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
ENDLOCAL
goto :eof

Offline Speech Recognition In Android (JellyBean)

I successfully implemented my Speech-Service with offline capabilities by using onPartialResults when offline and onResults when online.

npm WARN package.json: No repository field

you can also mark the application as private if you don’t plan to put it in an actual repository.

{
  "name": "my-application",
  "version": "0.0.1",
  "private": true
}

How to call a JavaScript function from PHP?

If you want to echo it out for later execution it's ok

If you want to execute the JS and use the results in PHP use V8JS

V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');

You can refer here for further reference: What are Extensions in php v8js?

If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution

how can I enable scrollbars on the WPF Datagrid?

This worked for me. The key is to use * as Row height.

<Grid x:Name="grid">
        <Grid.RowDefinitions>
            <RowDefinition Height="60"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="10"/>
        </Grid.RowDefinitions>

        <TabControl  Grid.Row="1" x:Name="tabItem">
                <TabItem x:Name="ta" 
                        Header="List of all Clients">
                        <DataGrid Name="clientsgrid" AutoGenerateColumns="True" Margin="2" 
                         ></DataGrid>
                </TabItem>
        </TabControl>
    
    </Grid>

How to use target in location.href

try this one, which simulates a click on an anchor.

var a = document.createElement('a');
a.href='http://www.google.com';
a.target = '_blank';
document.body.appendChild(a);
a.click();

Google Map API v3 ~ Simply Close an infowindow?

With the v3 API, you can easily close the InfoWindow with the InfoWindow.close() method. You simply need to keep a reference to the InfoWindow object that you are using. Consider the following example, which opens up an InfoWindow and closes it after 5 seconds:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
  <title>Google Maps API InfoWindow Demo</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 400px; height: 500px;"></div>

  <script type="text/javascript">
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: new google.maps.LatLng(-25.36388, 131.04492),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      map: map
    });

    var infowindow = new google.maps.InfoWindow({
      content: 'An InfoWindow'
    });

    infowindow.open(map, marker);

    setTimeout(function () { infowindow.close(); }, 5000);
  </script>
</body>
</html>

If you have a separate InfoWindow object for each Marker, you may want to consider adding the InfoWindow object as a property of your Marker objects:

var marker = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker.infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

Then you would be able to open and close that InfoWindow as follows:

marker.infowindow.open(map, marker);
marker.infowindow.close();

The same applies if you have an array of markers:

var markers = [];

marker[0] = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker[0].infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

// ...

marker[0].infowindow.open(map, marker);
marker[0].infowindow.close();

Unable to specify the compiler with CMake

Using with FILEPATH option might work:

set(CMAKE_CXX_COMPILER:FILEPATH C:/MinGW/bin/gcc.exe)

Best way to integrate Python and JavaScript?

Many of these projects mentioned above are dead or dying, lacking activity and interest from author side. Interesting to follow how this area develops.

For the record, in era of plugin based implementations, KDE camp had an attempt to solve this with plugin and non-language specific way and created the Kross https://en.wikipedia.org/wiki/Kross_(software) - in my understanding it never took off even inside the community itself.

During this chicken and egg -problem time, javascript-based implementions are definately way to go. Maybe in the future we seee pure and clean, full Python support natively in browsers.

How to get the ASCII value of a character

From here:

The function ord() gets the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick.

>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>

In Python 2, there was also the unichr function, returning the Unicode character whose ordinal is the unichr argument:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'

In Python 3 you can use chr instead of unichr.


ord() - Python 3.6.5rc1 documentation

ord() - Python 2.7.14 documentation

Get values from a listbox on a sheet

Take selected value:

worksheet name = ordls
form control list box name = DEPDB1

selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

Swift GET request with parameters

You can extend your Dictionary to only provide stringFromHttpParameter if both key and value conform to CustomStringConvertable like this

extension Dictionary where Key : CustomStringConvertible, Value : CustomStringConvertible {
  func stringFromHttpParameters() -> String {
    var parametersString = ""
    for (key, value) in self {
      parametersString += key.description + "=" + value.description + "&"
    }
    return parametersString
  }
}

this is much cleaner and prevents accidental calls to stringFromHttpParameters on dictionaries that have no business calling that method

Windows Explorer "Command Prompt Here"


http://www.petefreitag.com/item/146.cfm

  • Open up windows explorer

  • Tools -> Folder Options.

  • File Types Tab

  • Select the Folder file type

  • Click Advanced

  • Click New

  • For the Action type what ever you want the context menu to display, I used Command Prompt.

  • For the Application used to perform the action use c:\windows\system32\cmd.exe (note on win2k you will want to specify the winnt directory instead of the windows directory)

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

As explained here, if you clone with SSH url, you don't need to enter username / password each time you push / pull. Check above answer by @manojlds

But if you want to clone with HTTPS and want to avoid entering username / password each time, you can store credentials into cache with below command:

git config --global credential.helper 'cache --timeout 3600'

where 3600 (seconds) means 1 hour, you may change it as per your requirement.

C# static class why use?

If a class is declared as static then the variables and methods need to be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

->The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Example

static class CollegeRegistration
{
  //All static member variables
   static int nCollegeId; //College Id will be same for all the students studying
   static string sCollegeName; //Name will be same
   static string sColegeAddress; //Address of the college will also same

    //Member functions
   public static int GetCollegeId()
   {
     nCollegeId = 100;
     return (nCollegeID);
   }
    //similarly implementation of others also.
} //class end


public class student
{
    int nRollNo;
    string sName;

    public GetRollNo()
    {
       nRollNo += 1;
       return (nRollNo);
    }
    //similarly ....
    public static void Main()
   {
     //Not required.
     //CollegeRegistration objCollReg= new CollegeRegistration();

     //<ClassName>.<MethodName>
     int cid= CollegeRegistration.GetCollegeId();
    string sname= CollegeRegistration.GetCollegeName();


   } //Main end
}

How to set <iframe src="..."> without causing `unsafe value` exception?

constructor(
 public sanitizer: DomSanitizer, ) {

 }

I had been struggling for 4 hours. the problem was in img tag. When you use square bracket to 'src' ex: [src]. you can not use this angular expression {{}}. you just give directly from an object example below. if you give angular expression {{}}. you will get interpolation error.

  1. first i used ngFor to iterate the countries

    *ngFor="let country of countries"
    
  2. second you put this in the img tag. this is it.

    <img [src]="sanitizer.bypassSecurityTrustResourceUrl(country.flag)"
    height="20" width="20" alt=""/>
    

Git push error: "origin does not appear to be a git repository"

To resolving this problem.I just create a new folder and put some new files.Then use these commond.

* git add .
* git commit 
* git remote add master `your address`

then it tells me to login in. To input your username and password. after that

git pull 
git push origin master

finished you have pushed your code to your github

Java variable number or arguments for a method

For different types of arguments, there is 3-dots :

public void foo(Object... x) {
    String myVar1  = x.length > 0 ? (String)x[0]  : "Hello";
    int myVar2     = x.length > 1 ? Integer.parseInt((String) x[1]) : 888;
} 

Then call it

foo("Hii"); 
foo("Hii", 146); 

for security, use like this:
if (!(x[0] instanceof String)) { throw new IllegalArgumentException("..."); }

The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Please, see more variations .

Visual Studio Code cannot detect installed git

Version control

First install Git onto your desktop, then Add the encircled extension in vscode, as seen in the picture.

That helped me fix the same issue you have.

How does DISTINCT work when using JPA and Hibernate

@Entity
@NamedQuery(name = "Customer.listUniqueNames", 
            query = "SELECT DISTINCT c.name FROM Customer c")
public class Customer {
        ...

        private String name;

        public static List<String> listUniqueNames() {
             return = getEntityManager().createNamedQuery(
                   "Customer.listUniqueNames", String.class)
                   .getResultList();
        }
}

How to Detect Browser Back Button event - Cross Browser

In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.

if(performance.navigation.type == 2)
{
    //Do your code here
}

How do I set the path to a DLL file in Visual Studio?

  1. Go to project properties (Alt+F7)
  2. Under Debugging, look to the right
  3. There's an Environment field.
  4. Add your relative path there (relative to vcproj folder) i.e. ..\some-framework\lib by appending PATH=%PATH%;$(ProjectDir)\some-framework\lib or prepending to the path PATH=C:\some-framework\lib;%PATH%
  5. Hit F5 (debug) again and it should work.

A Space between Inline-Block List Items

just remove the breaks between li's in your html code... make the li's in one line only..

Why is my CSS bundling not working with a bin deployed MVC4 app?

Another thing to consider is the references cannot have the same name. For example, if you have jQuery UI in the libraries directory, and bundle its JavaScript file like so:

bundles.Add(new ScriptBundle("~/libraries").Include("~/libraries/jquery-ui/jqyery-ui.js"));

and then try to bundle its CSS files like so:

bundles.Add(new StyleBundle("~/libraries").Include("~/libraries/jquery-ui/jqyery-ui.css"));
...

it will fail. They have to have unique names. So do something like ScriptBundle("~/libraries/js")... and ScriptBundle("~/libraries/css")... or whatever.

Which Protocols are used for PING?

Ping can be used with a variety of protocols. The protocol value can be appletalk, clns, ip (the default), novell, apollo, vines, decnet, or xns. Some protocols require another Cisco router at the remote end to answer ping packets. ... (Cisco field manual: router configuration, By Dave Hucaby, Steve McQuerry. Page 64)

... For IP. ping uses ICMP type 8 requests and ICMP type 0 replies. The traceroute (by using UDP) command can be used to discover the routers along the path that packets are taking to a destination. ... (Page 63)

Best way to check if a URL is valid

Actually... filter_var($url, FILTER_VALIDATE_URL); doesn't work very well. When you type in a real url, it works but, it only checks for http:// so if you type something like "http://weirtgcyaurbatc", it will still say it's real.

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        tomcat.enableNaming();
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }
}

@Component
public class TomcatConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;
    }

Loading resources from context.xml doesn't work though. Will try to find out.

Room persistance library. Delete all

Here is how I have done it in Kotlin.

  1. Inject room db in the activity using DI (Koin).

     private val appDB: AppDB by inject()
    
  2. Then you can simply call clearAllTables()

private fun clearRoomDB() {
    GlobalScope.launch {
        appDB.clearAllTables()
        preferences.put(PreferenceConstants.IS_UPLOADCATEGORIES_SAVED_TO_DB, false)
        preferences.put(PreferenceConstants.IS_MEMBERHANDBOOK_SAVED_TO_DB, false)
    }
}

Python interpreter error, x takes no arguments (1 given)

Make sure, that all of your class methods (updateVelocity, updatePosition, ...) take at least one positional argument, which is canonically named self and refers to the current instance of the class.

When you call particle.updateVelocity(), the called method implicitly gets an argument: the instance, here particle as first parameter.

Change the "From:" address in Unix "mail"

On CentOS 5.5, the easiest way I've found to set the default from domain is to modify the hosts file. If your hosts file contains your WAN/public IP address, simply modify the first hostname listed for it. For example, your hosts file may look like:

...
11.22.33.44 localhost default-domain whatever-else.com
...

To make it send from whatever-else.com, simply modify it so that whatever-else.com is listed first, for example:

...
11.22.33.44 whatever-else.com localhost default-domain
...

I can't speak for any other distro (or even version of CentOS) but in my particular case, the above works perfectly.

How to install bcmath module?

For PHP 7+ version you can use only:

sudo apt install php-bcmath

dynamically set iframe src

Try this:

top.document.getElementById('AppFrame').setAttribute("src",fullPath);

How to split elements of a list?

Something like:

>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']

jquery simple image slideshow tutorial

I dont know why you havent marked on of these gr8 answers... here is another option which would enable you and anyone else visiting to control transition speed and pause time

JAVASCRIPT

$(function () {

    /* SET PARAMETERS */
    var change_img_time     = 5000; 
    var transition_speed    = 100;

    var simple_slideshow    = $("#exampleSlider"),
        listItems           = simple_slideshow.children('li'),
        listLen             = listItems.length,
        i                   = 0,

        changeList = function () {

            listItems.eq(i).fadeOut(transition_speed, function () {
                i += 1;
                if (i === listLen) {
                    i = 0;
                }
                listItems.eq(i).fadeIn(transition_speed);
            });

        };

    listItems.not(':first').hide();
    setInterval(changeList, change_img_time);

});

.

HTML

<ul id="exampleSlider">
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
    <li><img src="http://placehold.it/500x250" alt="" /></li>
</ul>

.
If your keeping this simple its easy to keep it resposive
best to visit the: DEMO

.
If you want something with special transition FX (Still responsive) - check this out
DEMO WITH SPECIAL FX

How to find array / dictionary value using key?

It's as simple as this :

$array[$key];

Easiest way to mask characters in HTML(5) text input

  1. Basic validation can be performed by choosing the type attribute of input elements. For example: <input type="email" /> <input type="URL" /> <input type="number" />

  2. using pattern attribute like: <input type="text" pattern="[1-4]{5}" />

  3. required attribute <input type="text" required />

  4. maxlength: <input type="text" maxlength="20" />

  5. min & max: <input type="number" min="1" max="4" />

Set proxy through windows command line including login parameters

The best way around this is (and many other situations) in my experience, is to use cntlm which is a local no-authentication proxy which points to a remote authentication proxy. You can then just set WinHTTP to point to your local CNTLM (usually localhost:3128), and you can set CNTLM itself to point to the remote authentication proxy. CNTLM has a "magic NTLM dialect detection" option which generates password hashes to be put into the CNTLM configuration files.

What is recursion and when should I use it?

Recursion is when you have an operation that uses itself. It probably will have a stopping point, otherwise it would go on forever.

Let's say you want to look up a word in the dictionary. You have an operation called "look-up" at your disposal.

Your friend says "I could really spoon up some pudding right now!" You don't know what he means, so you look up "spoon" in the dictionary, and it reads something like this:

Spoon: noun - a utensil with a round scoop at the end. Spoon: verb - to use a spoon on something Spoon: verb - to cuddle closely from behind

Now, being that you're really not good with English, this points you in the right direction, but you need more info. So you select "utensil" and "cuddle" to look up for some more information.

Cuddle: verb - to snuggle Utensil: noun - a tool, often an eating utensil

Hey! You know what snuggling is, and it has nothing to do with pudding. You also know that pudding is something you eat, so it makes sense now. Your friend must want to eat pudding with a spoon.

Okay, okay, this was a very lame example, but it illustrates (perhaps poorly) the two main parts of recursion. 1) It uses itself. In this example, you haven't really looked up a word meaningfully until you understand it, and that might mean looking up more words. This brings us to point two, 2) It stops somewhere. It has to have some kind of base-case. Otherwise, you'd just end up looking up every word in the dictionary, which probably isn't too useful. Our base-case was that you got enough information to make a connection between what you previously did and did not understand.

The traditional example that's given is factorial, where 5 factorial is 1*2*3*4*5 (which is 120). The base case would be 0 (or 1, depending). So, for any whole number n, you do the following

is n equal to 0? return 1 otherwise, return n * (factorial of n-1)

let's do this with the example of 4 (which we know ahead of time is 1*2*3*4 = 24).

factorial of 4 ... is it 0? no, so it must be 4 * factorial of 3 but what's factorial of 3? it's 3 * factorial of 2 factorial of 2 is 2 * factorial of 1 factorial of 1 is 1 * factorial of 0 and we KNOW factorial of 0! :-D it's 1, that's the definition factorial of 1 is 1 * factorial of 0, which was 1... so 1*1 = 1 factorial of 2 is 2 * factorial of 1, which was 1... so 2*1 = 2 factorial of 3 is 3 * factorial of 2, which was 2... so 3*2 = 6 factorial of 4 (finally!!) is 4 * factorial of 3, which was 6... 4*6 is 24

Factorial is a simple case of "base case, and uses itself".

Now, notice we were still working on factorial of 4 the entire way down... If we wanted factorial of 100, we'd have to go all the way down to 0... which might have a lot of overhead to it. In the same manner, if we find an obscure word to look up in the dictionary, it might take looking up other words and scanning for context clues until we find a connection we're familiar with. Recursive methods can take a long time to work their way through. However, when they're used correctly, and understood, they can make complicated work surprisingly simple.

convert php date to mysql format

$date = mysql_real_escape_string($_POST['intake_date']);

1. If your MySQL column is DATE type:

$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

2. If your MySQL column is DATETIME type:

$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

You haven't got to work strototime(), because it will not work with dash - separators, it will try to do a subtraction.


Update, the way your date is formatted you can't use strtotime(), use this code instead:

$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date);
echo $date;

Output:

2009-07-02 00:07:00

Capturing count from an SQL query

You'll get converting errors with:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

Use instead:

string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
    found = true; 
} else {
    found = false; 
}

Change the icon of the exe file generated from Visual Studio 2010

To specify an application icon

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. In the Icon list, choose an icon (.ico) file.

To specify an application icon and add it to your project

  1. In Solution Explorer, choose a project node (not the Solution node).
  2. On the menu bar, choose Project, Properties.
  3. When the Project Designer appears, choose the Application tab.
  4. Near the Icon list, choose the button, and then browse to the location of the icon file that you want.

The icon file is added to your project as a content file.

reference : for details see here

IIS - 401.3 - Unauthorized

  1. Create a new Site, Right Click on Sites folder then click add Site
  2. Enter the site name.
  3. Select physical path
  4. Select Ip Address
  5. Change Port
  6. Click OK
  7. Go to Application Pools
  8. Select the site pool
  9. Right-click the click Advance Settings
  10. Change the .Net CLR Version to "No Manage Code"
  11. Change the Identity to "ApplicationPoolIdentity"
  12. Go to Site home page then click "Authentication"
  13. Right-click to AnonymousAuthentication then click "Edit"
  14. Select Application Pool Identity
  15. Click ok
  16. boom!

for routes add a web.config

<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="React Routes" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

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

That approach will be good if the date-time in question is in UTC, or represents local time in an area that has never observed daylight saving time. The DateTime difference routines do not take into account Daylight Saving Time, and consequently will regard midnight June 1 as being a multiple of 24 hours after midnight January 1. I'm unaware of anything in Windows that reports historical daylight-saving rules for the current locale, so I don't think there's any good way to correctly handle any time prior to the most recent daylight-saving rule change.

How do I edit $PATH (.bash_profile) on OSX?

In Macbook, step by step:

  1. First of all open terminal and write it: cd ~/
  2. Create your bash file: touch .bash_profile

You created your ".bash_profile" file but if you would like to edit it, you should write it;

  1. Edit your bash profile: open -e .bash_profile

After you can save from top-left corner of screen: File > Save

@canerkaseler

recyclerview No adapter attached; skipping layout

i have this problem , a few time problem is recycleView put in ScrollView object

After checking implementation, the reason appears to be the following. If RecyclerView gets put into a ScrollView, then during measure step its height is unspecified (because ScrollView allows any height) and, as a result, gets equal to minimum height (as per implementation) which is apparently zero.

You have couple of options for fixing this:

  1. Set a certain height to RecyclerView
  2. Set ScrollView.fillViewport to true
  3. Or keep RecyclerView outside of ScrollView. In my opinion, this is the best option by far. If RecyclerView height is not limited - which is the case when it's put into ScrollView - then all Adapter's views have enough place vertically and get created all at once. There is no view recycling anymore which kinda breaks the purpose of RecyclerView .

(Can be followed for android.support.v4.widget.NestedScrollView as well)

Select arrow style change

You can also try this:

Heres a Picture of it!

And also run code snippet!

CSS and then HTML:

_x000D_
_x000D_
           #select-category {
            font-size: 100%;
            padding: 10px;
            padding-right: 180px;
            margin-left: 30px;
            border-radius: 1000000px;
            border: 1px solid #707070;
            outline: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background: transparent;
            background-image: url("data:image/svg+xml;utf8,<svg fill='black' height='34' viewBox='0 0 24 24' width='24' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/><path d='M0 0h24v24H0z' fill='none'/></svg>");
            background-repeat: no-repeat;
            background-position-x: 100%;
            background-position-y: 5px;
            margin-right: 2rem;
        }
_x000D_
                <select id="select-category">
                    <option>Category</option>
                    <option>Category 2</option>
                    <option>Category 3</option>
                    <option>Category 4</option>
                    <option>Category 5</option>
                    <option>Category 6</option>
                    <option>Category 7</option>
                    <option>Category 8</option>
                    <option>Category 9</option>
                    <option>Category 10</option>
                    <option>Category 11</option>
                    <option>Category 12</option>
                </select>
_x000D_
_x000D_
_x000D_

How to implement static class member functions in *.cpp file?

@crobar, you are right that there is a dearth of multi-file examples, so I decided to share the following in the hopes that it helps others:

::::::::::::::
main.cpp
::::::::::::::

#include <iostream>

#include "UseSomething.h"
#include "Something.h"

int main()
{
    UseSomething y;
    std::cout << y.getValue() << '\n';
}

::::::::::::::
Something.h
::::::::::::::

#ifndef SOMETHING_H_
#define SOMETHING_H_

class Something
{
private:
    static int s_value;
public:
    static int getValue() { return s_value; } // static member function
};
#endif

::::::::::::::
Something.cpp
::::::::::::::

#include "Something.h"

int Something::s_value = 1; // initializer

::::::::::::::
UseSomething.h
::::::::::::::

#ifndef USESOMETHING_H_
#define USESOMETHING_H_

class UseSomething
{
public:
    int getValue();
};

#endif

::::::::::::::
UseSomething.cpp
::::::::::::::

#include "UseSomething.h"
#include "Something.h"

int UseSomething::getValue()
{
    return(Something::getValue());
}

Groovy String to Date

I think the best easy way in this case is to use parseToStringDate which is part of GDK (Groovy JDK enhancements):

Parse a String matching the pattern EEE MMM dd HH:mm:ss zzz yyyy containing US-locale-constants only (e.g. Sat for Saturdays). Such a string is generated by the toString method of Date

Example:

println(Date.parseToStringDate("Tue Aug 10 16:02:43 PST 2010").format('MM-dd-yyyy'))

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

Center/Set Zoom of Map to cover all visible Markers?

To extend the given answer with few useful tricks:

var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
   bounds.extend(markers[i].getPosition());
}

//center the map to a specific spot (city)
map.setCenter(center); 

//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());

map.fitBounds(bounds);

//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1); 

// set a minimum zoom 
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
  map.setZoom(15);
}

//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
    map.setMaxZoom(15);
    map.fitBounds(bounds);
    map.setMaxZoom(Null)
}

UPDATE:
Further research in the topic show that fitBounds() is a asynchronic and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  this.setZoom(map.getZoom()-1);

  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});
map.fitBounds(bounds);

Is there a git-merge --dry-run option?

If you want to fast forward from B to A, then you must make sure that git log B..A shows you nothing, i.e. A has nothing that B doesn't have. But even if B..A has something, you might still be able to merge without conflicts, so the above shows two things: that there will be a fast-forward, and thus you won't get a conflict.

Duplicate symbols for architecture x86_64 under Xcode

Open your project in XCode

you will see the sidebar now focus on the attached image.enter image description here

Search your specific SDK or any dublicate file where you facing an issue.

You will see that you have added any file twice.

just remove that file and your issue will be resolved.

Note: you have to remove the file from that place where you add it wrongly.

FOR EXAMPLE enter image description here

Note: Just remove FBSDKCoreKit from Frameworks

Good Luck

Is the NOLOCK (Sql Server hint) bad practice?

The better solutions, when possible are:

  • Replicate your data (using log-replication) to a reporting database.
  • Use SAN snapshots and mount a consistent version of the DB
  • Use a database which has a better fundamental transaction isolation level

The SNAPSHOT transaction isolation level was created because MS was losing sales to Oracle. Oracle uses undo/redo logs to avoid this problem. Postgres uses MVCC. In the future MS's Heckaton will use MVCC, but that's years away from being production ready.

jwt check if token expired

Sadly @Andrés Montoya answer has a flaw which is related to how he compares the obj. I found a solution here which should solve this:

const now = Date.now().valueOf() / 1000

if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}
if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}

Thanks to thejohnfreeman!

SASS - use variables across multiple files

Create an index.scss and there you can import all file structure you have. I will paste you my index from an enterprise project, maybe it will help other how to structure files in css:

@import 'base/_reset';

@import 'helpers/_variables';
@import 'helpers/_mixins';
@import 'helpers/_functions';
@import 'helpers/_helpers';
@import 'helpers/_placeholders';

@import 'base/_typography';

@import 'pages/_versions';
@import 'pages/_recording';
@import 'pages/_lists';
@import 'pages/_global';

@import 'forms/_buttons';
@import 'forms/_inputs';
@import 'forms/_validators';
@import 'forms/_fieldsets';

@import 'sections/_header';
@import 'sections/_navigation';
@import 'sections/_sidebar-a';
@import 'sections/_sidebar-b';
@import 'sections/_footer';

@import 'vendors/_ui-grid';

@import 'components/_modals';
@import 'components/_tooltip';
@import 'components/_tables';
@import 'components/_datepickers';

And you can watch them with gulp/grunt/webpack etc, like:

gulpfile.js

// SASS Task

var gulp = require('gulp');
var sass = require('gulp-sass');
//var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', function(){
    return gulp
            .src('sass/**/*.scss')
            .pipe(sourcemaps.init())
            .pipe(sass().on('error', sass.logError))
            .pipe(concat('styles.css'))
            .pipe(uglifycss({
                "maxLineLen": 80,
                "uglyComments": true
            }))
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest('./build/css/'));
});

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

gulp.task('default', ['watch']);

Pretty-Printing JSON with PHP

here's the function i use myself, the api is just like json_encode, except it has a 3rd argument exclude_flags in case you want to exclude some of the default flags (like JSON_UNESCAPED_SLASHES)

function json_encode_pretty($data, int $extra_flags = 0, int $exclude_flags = 0): string
{
    // prettiest flags for: 7.3.9
    $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | (defined("JSON_UNESCAPED_LINE_TERMINATORS") ? JSON_UNESCAPED_LINE_TERMINATORS : 0) | JSON_PRESERVE_ZERO_FRACTION | (defined("JSON_THROW_ON_ERROR") ? JSON_THROW_ON_ERROR : 0);
    $flags = ($flags | $extra_flags) & ~ $exclude_flags;
    return (json_encode($data, $flags));
}

How can I convert string date to NSDate?

Swift: iOS
if we have string, convert it to NSDate,

var dataString = profileValue["dob"] as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"

// convert string into date
let dateValue:NSDate? = dateFormatter.dateFromString(dataString)

if you have and date picker parse date like this

// to avoid any nil value
if let isDate = dateValue {
self.datePicker.date = isDate
}

Get next / previous element using JavaScript?

use the nextSibling and previousSibling properties:

<div id="foo1"></div>
<div id="foo2"></div>
<div id="foo3"></div>

document.getElementById('foo2').nextSibling; // #foo3
document.getElementById('foo2').previousSibling; // #foo1

However in some browsers (I forget which) you also need to check for whitespace and comment nodes:

var div = document.getElementById('foo2');
var nextSibling = div.nextSibling;
while(nextSibling && nextSibling.nodeType != 1) {
    nextSibling = nextSibling.nextSibling
}

Libraries like jQuery handle all these cross-browser checks for you out of the box.

How to search if dictionary value contains certain string with Python

>>> myDict
{'lastName': ['Stone', 'Lee'], 'age': ['12'], 'firstName': ['Alan', 'Mary-Ann'],
 'address': ['34 Main Street, 212 First Avenue']}

>>> Set = set()

>>> not ['' for Key, Values in myDict.items() for Value in Values if 'Mary' in Value and Set.add(Key)] and list(Set)
['firstName']

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

From your stack trace, EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) occurred because dispatch_group_t was released while it was still locking (waiting for dispatch_group_leave).

According to what you found, this was what happened :

  • dispatch_group_t group was created. group's retain count = 1.
  • -[self webservice:onCompletion:] captured the group. group's retain count = 2.
  • dispatch_async(...., ^{ dispatch_group_wait(group, ...) ... }); captured the group again. group's retain count = 3.
  • Exit the current scope. group was released. group's retain count = 2.
  • dispatch_group_leave was never called.
  • dispatch_group_wait was timeout. The dispatch_async block was completed. group was released. group's retain count = 1.
  • You called this method again. When -[self webservice:onCompletion:] was called again, the old onCompletion block was replaced with the new one. So, the old group was released. group's retain count = 0. group was deallocated. That resulted to EXC_BAD_INSTRUCTION.

To fix this, I suggest you should find out why -[self webservice:onCompletion:] didn't call onCompletion block, and fix it. Then make sure the next call to the method will happen after the previous call did finish.


In case you allow the method to be called many times whether the previous calls did finish or not, you might find someone to hold group for you :

  • You can change the timeout from 2 seconds to DISPATCH_TIME_FOREVER or a reasonable amount of time that all -[self webservice:onCompletion] should call their onCompletion blocks by the time. So that the block in dispatch_async(...) will hold it for you.
    OR
  • You can add group into a collection, such as NSMutableArray.

I think it is the best approach to create a dedicate class for this action. When you want to make calls to webservice, you then create an object of the class, call the method on it with the completion block passing to it that will release the object. In the class, there is an ivar of dispatch_group_t or dispatch_semaphore_t.

Operator overloading ==, !=, Equals

I think you declared the Equals method like this:

public override bool Equals(BOX obj)

Since the object.Equals method takes an object, there is no method to override with this signature. You have to override it like this:

public override bool Equals(object obj)

If you want type-safe Equals, you can implement IEquatable<BOX>.

How to edit data in result grid in SQL Server Management Studio

Yes, This is possible. Right click on the table and Click on Edit Top 200 Rows as show in image below

enter image description here

Then click anywhere inside the result grid, to enable SQL Icon "Show Sql Pane". This will open sql editor for the table you opted to edit, here you can write your own sql query and then you can directly edit the result set of the query.

enter image description here

When do I use the PHP constant "PHP_EOL"?

From main/php.h of PHP version 7.1.1 and version 5.6.30:

#ifdef PHP_WIN32
#   include "tsrm_win32.h"
#   include "win95nt.h"
#   ifdef PHP_EXPORTS
#       define PHPAPI __declspec(dllexport)
#   else
#       define PHPAPI __declspec(dllimport)
#   endif
#   define PHP_DIR_SEPARATOR '\\'
#   define PHP_EOL "\r\n"
#else
#   if defined(__GNUC__) && __GNUC__ >= 4
#       define PHPAPI __attribute__ ((visibility("default")))
#   else
#       define PHPAPI
#   endif
#   define THREAD_LS
#   define PHP_DIR_SEPARATOR '/'
#   define PHP_EOL "\n"
#endif

As you can see PHP_EOL can be "\r\n" (on Windows servers) or "\n" (on anything else). On PHP versions prior 5.4.0RC8, there were a third value possible for PHP_EOL: "\r" (on MacOSX servers). It was wrong and has been fixed on 2012-03-01 with bug 61193.

As others already told you, you can use PHP_EOL in any kind of output (where any of these values are valid - like: HTML, XML, logs...) where you want unified newlines. Keep in mind that it's the server that it's determining the value, not the client. Your Windows visitors will get the value from your Unix server which is inconvenient for them sometimes.

I just wanted to show the possibles values of PHP_EOL backed by the PHP sources since it hasn't been shown here yet...

How do I timestamp every ping result?

You did not specify any time stamp or interval for how long you would require such output, so I considered it to be an infinite loop. You can change it accordingly as per your need.

while true
do
   echo -e "`date`|`ping -n -c 1 <IP_TO_PING>|grep 'bytes from'`"
   sleep 2
done

How to connect mySQL database using C++

Found here:

/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
   AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
  /* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column fata by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  }
  delete res;
  delete stmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " »
     << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}

Convert a Unix timestamp to time in JavaScript

_x000D_
_x000D_
let unix_timestamp = 1549312452_x000D_
// Create a new JavaScript Date object based on the timestamp_x000D_
// multiplied by 1000 so that the argument is in milliseconds, not seconds._x000D_
var date = new Date(unix_timestamp * 1000);_x000D_
// Hours part from the timestamp_x000D_
var hours = date.getHours();_x000D_
// Minutes part from the timestamp_x000D_
var minutes = "0" + date.getMinutes();_x000D_
// Seconds part from the timestamp_x000D_
var seconds = "0" + date.getSeconds();_x000D_
_x000D_
// Will display time in 10:30:23 format_x000D_
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);_x000D_
_x000D_
console.log(formattedTime);
_x000D_
_x000D_
_x000D_

For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.

Could not reliably determine the server's fully qualified domain name

If you are using windows, remove comment on these lines and set them as:

Line 227 : ServerName 127.0.0.1:80 
Line 235 : AllowOverride all 
Line 236 : Require all granted

Worked for me!

Why is document.write considered a "bad practice"?

Another legitimate use of document.write comes from the HTML5 Boilerplate index.html example.

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.3.min.js"><\/script>')</script>

I've also seen the same technique for using the json2.js JSON parse/stringify polyfill (needed by IE7 and below).

<script>window.JSON || document.write('<script src="json2.js"><\/script>')</script>

Sequence contains no elements?

Well, what is ID here? In particular, is it a local variable? There are some scope / capture issues, which mean that it may be desirable to use a second variable copy, just for the query:

var id = ID;
BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == id
                 select p).Single();

Also; if this is LINQ-to-SQL, then in the current version you get a slightly better behaviour if you use the form:

var id = ID;
BlogPost post = dc.BlogPosts.Single(p => p.BlogPostID == id);

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Is there any way to install Composer globally on Windows?

sorry to dig this up, I just want to share my idea, the easy way for me is to rename composer.phar to composer.bat and put it into my PATH.

Rerouting stdin and stdout from C

freopen("/my/newstdin", "r", stdin);
freopen("/my/newstdout", "w", stdout);
freopen("/my/newstderr", "w", stderr);

... do your stuff

freopen("/dev/stdin", "r", stdin);
...
...

This peaks the needle on my round-peg-square-hole-o-meter, what are you trying to accomplish?

Edit:

Remember that stdin, stdout and stderr are file descriptors 0, 1 and 2 for every newly created process. freopen() should keep the same fd's, just assign new streams to them.

So, a good way to ensure that this is actually doing what you want it to do would be:

printf("Stdout is descriptor %d\n", fileno(stdout));
freopen("/tmp/newstdout", "w", stdout);
printf("Stdout is now /tmp/newstdout and hopefully still fd %d\n",
   fileno(stdout));
freopen("/dev/stdout", "w", stdout);
printf("Now we put it back, hopefully its still fd %d\n",
   fileno(stdout));

I believe this is the expected behavior of freopen(), as you can see, you're still only using three file descriptors (and associated streams).

This would override any shell redirection, as there would be nothing for the shell to redirect. However, its probably going to break pipes. You might want to be sure to set up a handler for SIGPIPE, in case your program finds itself on the blocking end of a pipe (not FIFO, pipe).

So, ./your_program --stdout /tmp/stdout.txt --stderr /tmp/stderr.txt should be easily accomplished with freopen() and keeping the same actual file descriptors. What I don't understand is why you'd need to put them back once changing them? Surely, if someone passed either option, they would want it to persist until the program terminated?

Extract first and last row of a dataframe in pandas

The accepted answer duplicates the first row if the frame only contains a single row. If that's a concern

df[0::len(df)-1 if len(df) > 1 else 1]

works even for single row-dataframes.

Example: For the following dataframe this will not create a duplicate:

df = pd.DataFrame({'a': [1], 'b':['a']})
df2 = df[0::len(df)-1 if len(df) > 1  else 1]

print df2

   a  b
0  1  a

whereas this does:

df3 = df.iloc[[0, -1]]

print df3 

   a  b
0  1  a
0  1  a

because the single row is the first AND last row at the same time.

how to fix java.lang.IndexOutOfBoundsException

You do not have any elements in the list so can't access the first element.

Using Spring MVC Test to unit test multipart POST request

Here's what worked for me, here I'm attaching a file to my EmailController under test. Also take a look at the postman screenshot on how I'm posting the data.

    @WebAppConfiguration
    @RunWith(SpringRunner.class)
    @SpringBootTest(
            classes = EmailControllerBootApplication.class
        )
    public class SendEmailTest {

        @Autowired
        private WebApplicationContext webApplicationContext;

        @Test
        public void testSend() throws Exception{
            String jsonStr = "{\"to\": [\"[email protected]\"],\"subject\": "
                    + "\"CDM - Spring Boot email service with attachment\","
                    + "\"body\": \"Email body will contain  test results, with screenshot\"}";

            Resource fileResource = new ClassPathResource(
                    "screen-shots/HomePage-attachment.png");

            assertNotNull(fileResource);

            MockMultipartFile firstFile = new MockMultipartFile( 
                       "attachments",fileResource.getFilename(),
                        MediaType.MULTIPART_FORM_DATA_VALUE,
                        fileResource.getInputStream());  
                        assertNotNull(firstFile);


            MockMvc mockMvc = MockMvcBuilders.
                  webAppContextSetup(webApplicationContext).build();

            mockMvc.perform(MockMvcRequestBuilders
                   .multipart("/api/v1/email/send")
                    .file(firstFile)
                    .param("data", jsonStr))
                    .andExpect(status().is(200));
            }
        }

Postman Request

YouTube API to fetch all videos on a channel

Here is the code that will return all video ids under your channel

<?php 
    $baseUrl = 'https://www.googleapis.com/youtube/v3/';
    // https://developers.google.com/youtube/v3/getting-started
    $apiKey = 'API_KEY';
    // If you don't know the channel ID see below
    $channelId = 'CHANNEL_ID';

    $params = [
        'id'=> $channelId,
        'part'=> 'contentDetails',
        'key'=> $apiKey
    ];
    $url = $baseUrl . 'channels?' . http_build_query($params);
    $json = json_decode(file_get_contents($url), true);

    $playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];

    $params = [
        'part'=> 'snippet',
        'playlistId' => $playlist,
        'maxResults'=> '50',
        'key'=> $apiKey
    ];
    $url = $baseUrl . 'playlistItems?' . http_build_query($params);
    $json = json_decode(file_get_contents($url), true);

    $videos = [];
    foreach($json['items'] as $video)
        $videos[] = $video['snippet']['resourceId']['videoId'];

    while(isset($json['nextPageToken'])){
        $nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
        $json = json_decode(file_get_contents($nextUrl), true);
        foreach($json['items'] as $video)
            $videos[] = $video['snippet']['resourceId']['videoId'];
    }
    print_r($videos);

Note: You can get channel id at https://www.youtube.com/account_advanced after logged in.

How to upload (FTP) files to server in a bash script?

echo -e "open <ftp.hostname>\nuser <username> <password>\nbinary\nmkdir New_Folder\nquit"|ftp -nv

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

JQuery Validate input file type

So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.

So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

lexical or preprocessor issue file not found occurs while archiving?

Few things to try, Ensure the Framework and all it's headers are imported into your project properly.

Also in your Build Settings set YES to Always search user paths, and make sure your User header paths are pointing to the Framework.

Finally, Build->Clean and Restart Xcode.

Hope this helps !

UPDATE: According to SDWebImage's installation, it's required you make a modification to Header Search Path and not User header paths, As seen below.

enter image description here

Have you done this as well? I suggest slowly, re-doing all the installation steps from the beginning.

HTML - Arabic Support

i edit the html page with notepad ++ ,set encoding to utf-8 and its work

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

To keep this question current it is worth highlighting that AssemblyInformationalVersion is used by NuGet and reflects the package version including any pre-release suffix.

For example an AssemblyVersion of 1.0.3.* packaged with the asp.net core dotnet-cli

dotnet pack --version-suffix ci-7 src/MyProject

Produces a package with version 1.0.3-ci-7 which you can inspect with reflection using:

CustomAttributeExtensions.GetCustomAttribute<AssemblyInformationalVersionAttribute>(asm);

How to find the mime type of a file in python?

You didn't state what web server you were using, but Apache has a nice little module called Mime Magic which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as Dave Webb Mentioned the MimeTypes Module under python will work, provided an extension is handy.

Alternatively, if you are sitting on a UNIX box you can use sys.popen('file -i ' + fileName, mode='r') to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is.

Why use def main()?

if the content of foo.py

print __name__
if __name__ == '__main__':
    print 'XXXX'

A file foo.py can be used in two ways.

  • imported in another file : import foo

In this case __name__ is foo, the code section does not get executed and does not print XXXX.

  • executed directly : python foo.py

When it is executed directly, __name__ is same as __main__ and the code in that section is executed and prints XXXX

One of the use of this functionality to write various kind of unit tests within the same module.

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

If primary key is not already defined on parent table then this issue may arise. Please try to define the primary key on existing table. For eg:

ALTER TABLE table_name
ADD PRIMARY KEY (the_column_which_is_primary_key);

How to check if multiple array keys exists

Hope this helps:

function array_keys_exist($searchForKeys = array(), $inArray = array()) {
    $inArrayKeys = array_keys($inArray);
    return count(array_intersect($searchForKeys, $inArrayKeys)) == count($searchForKeys); 
}

How to export and import a .sql file from command line with options?

mysqldump will not dump database events, triggers and routines unless explicitly stated when dumping individual databases;

mysqldump -uuser -p db_name --events --triggers --routines > db_name.sql

Assign command output to variable in batch file

Okay here some more complex sample for the use of For /F

:: Main
@prompt -$G
    call :REGQUERY  "Software\Classes\CLSID\{3E6AE265-3382-A429-56D1-BB2B4D1D}"

@goto :EOF

:REGQUERY
:: Checks HKEY_LOCAL_MACHINE\ and HKEY_CURRENT_USER\ 
:: for the key and lists its content

    @call :EXEC "REG QUERY  HKCU\%~1"
    @call :EXEC "REG QUERY "HKLM\%~1""

@goto :EOF    

:EXEC
    @set output=

    @for /F "delims=" %%i in ('%~1 2^>nul') do @(
        set output=%%i
    )

    @if not "%output%"=="" (
        echo %1 -^> %output%
    )

@goto :EOF

I packed it into the sub function :EXEC so all of its nasty details of implementation doesn't litters the main script. So it got some kinda some batch tutorial. Notes 'bout the code:

  1. the output from the command executed via call :EXEC command is stored in %output%. Batch cmd doesn't cares about scopes so %output% will be also available in the main script.
  2. the @ the beginning is just decoration and there to suppress echoing the command line. You may delete them all and just put some @echo off at the first line is really dislike that. However like this I find debugging much more nice. Decoration Number two is prompt -$G. It's there to make command prompt look like this ->
  3. I use :: instead of rem
  4. the tilde(~) in %~1 is to remove quotes from the first argument
  5. 2^>nul is there to suppress/discard stderr error output. Normally you would do it via 2>nul. Well the ^ the batch escape char is there avoids to early resolving the redirector(>). There's some simulare use a little later in the script: echo %1 -^>... so there ^ makes it possible the output a '>' via echo what else wouldn't have been possible.
  6. even if the compare at @if not "%output%"==""looks like in most common programming languages - it's maybe different that you expected (if you're not used to MS-batch). Well remove the '@' at the beginning. Study the output. Change it tonot %output%==""-rerun and consider why this doesn't work. ;)

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

Accessing Websites through a Different Port?

Perhaps this is obvious, but FWIW this will only work if the web server is serving requests for that website on the alternate port. It's not at all uncommon for a webserver to only serve a site on port 80.

Difference between binary semaphore and mutex

Mutex and binary semaphore are both of the same usage, but in reality, they are different.

In case of mutex, only the thread which have locked it can unlock it. If any other thread comes to lock it, it will wait.

In case of semaphone, that's not the case. Semaphore is not tied up with a particular thread ID.

Xcode 7.2 no matching provisioning profiles found

For me changing the build configuration from release to Debug solved the issue.

You can find Build Configuration in Edit Scheme -> Run -> Info -> Build Configuration

Clean your project and re run.

Is it possible to specify condition in Count()?

If using Postgres or SQLite, you can use the Filter clause to improve readability:

SELECT
  COUNT(1) FILTER (WHERE POSITION = 'Manager') AS ManagerCount,
  COUNT(1) FILTER (WHERE POSITION = 'Other') AS OtherCount
FROM ...

BigQuery also has Countif - see the support across different SQL dialects for these features here: https://modern-sql.com/feature/filter

onSaveInstanceState () and onRestoreInstanceState ()

The state you save at onSaveInstanceState() is later available at onCreate() method invocation. So use onCreate (and its Bundle parameter) to restore state of your activity.

How to convert all tables from MyISAM into InnoDB?

SELECT CONCAT('ALTER TABLE ',TABLE_NAME,' ENGINE=InnoDB;') 
FROM INFORMATION_SCHEMA.TABLES
WHERE ENGINE='MyISAM'
AND table_schema = 'mydatabase';

Works like a charm.

This will give you list of all tables with the alter queries that you can run in a batch

Grab a segment of an array in Java without creating a new array on heap

Java references always point to an object. The object has a header that amongst other things identifies the concrete type (so casts can fail with ClassCastException). For arrays, the start of the object also includes the length, the data then follows immediately after in memory (technically an implementation is free to do what it pleases, but it would be daft to do anything else). So, you can;t have a reference that points somewhere into an array.

In C pointers point anywhere and to anything, and you can point to the middle of an array. But you can't safely cast or find out how long the array is. In D the pointer contains an offset into the memory block and length (or equivalently a pointer to the end, I can't remember what the implementation actually does). This allows D to slice arrays. In C++ you would have two iterators pointing to the start and end, but C++ is a bit odd like that.

So getting back to Java, no you can't. As mentioned, NIO ByteBuffer allows you to wrap an array and then slice it, but gives an awkward interface. You can of course copy, which is probably very much faster than you would think. You could introduce your own String-like abstraction that allows you to slice an array (the current Sun implementation of String has a char[] reference plus a start offset and length, higher performance implementation just have the char[]). byte[] is low level, but any class-based abstraction you put on that is going to make an awful mess of the syntax, until JDK7 (perhaps).

Is it possible to embed animated GIFs in PDFs?

I just had to figure this out for a client presentation and found a work around to having the GIF play a few times by making a fake loop.

  • Open the Gif in Photoshop
  • View the timeline
  • Select all the instances and duplicate them (I did it 10 times)
  • Export as a MP4
  • Open up your PDF and go to TOOLS> RICH MEDIA>ADD VIDEO> then place the video of your gif where you would want it
  • A window comes up, be sure to click on SHOW ADVANCED OPTIONS
  • Choose your file and right underneath select ENABLE WHEN CONTENT IS VISIBLE

Hope this helps.

How to check if click event is already bound - JQuery

Update 24 Aug '12: In jQuery 1.8, it is no longer possible to access the element's events using .data('events'). (See this bug for details.) It is possible to access the same data with jQuery._data(elem, 'events'), an internal data structure, which is undocumented and therefore not 100% guaranteed to remain stable. This shouldn't, however, be a problem, and the relevant line of the plugin code above can be changed to the following:

var data = jQuery._data(this[0], 'events')[type];

jQuery events are stored in a data object called events, so you could search in this:

var button = $('#myButton');
if (-1 !== $.inArray(onButtonClicked, button.data('events').click)) {
    button.click(onButtonClicked);
}

It would be best, of course, if you could structure your application so this code only gets called once.


This could be encapsulated into a plugin:

$.fn.isBound = function(type, fn) {
    var data = this.data('events')[type];

    if (data === undefined || data.length === 0) {
        return false;
    }

    return (-1 !== $.inArray(fn, data));
};

You could then call:

var button = $('#myButton');
if (!button.isBound('click', onButtonClicked)) {
    button.click(onButtonClicked);
}

Good way to encapsulate Integer.parseInt()

There is Ints.tryParse() in Guava. It doesn't throw exception on non-numeric string, however it does throw exception on null string.

How to fetch data from local JSON file on react native?

maybe you could use AsyncStorage setItem and getItem...and store the data as string, then use the json parser for convert it again to json...

Matlab: Running an m-file from command-line

A command like this runs the m-file successfully:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m'); exit;"

Why is using the JavaScript eval function a bad idea?

If you spot the use of eval() in your code, remember the mantra “eval() is evil.”

This function takes an arbitrary string and executes it as JavaScript code. When the code in question is known beforehand (not determined at runtime), there’s no reason to use eval(). If the code is dynamically generated at runtime, there’s often a better way to achieve the goal without eval(). For example, just using square bracket notation to access dynamic properties is better and simpler:

// antipattern
var property = "name";
alert(eval("obj." + property));

// preferred
var property = "name";
alert(obj[property]);

Using eval() also has security implications, because you might be executing code (for example coming from the network) that has been tampered with. This is a common antipattern when dealing with a JSON response from an Ajax request. In those cases it’s better to use the browsers’ built-in methods to parse the JSON response to make sure it’s safe and valid. For browsers that don’t support JSON.parse() natively, you can use a library from JSON.org.

It’s also important to remember that passing strings to setInterval(), setTimeout(), and the Function() constructor is, for the most part, similar to using eval() and therefore should be avoided.

Behind the scenes, JavaScript still has to evaluate and execute the string you pass as programming code:

// antipatterns
setTimeout("myFunc()", 1000);
setTimeout("myFunc(1, 2, 3)", 1000);

// preferred
setTimeout(myFunc, 1000);
setTimeout(function () {
myFunc(1, 2, 3);
}, 1000);

Using the new Function() constructor is similar to eval() and should be approached with care. It could be a powerful construct but is often misused. If you absolutely must use eval(), you can consider using new Function() instead.

There is a small potential benefit because the code evaluated in new Function() will be running in a local function scope, so any variables defined with var in the code being evaluated will not become globals automatically.

Another way to prevent automatic globals is to wrap the eval() call into an immediate function.

Why check both isset() and !empty()

  • From the PHP Web site, referring to the empty() function:

Returns FALSE if var has a non-empty and non-zero value.

That’s a good thing to know. In other words, everything from NULL, to 0 to “” will return TRUE when using the empty() function.

  • Here is the description of what the isset() function returns:

Returns TRUE if var exists; FALSE otherwise.

In other words, only variables that don’t exist (or, variables with strictly NULL values) will return FALSE on the isset() function. All variables that have any type of value, whether it is 0, a blank text string, etc. will return TRUE.

How to increase apache timeout directive in .htaccess?

if you have long processing server side code, I don't think it does fall into 404 as you said ("it goes to a webpage is not found error page")

Browser should report request timeout error.

You may do 2 things:

Based on CGI/Server side engine increase timeout there

PHP : http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time - default is 30 seconds

In php.ini:

max_execution_time 60

Increase apache timeout - default is 300 (in version 2.4 it is 60).

In your httpd.conf (in server config or vhost config)

TimeOut 600

Note that first setting allows your PHP script to run longer, it will not interferre with network timeout.

Second setting modify maximum amount of time the server will wait for certain events before failing a request

Sorry, I'm not sure if you are using PHP as server side processing, but if you provide more info I will be more accurate.

Fastest way to get the first object from a queryset in django?

You should use django methods, like exists. Its there for you to use it.

if qs.exists():
    return qs[0]
return None

In bootstrap how to add borders to rows without adding up?

You can remove the border from top if the element is sibling of the row . Add this to css :

.row + .row {
   border-top:0;
}

Here is the link to the fiddle http://jsfiddle.net/7cb3Y/3/

Java - Including variables within strings?

Since Java 15, you can use a non-static string method called String::formatted(Object... args)

Example:

String foo = "foo";
String bar = "bar";

String str = "First %s, then %s".formatted(foo, bar);     

Output:

"First foo, then bar"

JavaScript get window X/Y position for scroll

The method jQuery (v1.10) uses to find this is:

var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

That is:

  • It tests for window.pageXOffset first and uses that if it exists.
  • Otherwise, it uses document.documentElement.scrollLeft.
  • It then subtracts document.documentElement.clientLeft if it exists.

The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.

Make an html number input always display 2 decimal places

Pure html is not able to do what you want. My suggestion would be to write a simple javascript function to do the roudning for you.

Difference between a User and a Login in SQL Server

In Short,

Logins will have the access of the server.

and

Users will have the access of the database.

How to send UTF-8 email?

I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:

function utf8_to_latin2($str)
{
    return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
    {
        mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
        "From: $form\r\n".
        "Reply-To: $reply\r\n".
        "X-Mailer: PHP/" . phpversion());
    }

I have made another mailer function, because apple device could not read well the previous version.

function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
    $s= "=?utf-8?b?".base64_encode($s)."?=";
    $headers = "MIME-Version: 1.0\r\n";
    $headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
    $headers.= "Content-Type: text/plain;charset=utf-8\r\n";
    $headers.= "Reply-To: $reply\r\n";  
    $headers.= "X-Mailer: PHP/" . phpversion();
    mail($to, $s, $body, $headers);
}

Set Locale programmatically

As of 2020 language management become easy! All you have to do is:

  1. Call to Activity.applyOverrideConfiguration
  2. And call to Locale.setDefault

You must call those from the activity constructor since you can call to applyOverrideConfiguration only once, and the system calls it pretty early.

And watch out from app-bundles, Google will split your APK by language resources automatically when using app-bundles. Check out the new API and the workaround here.


I created a helper class to help you with it. In my implementation G.app is the application context. Also, I need to access resources from the app context so I use the Res class for it, this one is optional, but I provide its code as well.

Usage

public BaseActivity(){
    LanguageUtility.init(this);
}

public void changeLanguage(Local local){
    // you must recreat your activity after you call this
    LanguageUtillity.setDefaultLanguage(local, this);
}

Source code

public class LanguageUtility {

    private static Configuration configuration;

    public static void setDefaultLanguage(Locale locale, Context context) {
        Locale.setDefault(locale);

        context.getSharedPreferences("LocaleSettings", Context.MODE_PRIVATE)
                .edit()
                .putString("language", locale.getLanguage())
                .putString("country", locale.getCountry())
                .putString("variant", locale.getVariant())
                .apply();

        configuration = createConfiguration(context);
        Res.updateContext();
    }

    /**
     * Used to update your app context in case you cache it.
     */
    public static Context createConfigurationContext(Context context) {
        return context.createConfigurationContext(getConfiguration(context));
    }

    public static void init(Activity activity) {
        activity.applyOverrideConfiguration(LanguageUtility.getConfiguration(G.app));
        // you can't access sharedPrefferences from activity constructor 
        // with activity context, so I used the app context.
        Locale.setDefault(getLocale(G.app));
    }

    @NotNull
    private static Configuration getConfiguration(Context context) {
        if (configuration == null) {
            configuration = createConfiguration(context);
        }
        return configuration;
    }

    @NotNull
    private static Configuration createConfiguration(Context context) {
        Locale locale = getLocale(context);
        Configuration configuration = new Configuration();
        configuration.setLocale(locale);
        LanguageUtility.configuration = configuration;
        return configuration;
    }

    @NotNull
    private static Locale getLocale(Context context) {
        Locale aDefault = Locale.getDefault();
        SharedPreferences preferences =
                context.getSharedPreferences("LocaleSettings", Context.MODE_PRIVATE);
        String language = preferences.getString("language", aDefault.getLanguage());
        String country = preferences.getString("country", aDefault.getCountry());
        String variant = preferences.getString("variant", aDefault.getVariant());
        return new Locale(language, country, variant);
    }
}

An optional Res class.

public class Res {

    @SuppressLint("StaticFieldLeak")
    public static Context appLocalContext = LanguageUtility.createConfigurationContext(G.app);

    public static void updateContext() {
        appLocalContext = LanguageUtility.createConfigurationContext(G.app);
    }

    public static String getString(@StringRes int id, Object... formatArgs) {
        return appLocalContext.getResources().getString(id, formatArgs);
    }

    public static int getColor(@ColorRes int id) {
        return G.app.getColor(id);
    }
}

Accessing Imap in C#

MailSystem.NET contains all your need for IMAP4. It's free & open source.

(I'm involved in the project)

Using Gradle to build a jar with dependencies

Gradle 6.3, Java library. The code from "jar task" adds the dependencies to the "build/libs/xyz.jar" when running "gradle build" task.

plugins {
    id 'java-library'
}

jar {
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

Get the data received in a Flask request

To get the raw data, use request.data. This only works if it couldn't be parsed as form data, otherwise it will be empty and request.form will have the parsed data.

from flask import request
request.data

Replace all occurrences of a String using StringBuilder?

Look at JavaDoc of replaceAll method of String class:

Replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)

As you can see you can use Pattern and Matcher to do that.

Swift error : signal SIGABRT how to solve it

For me, This error was because i had a prepare segue step that wasn't applicable to the segue that was being done.

long story:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let gosetup = segue.destination as! Update
        gosetup.wherefrom = updatestring

    }

This was being done to all segue when it was only for one. So i create a boolean and placed the gosetup inside it.

NSUserDefaults - How to tell if a key exists

"objectForKey will return nil if it doesn't exist." It will also return nil if it does exist and it is either an integer or a boolean with a value of zero (i.e. FALSE or NO for the boolean).

I've tested this in the simulator for both 5.1 and 6.1. This means that you cannot really test for either integers or booleans having been set by asking for "the object". You can get away with this for integers if you don't mind treating "not set" as if it were "set to zero".

The people who already tested this appear to have been fooled by the false negative aspect, i.e. testing this by seeing if objectForKey returns nil when you know the key hasn't been set but failing to notice that it also returns nil if the key has been set but has been set to NO.

For my own problem, that sent me here, I just ended up changing the semantics of my boolean so that my desired default was in congruence with the value being set to NO. If that's not an option, you'll need to store as something other than a boolean and make sure that you can tell the difference between YES, NO, and "not set."

How to style the menu items on an Android action bar

Instead of having the android:actionMenuTextAppearance item under your action bar style, move it under your app theme.

git: fatal unable to auto-detect email address

1st Step : Go for the workstation In my case -> cd /c/Users/rashni/MyWS/WSpace

2nd Step : create a folder In my case -> mkdir config

3rd step : use command In my case -> git config --global user.name "rashni" In my case -> git config --global user.email [email protected]

4th step : To check all configuration(optional) In my case -> git config --list

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

foreach vs someList.ForEach(){}

The second way you showed uses an extension method to execute the delegate method for each of the elements in the list.

This way, you have another delegate (=method) call.

Additionally, there is the possibility to iterate the list with a for loop.

React - clearing an input value after form submit

this.mainInput doesn't actually point to anything. Since you are using a controlled component (i.e. the value of the input is obtained from state) you can set this.state.city to null:

onHandleSubmit(e) {
  e.preventDefault();
  const city = this.state.city;
  this.props.onSearchTermChange(city);
  this.setState({ city: '' });
}

MySQL 'create schema' and 'create database' - Is there any difference

Database is a collection of schemas and schema is a collection of tables. But in MySQL they use it the same way.

Why can a function modify some arguments as perceived by the caller, but not others?

My general understanding is that any object variable (such as a list or a dict, among others) can be modified through its functions. What I believe you are not able to do is reassign the parameter - i.e., assign it by reference within a callable function.

That is consistent with many other languages.

Run the following short script to see how it works:

def func1(x, l1):
    x = 5
    l1.append("nonsense")

y = 10
list1 = ["meaning"]
func1(y, list1)
print(y)
print(list1)

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

Further to the answer by Jon Skeet, which uses this example code:

// Illegal code - because otherwise life would be Bad
List<Dog> dogs = new ArrayList<Dog>(); // ArrayList implements List
List<Animal> animals = dogs; // Awooga awooga
animals.add(new Cat());
Dog dog = dogs.get(0); // This should be safe, right?

At the deepest level, the problem here is that dogs and animals share a reference. That means that one way to make this work would be to copy the entire list, which would break reference equality:

// This code is fine
List<Dog> dogs = new ArrayList<Dog>();
dogs.add(new Dog());
List<Animal> animals = new ArrayList<>(dogs); // Copy list
animals.add(new Cat());
Dog dog = dogs.get(0);   // This is fine now, because it does not return the Cat

After calling List<Animal> animals = new ArrayList<>(dogs);, you cannot subsequently directly assign animals to either dogs or cats:

// These are both illegal
dogs = animals;
cats = animals;

therefore you can't put the wrong subtype of Animal into the list, because there is no wrong subtype -- any object of subtype ? extends Animal can be added to animals.

Obviously, this changes the semantics, since the lists animals and dogs are no longer shared, so adding to one list does not add to the other (which is exactly what you want, to avoid the problem that a Cat could be added to a list that is only supposed to contain Dog objects). Also, copying the entire list can be inefficient. However, this does solve the type equivalence problem, by breaking reference equality.

Android ListView Text Color

I needed to make a ListView with items of different colors. I modified Shardul's method a bit and result in this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, colorString) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setBackgroundColor(assignBackgroundColor(position));
                textView.setTextColor(assignTextColor(position));
                return textView;
            }
        };
        colorList.setAdapter(adapter);

assignBackgroundColor() and assignTextColor() are methods that assign color you want. They can be replaced with int[] arrays.

How to add spacing between UITableViewCell

I solved it like this way in Swift 4.

I create a extension of UITableViewCell and include this code:

override open var frame: CGRect {
    get {
        return super.frame
    }
    set (newFrame) {
        var frame =  newFrame
        frame.origin.y += 10
        frame.origin.x += 10
        frame.size.height -= 15
        frame.size.width -= 2 * 10
        super.frame = frame
    }
}

override open func awakeFromNib() {
    super.awakeFromNib()
    layer.cornerRadius = 15
    layer.masksToBounds = false
}

I hope it helps you.

How to POST JSON data with Python Requests?

From requests 2.4.2 (https://pypi.python.org/pypi/requests), the "json" parameter is supported. No need to specify "Content-Type". So the shorter version:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})

Regex to remove letters, symbols except numbers

You can use \D which means non digits.

var removedText = self.val().replace(/\D+/g, '');

jsFiddle.

You could also use the HTML5 number input.

<input type="number" name="digit" />

jsFiddle.

Converting XML to JSON using Python?

While the built-in libs for XML parsing are quite good I am partial to lxml.

But for parsing RSS feeds, I'd recommend Universal Feed Parser, which can also parse Atom. Its main advantage is that it can digest even most malformed feeds.

Python 2.6 already includes a JSON parser, but a newer version with improved speed is available as simplejson.

With these tools building your app shouldn't be that difficult.

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

To get directory of executing script

 print os.path.dirname( inspect.getfile(inspect.currentframe()))

Make more than one chart in same IPython Notebook cell

Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.

df.plot(subplots=True)

If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df with df[['korisnika','osiguranika']].

Label points in geom_point

Use geom_text , with aes label. You can play with hjust, vjust to adjust text position.

ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
  geom_point() +geom_text(aes(label=Name),hjust=0, vjust=0)

enter image description here

EDIT: Label only values above a certain threshold:

  ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
  geom_point() +
  geom_text(aes(label=ifelse(PTS>24,as.character(Name),'')),hjust=0,vjust=0)

chart with conditional labels

How to generate class diagram from project in Visual Studio 2013?

For creating real UML class diagrams:

In Visual Studio 2013 Ultimate you can do this without any external tools.

  • In the menu, click on Architecture, New Diagram Select UML Class Diagram
  • This will ask you to create a new Modeling Project if you don't have one already.

You will have a empty UMLClassDiagram.classdiagram.

  • Again, go to Architecture, Windows, Architecture Explorer.
  • A window will pop up with your namespaces, Choose Class View.
  • Then a list of sub-namespaces will appear, if any. Choose one, select the classes and drag them to the empty UMLClassDiagram1.classdiagram window.

Reference: Create UML Class Diagrams from Code

git - Your branch is ahead of 'origin/master' by 1 commit

If you just want to throw away the changes and revert to the last commit (the one you wanted to share):

git reset --hard HEAD~

You may want to check to make absolutely sure you want this (git log), because you'll loose all changes.

A safer alternative is to run

git reset --soft HEAD~ # reset to the last commit
git stash              # stash all the changes in the working tree 
git push               # push changes 
git stash pop          # get your changes back 

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

Try to change where Member class

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');

How can I replace newlines using PowerShell?

With -Raw you should get what you expect

How can I convert a long to int in Java?

Since Java 8 you can use: Math.toIntExact(long value)

See JavaDoc: Math.toIntExact

Returns the value of the long argument; throwing an exception if the value overflows an int.

Source code of Math.toIntExact in JDK 8:

public static int toIntExact(long value) {
    if ((int)value != value) {
        throw new ArithmeticException("integer overflow");
    }
    return (int)value;
}

jQuery - how to check if an element exists?

Assuming you are trying to find if a div exists

$('div').length ? alert('div found') : alert('Div not found')

Check working example at http://jsfiddle.net/Qr86J/1/

SQL Query to concatenate column values from multiple rows in Oracle

Before you run a select query, run this:

SET SERVEROUT ON SIZE 6000

SELECT XMLAGG(XMLELEMENT(E,SUPLR_SUPLR_ID||',')).EXTRACT('//text()') "SUPPLIER" 
FROM SUPPLIERS;

How to center icon and text in a android button with width set to "fill parent"

I know this question is a bit older, but perhaps you're still open for hints or workarounds:

Create a RelativeLayout "wrap_content" with the button image as the background or the button itself as the first element of the layout. Get a LinearLayout and set it to "layout_centerInParent" and "wrap_content". Then set your Drawable as an Imageview. At last set a TextView with your text (locale).

so basically you have this structure:

RelativeLayout
  Button
    LinearLayout
      ImageView
      TextView

or like this:

RelativeLayout with "android-specific" button image as background
  LinearLayout
    ImageView
    TextView

I know with this solution there are many elements to deal with, but you can create very easy your own custom button with it and also set the exact position of text and drawables :)

PHP mysql insert date format

The simplest method is

$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];

$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());

Saving and Reading Bitmaps/Images from Internal memory in Android

    public static String saveImage(String folderName, String imageName, RelativeLayout layoutCollage) {
        String selectedOutputPath = "";
        if (isSDCARDMounted()) {
            File mediaStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
            // Create a storage directory if it does not exist
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("PhotoEditorSDK", "Failed to create directory");
                }
            }
            // Create a media file name
            selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
            Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
            File file = new File(selectedOutputPath);
            try {
                FileOutputStream out = new FileOutputStream(file);
                if (layoutCollage != null) {
                    layoutCollage.setDrawingCacheEnabled(true);
                    layoutCollage.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
                }
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return selectedOutputPath;
    }



private static boolean isSDCARDMounted() {
        String status = Environment.getExternalStorageState();
        return status.equals(Environment.MEDIA_MOUNTED);
    }

How to increase Java heap space for a tomcat app

you can set this in catalina.sh as CATALINA_OPTS=-Xms512m -Xmx512m

Open your tomcat-dir/bin/catalina.sh file and add following line anywhere -

CATALINA_OPTS="$CATALINA_OPTS -Xms1024m -Xmx3024m"

and restart your tomcat

How to Debug Variables in Smarty like in PHP var_dump()

In smarty there is built in modifier you could use that by using | (single pipeline operator). Like this {$varname|@print_r} will print value as print_r($php_variable)

Is there a simple way to convert C++ enum to string?

Note that your conversion function should ideally be returning a const char *.

If you can afford to put your enums in their separate header files, you could perhaps do something like this with macros (oh, this will be ugly):

#include "enum_def.h"
#include "colour.h"
#include "enum_conv.h"
#include "colour.h"

Where enum_def.h has:

#undef ENUM_START
#undef ENUM_ADD
#undef ENUM_END
#define ENUM_START(NAME) enum NAME {
#define ENUM_ADD(NAME, VALUE) NAME = VALUE,
#define ENUM_END };

And enum_conv.h has:

#undef ENUM_START
#undef ENUM_ADD
#undef ENUM_END
#define ENUM_START(NAME) const char *##NAME##_to_string(NAME val) { switch (val) {
#define ENUM_ADD(NAME, VALUE) case NAME: return #NAME;
#define ENUM_END default: return "Invalid value"; } }

And finally, colour.h has:

ENUM_START(colour)
ENUM_ADD(red,   0xff0000)
ENUM_ADD(green, 0x00ff00)
ENUM_ADD(blue,  0x0000ff)
ENUM_END

And you can use the conversion function as:

printf("%s", colour_to_string(colour::red));

This is ugly, but it's the only way (at the preprocessor level) that lets you define your enum just in a single place in your code. Your code is therefore not prone to errors due to modifications to the enum. Your enum definition and the conversion function will always be in sync. However, I repeat, this is ugly :)

How to connect to MongoDB in Windows?

I found that when I got this error it wasn't because I didn't have my default db path set up. It was because I was trying to run mongo.exe before running mongod.exe.

CardView background color always white

Kotlin for XML

app:cardBackgroundColor="@android:color/red"

code

cardName.setCardBackgroundColor(ContextCompat.getColor(this, R.color.colorGray));

React router nav bar example

Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.

Nav.js

  import React from 'react';
  import { Link } from 'react-router';

  export default class Nav extends React.Component {
    render() {    
      return (
        <nav className="Nav">
          <div className="Nav__container">
            <Link to="/" className="Nav__brand">
              <img src="logo.svg" className="Nav__logo" />
            </Link>

            <div className="Nav__right">
              <ul className="Nav__item-wrapper">
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path1">Link 1</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path2">Link 2</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path3">Link 3</Link>
                </li>
              </ul>
            </div>
          </div>
        </nav>
      );
    }
  }

App.js

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
            <div>
              <Nav />
              <Switch>
                <Route exactly component={Landing} pattern="/" />
                <Route exactly component={Page1} pattern="/path1" />
                <Route exactly component={Page2} pattern="/path2" />
                <Route exactly component={Page3} pattern="/path3" />
                <Route component={Page404} />
              </Switch>
            </div>
          </Router>
        </div>
      );
    }
  }

Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar

Edit

A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  const NavRoute = ({exact, path, component: Component}) => (
    <Route exact={exact} path={path} render={(props) => (
      <div>
        <Header/>
        <Component {...props}/>
      </div>
    )}/>
  )

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
              <Switch>
                <NavRoute exactly component={Landing} pattern="/" />
                <Route exactly component={Login} pattern="/login" />
                <NavRoute exactly component={Page1} pattern="/path1" />
                <NavRoute exactly component={Page2} pattern="/path2" />
                <NavRoute component={Page404} />
              </Switch>
          </Router>
        </div>
      );
    }
  }

When to use cla(), clf() or close() for clearing a plot in matplotlib?

There is just a caveat that I discovered today. If you have a function that is calling a plot a lot of times you better use plt.close(fig) instead of fig.clf() somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).

So the the following script will produce an empty list:

for i in range(5):
    fig = plot_figure()
    plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())

Whereas this one will produce a list with five figures on it.

for i in range(5):
    fig = plot_figure()
    fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())

From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.

If you want to try a complete script there you have:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    plt.close(fig)

print(plt.get_fignums())

for i in range(5):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, y)
    fig.clf()

print(plt.get_fignums())

If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

Different ways of loading a file as an InputStream

There are subtle differences as to how the fileName you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently.

In Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.class.getResourceAsStream("myfile.txt") will look for a file in your classpath at the following location: "java/lang/myfile.txt". If your path starts with a /, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.class.getResourceAsStream("/myfile.txt") will look at the following location in your class path ./myfile.txt.

ClassLoader.getResourceAsStream(path) will consider all paths to be absolute paths. So calling String.class.getClassLoader().getResourceAsStream("myfile.txt") and String.class.getClassLoader().getResourceAsStream("/myfile.txt") will both look for a file in your classpath at the following location: ./myfile.txt.

Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.

In your case, you are loading the class from an Application Server, so your should use Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) instead of this.getClass().getClassLoader().getResourceAsStream(fileName). this.getClass().getResourceAsStream() will also work.

Read this article for more detailed information about that particular problem.


Warning for users of Tomcat 7 and below

One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.

So I've looked at the source code of Tomcat's WebAppClassLoader for several versions of Tomcat. The implementation of findResource(String name) (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.

In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, classLoader.getResourceAsStream("/resource.txt") may not produce the same result as classLoader.getResourceAsStream("resource.txt") event though it should (since that what the Javadoc specifies). [source code]

In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. [source code]

As a result, you have to be extra careful when using ClassLoader.getResourceAsStream() or Class.getResourceAsStream() on Tomcat versions earlier than 8. And you must also keep in mind that class.getResourceAsStream("/resource.txt") actually calls classLoader.getResourceAsStream("resource.txt") (the leading / is stripped).