Programs & Examples On #Parser combinators

In functional programming, a parser combinator is a higher-order function which accepts several parsers as input and returns a new parser as its output.

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

Where is Developer Command Prompt for VS2013?

Since any solution given so far will open the command prompt on the project folder, you would still have to navigate to the project's folder. If you are interested in getting the command prompt directly into the project's folder, here is my 2 steps:

  1. Right-click in solution explorer on the project name (just under the solution name) and choose the command "Open Folder in File Explorer"
  2. Once the Windows Explorer is open, just type in the address bar "cmd" and then hit enter!

Et voila! Hope that helps

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

null is for database and blank is for fields validation that you want to show on user interface like textfield to get the last name of person. If lastname=models.charfield (blank=true) it didnot ask user to enter last name as this is the optional field now. If lastname=models.charfield (null=true) then it means that if this field doesnot get any value from user then it will store in database as an empty string " ".

How to display svg icons(.svg files) in UI using React Component?

Just write require with path inside the src of image. it will work. like:

<img alt="Clock" src={require('../assets/images/search_icon.svg')}/>

Malformed String ValueError ast.literal_eval() with String representation of Tuple

From the documentation for ast.literal_eval():

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Decimal isn't on the list of things allowed by ast.literal_eval().

Is there a way to add/remove several classes in one single instruction with classList?

Assume that you have an array of classes to being added, you can use ES6 spread syntax:

let classes = ['first', 'second', 'third']; elem.classList.add(...classes);

How can I remove all my changes in my SVN working directory?

If you have no changes, you can always be really thorough and/or lazy and do...

rm -rf *
svn update

But, no really, do not do that unless you are really sure that the nuke-from-space option is what you want!! This has the advantage of also nuking all build cruft, temporary files, and things that SVN ignores.

The more correct solution is to use the revert command:

svn revert -R .

The -R causes subversion to recurse and revert everything in and below the current working directory.

Create Table from View

SQL Server does not support CREATE TABLE AS SELECT.

Use this:

SELECT  *
INTO    A
FROM    myview

or

SELECT  TOP 10
        *
INTO    A
FROM    myview
ORDER BY
        id

Docker is installed but Docker Compose is not ? why?

I'm installing on a Raspberry Pi 3, with Raspbian 8. The curl method failed for me (got a line 1: Not: command not found error upon asking for docker-compose --version) and the solution of @sunapi386 seemed a little out-dated, so I tried this which worked:

First clean things up from previous efforts:

sudo rm /usr/local/bin/docker-compose
sudo pip uninstall docker-compose

Then follow this guidance re docker-compose on Rpi:

sudo apt-get -y install python-pip
sudo pip install docker-compose

For me (on 1 Nov 2017) this results in the following response to docker-compose --version:

docker-compose version 1.16.1, build 6d1ac219

JavaScript style.display="none" or jQuery .hide() is more efficient?

Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.

In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden') which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.

Angular 2: How to style host element of the component?

Try the :host > /deep/ :

Add the following to the parent.component.less file

:host {
    /deep/ app-child-component {
       //your child style
    }
}

Replace the app-child-component by your child selector

The number of method references in a .dex file cannot exceed 64k API 17

When your app references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can add the multidex support library to your project:

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

Multidex support for Android 5.0 and higher

Android 5.0 (API level 21) and higher uses a runtime called ART which natively supports loading multiple DEX files from APK files. Therefore, if your minSdkVersion is 21 or higher, you do not need the multidex support library.

Avoid the 64K limit

  • Remove unused code with ProGuard - Enable code shrinking

Configure multidex in app for

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file

android {
defaultConfig {
    ...
    minSdkVersion 21 
    targetSdkVersion 28
    multiDexEnabled true
  }
 ...
}

if your minSdkVersion is set to 20 or lower, then you must use the multidex support library

android {
defaultConfig {
    ...
    minSdkVersion 15 
    targetSdkVersion 28
    multiDexEnabled true
   }
   ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.3'
}

Override the Application class, change it to extend MultiDexApplication (if possible) as follows:

public class MyApplication extends MultiDexApplication { ... }

add to the manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="MyApplication" >
        ...
    </application>
</manifest>

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

you can use this option for call soap with wdsl :

$opts = array(
            'http' => array(
                'user_agent' => 'PHPSoapClient'
            )
        );
        $context = stream_context_create($opts);

        $soapClientOptions = array(
            'stream_context' => $context,
            'cache_wsdl' => WSDL_CACHE_NONE
        );

        $wsdlUrl = 'your wsdl url';
        $soapClient = new SoapClient($wsdlUrl, $soapClientOptions);

        $result = $soapClient->VerifyTransaction($refNum, $MerchantCode);

Getting "project" nuget configuration is invalid error

Simply restarting Visual Studio worked for me.

Hosting ASP.NET in IIS7 gives Access is denied?

I was facing this issue after pulling from remote master and adding to the appsettings on web.config. I solved it by enabling Windows Authentication:

Click on the project and press f4

Make sure Windows Auth is enabled:

enter image description here

How to create duplicate table with new name in SQL Server 2008

SELECT * 
INTO target
FROM  source
WHERE 1 = 2

How do I set a path in Visual Studio?

Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.

If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.

How to align the text middle of BUTTON

This is more predictable then "line-height"

_x000D_
_x000D_
.loginBtn {_x000D_
    background:url(images/loginBtn-center.jpg) repeat-x;_x000D_
    width:175px;_x000D_
    height:65px;_x000D_
    margin:20px auto;_x000D_
    border-radius:10px;_x000D_
    -webkit-border-radius:10px;_x000D_
    box-shadow:0 1px 2px #5e5d5b;_x000D_
}_x000D_
_x000D_
.loginBtn span {_x000D_
    display: block;_x000D_
    padding-top: 22px;_x000D_
    text-align: center;_x000D_
    line-height: 1em;_x000D_
}
_x000D_
<div id="loginBtn" class="loginBtn"><span>Log in</span></div>
_x000D_
_x000D_
_x000D_

EDIT (2018): use flexbox

.loginBtn {
    display: flex;
    align-items: center;
    justify-content: center;
}

Run a command shell in jenkins

Error shows that script does not exists

The file does not exists. check your full path

C:\Windows\TEMP\hudson6299483223982766034.sh
The system cannot find the file specified

Moreover, to launch .sh scripts into windows, you need to have CYGWIN installed and well configured into your path

Confirm that script exists.

Into jenkins script, do the following to confirm that you do have the file

cd C:\Windows\TEMP\
ls -rtl
sh -xe hudson6299483223982766034.sh

Convert UTF-8 encoded NSData to NSString

Just to summarize, here's a complete answer, that worked for me.

My problem was that when I used

[NSString stringWithUTF8String:(char *)data.bytes];

The string I got was unpredictable: Around 70% it did contain the expected value, but too often it resulted with Null or even worse: garbaged at the end of the string.

After some digging I switched to

[[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];

And got the expected result every time.

Java: using switch statement with enum under subclass

this should do:

//Main Class
public class SomeClass {

    //Sub-Class
    public static class AnotherClass {
        public enum MyEnum {
            VALUE_A, VALUE_B
        }    
        public MyEnum myEnum;
    }

    public void someMethod() { 
        AnotherClass.MyEnum enumExample = AnotherClass.MyEnum.VALUE_A; //...

        switch (enumExample) {
            case VALUE_A: { //<-- error on this line
            //..
            break;
            }
        }
    }
}

What are .tpl files? PHP, web design

That looks like Smarty to me. Smarty is a template parser written in PHP.

You can read up on how to use Smarty in the documentation.

If you can't get access to the CMS's source: To view the templates in your browser, just look at what variables Smarty is using and create a PHP file that populates the used variables with dummy data.

If I remember correctly, once Smarty is set up, you can use:

$smarty->assign('nameofvar', 'some data');

to set the variables.

How to scroll the window using JQuery $.scrollTo() function

To get around the html vs body issue, I fixed this by not animating the css directly but rather calling window.scrollTo(); on each step:

$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
  duration: 600,
  easing: 'swing',
  step: function(val) {
    window.scrollTo(0, val);
  }
});

This works nicely without any refresh gotchas as it's using cross-browser JavaScript.

Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.

Xcode : Adding a project as a build dependency

  1. Select your project in the navigator on left.
  2. Open up the drawer in the middle pane and select your target.
  3. Select Build Phases
  4. Target Dependencies is an option at that point.

How to pass data to view in Laravel?

You can also do the same thing in another way,

If you are using PHP 5.5 or latest one then you can do it as follow,

Controller:

return view(index, compact('data1','data2')); //as many as you want to pass

View:

<div>
    You can access {{$data1}}. [if it is variable]
</div>

@foreach($data1 as $d1)
    <div>
        You can access {{$d1}}. [if it is array]
    </div>
@endforeach

Same way you can access all variable that you have passed in compact function.

Hope it helps :)

SQL permissions for roles

SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.

'does it mean that they wont be able to update 4 and 5 ?'

If your users in the doctor role are only in the doctor role, then yes.

However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.

More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx

Telling gcc directly to link a library statically

You can add .a file in the linking command:

  gcc yourfiles /path/to/library/libLIBRARY.a

But this is not talking with gcc driver, but with ld linker as options like -Wl,anything are.

When you tell gcc or ld -Ldir -lLIBRARY, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose). To change order of library types checked you can use -Wl,-Bstatic and -Wl,-Bdynamic. Here is a man page of gnu LD: http://linux.die.net/man/1/ld

To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:

gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3

Assuming that default setting of ld is to use dynamic libraries (it is on Linux).

How to import component into another root component in Angular 2

Angular RC5 & RC6

If you are getting the above mentioned error in your Jasmine tests, it is most likely because you have to declare the unrenderable component in your TestBed.configureTestingModule({}).

The TestBed configures and initializes an environment for unit testing and provides methods for mocking/creating/injecting components and services in unit tests.

If you don't declare the component before your unit tests are executed, Angular will not know what <courses></courses> is in your template file.

Here is an example:

import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {AppComponent} from "../app.component";
import {CoursesComponent} from './courses.component';

describe('CoursesComponent', () => {
  let component: CoursesComponent;
  let fixture: ComponentFixture<CoursesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        CoursesComponent
      ],
      imports: [
        BrowserModule
        // If you have any other imports add them here
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CoursesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

How to determine if a string is a number with C++?

include <string>

For Validating Doubles:

bool validateDouble(const std::string & input) {
int decimals = std::count(input.begin(), input.end(), '.'); // The number of decimals in the string
int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string

if (input.size() == decimals + negativeSigns) // Consists of only decimals and negatives or is empty
    return false;
else if (1 < decimals || 1 < negativeSigns) // More than 1 decimal or negative sign
    return false;
else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
    return false;
else if (strspn(input.c_str(), "-.0123456789") != input.size()) // The string contains a character that isn't in "-.0123456789"
    return false;
return true;

}

For Validating Ints (With Negatives)

bool validateInt(const std::string & input) {
int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string

if (input.size() == negativeSigns) // Consists of only negatives or is empty
    return false;
else if (1 < negativeSigns) // More than 1 negative sign
    return false;
else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
    return false;
else if (strspn(input.c_str(), "-0123456789") != input.size()) // The string contains a character that isn't in "-0123456789"
    return false;
return true;

}

For Validating Unsigned Ints

bool validateUnsignedInt(const std::string & input) {
return (input.size() != 0 && strspn(input.c_str(), "0123456789") == input.size()); // The string is not empty and contains characters only in "0123456789"

}

How can get the text of a div tag using only javascript (no jQuery)

You'll probably want to try textContent instead of innerHTML.

Given innerHTML will return DOM content as a String and not exclusively the "text" in the div. It's fine if you know that your div contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent instead of innerHTML

For example, considering the following markup:

<div id="test">
  Some <span class="foo">sample</span> text.
</div>

You'll get the following result:

var node = document.getElementById('test'),

htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."

textContent = node.textContent;
// textContent = "Some sample text."

See MDN for more details:

How to use _CRT_SECURE_NO_WARNINGS

I was getting the same error in Visual Studio 2017 and to fix it just added #define _CRT_SECURE_NO_WARNINGS after #include "pch.h"

#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
....

Using PHP variables inside HTML tags?

HI Jasper,

you can do this:

<?
sprintf("<a href=\"http://www.whatever.com/%s\">Click Here</a>", $param);
?>

Calculate correlation with cor(), only for numerical columns

For numerical data you have the solution. But it is categorical data, you said. Then life gets a bit more complicated...

Well, first : The amount of association between two categorical variables is not measured with a Spearman rank correlation, but with a Chi-square test for example. Which is logic actually. Ranking means there is some order in your data. Now tell me which is larger, yellow or red? I know, sometimes R does perform a spearman rank correlation on categorical data. If I code yellow 1 and red 2, R would consider red larger than yellow.

So, forget about Spearman for categorical data. I'll demonstrate the chisq-test and how to choose columns using combn(). But you would benefit from a bit more time with Agresti's book : http://www.amazon.com/Categorical-Analysis-Wiley-Probability-Statistics/dp/0471360937

set.seed(1234)
X <- rep(c("A","B"),20)
Y <- sample(c("C","D"),40,replace=T)

table(X,Y)
chisq.test(table(X,Y),correct=F)
# I don't use Yates continuity correction

#Let's make a matrix with tons of columns

Data <- as.data.frame(
          matrix(
            sample(letters[1:3],2000,replace=T),
            ncol=25
          )
        )

# You want to select which columns to use
columns <- c(3,7,11,24)
vars <- names(Data)[columns]

# say you need to know which ones are associated with each other.
out <-  apply( combn(columns,2),2,function(x){
          chisq.test(table(Data[,x[1]],Data[,x[2]]),correct=F)$p.value
        })

out <- cbind(as.data.frame(t(combn(vars,2))),out)

Then you should get :

> out
   V1  V2       out
1  V3  V7 0.8116733
2  V3 V11 0.1096903
3  V3 V24 0.1653670
4  V7 V11 0.3629871
5  V7 V24 0.4947797
6 V11 V24 0.7259321

Where V1 and V2 indicate between which variables it goes, and "out" gives the p-value for association. Here all variables are independent. Which you would expect, as I created the data at random.

read input separated by whitespace(s) or newline...?

Use 'q' as the the optional argument to getline.

#include <iostream>
#include <sstream>

int main() {
    std::string numbers_str;
    getline( std::cin, numbers_str, 'q' );

    int number;
    for ( std::istringstream numbers_iss( numbers_str );
          numbers_iss >> number; ) {
        std::cout << number << ' ';
    }
}

http://ideone.com/I2vWl

canvas.toDataURL() SecurityError

Just use the crossOrigin attribute and pass 'anonymous' as the second parameter

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock


For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
    
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe
    

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock
    

Twitter Bootstrap add active class to li

You don't really need any JavaScript with Bootstrap:

 <ul class="nav">
     <li><a data-target="#" data-toggle="pill" href="#accounts">Accounts</a></li>
     <li><a data-target="#" data-toggle="pill" href="#users">Users</a></li>
 </ul>

To do more tasks after the menu item is selected you need JS as explained by other posts here.

Hope this helps.

Extract the filename from a path

$file = Get-Item -Path "c:/foo/foobar.txt"
$file.Name

Works with both relative an absolute paths

Turn off enclosing <p> tags in CKEditor 3.0

Found it!

ckeditor.js line #91 ... search for

B.config.enterMode==3?'div':'p'

change to

B.config.enterMode==3?'div':'' (NO P!)

Dump your cache and BAM!

MySQL Multiple Left Joins

You're missing a GROUP BY clause:

SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

Getting GET "?" variable in laravel

This is the best practice. This way you will get the variables from GET method as well as POST method

    public function index(Request $request) {
            $data=$request->all();
            dd($data);
    }
//OR if you want few of them then
    public function index(Request $request) {
            $data=$request->only('id','name','etc');
            dd($data);
    }
//OR if you want all except few then
    public function index(Request $request) {
            $data=$request->except('__token');
            dd($data);
    }

Why is NULL undeclared?

Are you including "stdlib.h" or "cstdlib" in this file? NULL is defined in stdlib.h/cstdlib

#include <stdlib.h>

or

#include <cstdlib>  // This is preferrable for c++

Convert a string to an enum in C#

Super simple code using TryParse:

var value = "Active";

StatusEnum status;
if (!Enum.TryParse<StatusEnum>(value, out status))
    status = StatusEnum.Unknown;

How to update MySql timestamp column to current timestamp on PHP?

Another option:

UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().

What is the reason for having '//' in Python?

// is unconditionally "flooring division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still floors -- so you always know securely what it's going to do.

Single / may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want flooring, always use //, which guarantees it. If and when you know you don't want flooring, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

How should I load files into my Java application?

public static String loadTextFile(File f) {
    try {
        BufferedReader r = new BufferedReader(new FileReader(f));
        StringWriter w = new StringWriter();

        try {
            String line = reader.readLine();
            while (null != line) {
                w.append(line).append("\n");
                line = r.readLine();
            }

            return w.toString();
        } finally {
            r.close();
            w.close();
        }
    } catch (Exception ex) {
        ex.printStackTrace();

        return "";
    }
}

MYSQL order by both Ascending and Descending sorting

You can do that in this way:

ORDER BY `products`.`product_category_id` DESC ,`naam` ASC

Have a look at ORDER BY Optimization

How to call a method function from another class?

You need a reference to the class that contains the method you want to call. Let's say we have two classes, A and B. B has a method you want to call from A. Class A would look like this:

public class A
{
    B b; // A reference to B

    b = new B(); // Creating object of class B

    b.doSomething();  // Calling a method contained in class B from class A
}

B, which contains the doSomething() method would look like this:

public class B
{
    public void doSomething()
    {
        System.out.println("Look, I'm doing something in class B!");
    }
}

How to delete zero components in a vector in Matlab?

You could use sparse(a), which would return

(1,2) 1

(1,4) 3

This allows you to keep the information about where your non-zero entries used to be.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

DATETIME supports 1753/1/1 to "eternity" (9999/12/31), while DATETIME2 support 0001/1/1 through eternity.

Msdn

Answer: I suppose you try to save DateTime with '0001/1/1' value. Just set breakpoint and debug it, if so then replace DateTime with null or set normal date.

jQuery - passing value from one input to another

It's simpler if you modify your HTML a little bit:

<label for="first_name">First Name</label>
<input type="text" id="name" name="name" />

<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" />

<label for="firstname">Firstname</label>
<input type="text" id="firstname" name="firstname" disabled="disabled" />

then it's relatively simple

$(document).ready(function() { 
    $('#name').change(function() {
      $('#firstname').val($('#name').val());
    });
});

How do you find out which version of GTK+ is installed on Ubuntu?

You can also just open synaptic and search for libgtk, it will show you exactly which lib is installed.

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

How to set underline text on textview?

Need not to use HTML properties, let's focus on java xD I had the same problem, i found the way to do it in java:

String text="Hide post";
TextView tvHide=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(text);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
tvHide.setText(spanString );

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

MySQL SELECT query string matching

Just turn the LIKE around

SELECT * FROM customers
WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%')

JSON Naming Convention (snake_case, camelCase or PascalCase)

In this document Google JSON Style Guide (recommendations for building JSON APIs at Google),

It recommends that:

  1. Property names must be camelCased, ASCII strings.

  2. The first character must be a letter, an underscore (_) or a dollar sign ($).

Example:

{
  "thisPropertyIsAnIdentifier": "identifier value"
}

My team follows this convention.

How to make my layout able to scroll down?

Just wrap all that inside a ScrollView

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ruatech.sanikamal.justjava.MainActivity">
<!-- Here you put the rest of your current view-->
</ScrollView>

error C2220: warning treated as error - no 'object' file generated

The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.

In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.

How do I wait for an asynchronously dispatched block to finish?

Trying to use a dispatch_semaphore. It should look something like this:

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

[object runSomeLongOperationAndDo:^{
    STAssert…

    dispatch_semaphore_signal(sema);
}];

if (![NSThread isMainThread]) {
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
} else {
    while (dispatch_semaphore_wait(sema, DISPATCH_TIME_NOW)) { 
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]]; 
    }
}

This should behave correctly even if runSomeLongOperationAndDo: decides that the operation isn't actually long enough to merit threading and runs synchronously instead.

Convert PDF to image with high resolution

I have found it both faster and more stable when batch-processing large PDFs into PNGs and JPGs to use the underlying gs (aka Ghostscript) command that convert uses.

You can see the command in the output of convert -verbose and there are a few more tweaks possible there (YMMV) that are difficult / impossible to access directly via convert.

However, it would be harder to do your trimming and sharpening using gs, so, as I said, YMMV!

c# datagridview doubleclick on row with FullRowSelect

In CellContentDoubleClick event fires only when double clicking on cell's content. I used this and works:

    private void dgvUserList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show(e.RowIndex.ToString());
    }

Char to int conversion in C

Since the ASCII codes for '0','1','2'.... are placed from 48 to 57 they are essentially continuous. Now the arithmetic operations require conversion of char datatype to int datatype.Hence what you are basically doing is: 53-48 and hence it stores the value 5 with which you can do any integer operations.Note that while converting back from int to char the compiler gives no error but just performs a modulo 256 operation to put the value in its acceptable range

What is the difference between CSS and SCSS?

Sass is a language that provides features to make it easier to deal with complex styling compared to editing raw .css. An example of such a feature is allowing definition of variables that can be re-used in different styles.

The language has two alternative syntaxes:

  • A JSON like syntax that is kept in files ending with .scss
  • A YAML like syntax that is kept in files ending with .sass

Either of these must be compiled to .css files which are recognized by browsers.

See https://sass-lang.com/ for further information.

How can I tell jaxb / Maven to generate multiple schema packages?

This can also be achieved by specifying stale file name for schemas and not clearing output directory. The default out put directory is automatically included in classpath which is little convenient. If we specify different output directory one has to take care of classpath to use this code in IDE. For example -

<plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxb2-maven-plugin</artifactId>
            <version>1.3.1</version>
            <configuration>
                <quiet>true</quiet>
                <verbose>false</verbose>
                <clearOutputDir>false</clearOutputDir>
                <readOnly>true</readOnly>
                <arguments>-mark-generated</arguments>
            </configuration>
            <executions>
                <execution>
                    <id>reportingSchema</id>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                    <configuration>
                        <schemaDirectory>src/main/resources/schema/r17/schemaReporting</schemaDirectory>
                        <schemaIncludes>
                            <include>OCISchemaReporting.xsd</include>
                        </schemaIncludes>
                        <packageName>com.broadsoft.oci.r17.reporting</packageName>
                        <staleFile>${build.directory}/generated-sources/.jaxb-staleFlag-reporting</staleFile>
                    </configuration>
                </execution>
                <execution>
                    <id>schemaAS</id>
                    <goals>
                        <goal>xjc</goal>
                    </goals>
                    <configuration>
                        <schemaDirectory>src/main/resources/schema/r17/schemaAS</schemaDirectory>
                        <schemaIncludes>
                            <include>OCISchemaAS.xsd</include>
                        </schemaIncludes>
                        <packageName>com.broadsoft.oci.r17.as</packageName>
                        <staleFile>${build.directory}/generated-sources/.jaxb-staleFlag-as</staleFile>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</plugins>

Source:Generating Code with JAXB Plugin

Pretty-print an entire Pandas Series / DataFrame

Using pd.options.display

This answer is a variation of the prior answer by lucidyan. It makes the code more readable by avoiding the use of set_option.

After importing pandas, as an alternative to using the context manager, set such options for displaying large dataframes:

def set_pandas_display_options() -> None:
    """Set pandas display options."""
    # Ref: https://stackoverflow.com/a/52432757/
    display = pd.options.display

    display.max_columns = 1000
    display.max_rows = 1000
    display.max_colwidth = 199
    display.width = None
    # display.precision = 2  # set as needed

set_pandas_display_options()

After this, you can use either display(df) or just df if using a notebook, otherwise print(df).

Using to_string

Pandas 0.25.3 does have DataFrame.to_string and Series.to_string methods which accept formatting options.

Using to_markdown

If what you need is markdown output, Pandas 1.0.0 has DataFrame.to_markdown and Series.to_markdown methods.

Using to_html

If what you need is HTML output, Pandas 0.25.3 does have a DataFrame.to_html method but not a Series.to_html. Note that a Series can be converted to a DataFrame.

Populate data table from data reader

If you're trying to load a DataTable, then leverage the SqlDataAdapter instead:

DataTable dt = new DataTable();

using (SqlConnection c = new SqlConnection(cString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, c))
{
    sda.SelectCommand.CommandType = CommandType.StoredProcedure;
    sda.SelectCommand.Parameters.AddWithValue("@parm1", val1);
    ...

    sda.Fill(dt);
}

You don't even need to define the columns. Just create the DataTable and Fill it.

Here, cString is your connection string and sql is the stored procedure command.

How to align an indented line in a span that wraps into multiple lines?

You want multiple lines of text indented on the left. Try the following:

CSS:

div.info {
    margin-left: 10px;
}

span.info {
    color: #b1b1b1;
    font-size: 11px;
    font-style: italic;
    font-weight:bold;
}

HTML:

<div class="info"><span class="info">blah blah <br/> blah blah</span></div>

SQL Query to find the last day of the month

Just a different version of adding a month and subtracting a day for creating reports:

ex: StartofMonth is '2019-10-01'

dateadd(day,-1,dateadd(month,1,StartofMonth))

EndOfMonth will become '2019-10-31'

Why shouldn't `&apos;` be used to escape single quotes?

&quot; is on the official list of valid HTML 4 entities, but &apos; is not.

From C.16. The Named Character Reference ':

The named character reference &apos; (the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use &#39; instead of &apos; to work as expected in HTML 4 user agents.

Catch Ctrl-C in C

Or you can put the terminal in raw mode, like this:

struct termios term;

term.c_iflag |= IGNBRK;
term.c_iflag &= ~(INLCR | ICRNL | IXON | IXOFF);
term.c_lflag &= ~(ICANON | ECHO | ECHOK | ECHOE | ECHONL | ISIG | IEXTEN);
term.c_cc[VMIN] = 1;
term.c_cc[VTIME] = 0;
tcsetattr(fileno(stdin), TCSANOW, &term);

Now it should be possible to read Ctrl+C keystrokes using fgetc(stdin). Beware using this though because you can't Ctrl+Z, Ctrl+Q, Ctrl+S, etc. like normally any more either.

I need to round a float to two decimal places in Java

If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat class. It's very simple:

double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);

Which will output (depending on locale):

$2.30

Also, if currency isn't required (just the exact two decimal places) you can use this instead:

NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);

Which will output 2.30

Is Java RegEx case-insensitive?

You can also match case insensitive regexs and make it more readable by using the Pattern.CASE_INSENSITIVE constant like:

Pattern mypattern = Pattern.compile(MYREGEX, Pattern.CASE_INSENSITIVE);
Matcher mymatcher= mypattern.matcher(mystring);

Configuring IntelliJ IDEA for unit testing with JUnit

One way of doing this is to do add junit.jar to your $CLASSPATH as an external dependency.

adding junit intellij

So to do that, go to project structure, and then add JUnit as one of the libraries as shown in the gif.

In the 'Choose Modules' prompt choose only the modules that you'd need JUnit for.

How to use Typescript with native ES6 Promises

Using native ES6 Promises with Typescript in Visual Studio 2015 + Node.js tools 1.2

No npm install required as ES6 Promises is native.

Node.js project -> Properties -> Typescript Build tab ECMAScript version = ECMAScript6

import http = require('http');
import fs = require('fs');

function findFolderAsync(directory : string): Promise<string> {

    let p = new Promise<string>(function (resolve, reject) {

        fs.stat(directory, function (err, stats) {

            //Check if error defined and the error code is "not exists"
            if (err && err.code === "ENOENT") {
                reject("Directory does not exist");
            }
            else {
                resolve("Directory exists");
            }
        });

    });
    return p;
}

findFolderAsync("myFolder").then(

    function (msg : string) {
        console.log("Promise resolved as " + msg); 
    },
    function (msg : string) {
        console.log("Promise rejected as " + msg); 
    }
);

Find if a textbox is disabled or not using jquery

You can find if the textbox is disabled using is method by passing :disabled selector to it. Try this.

if($('textbox').is(':disabled')){
     //textbox is disabled
}

Warning as error - How to get rid of these

VS 2019

Just for people using VS2019, I think other answers are also pointing out same location.

How do I revert an SVN commit?

First, revert the working copy to 1943.

> svn merge -c -1943 .

Second, check what is about to be commited.

> svn status

Third, commit version 1945.

> svn commit -m "Fix bad commit."

Fourth, look at the new log.

> svn log -l 4

------------------------------------------------------------------------
1945 | myname | 2015-04-20 19:20:51 -0700 (Mon, 20 Apr 2015) | 1 line

Fix bad commit.
------------------------------------------------------------------------
1944 | myname | 2015-04-20 19:09:58 -0700 (Mon, 20 Apr 2015) | 1 line

This is the bad commit that I made.
------------------------------------------------------------------------
1943 | myname | 2015-04-20 18:36:45 -0700 (Mon, 20 Apr 2015) | 1 line

This was a good commit.
------------------------------------------------------------------------

Detect when browser receives file download

Create an iframe when button/link is clicked and append this to body.

                  $('<iframe />')
                 .attr('src', url)
                 .attr('id','iframe_download_report')
                 .hide()
                 .appendTo('body'); 

Create an iframe with delay and delete it after download.

                            var triggerDelay =   100;
                            var cleaningDelay =  20000;
                            var that = this;
                            setTimeout(function() {
                                var frame = $('<iframe style="width:1px; height:1px;" class="multi-download-frame"></iframe>');
                                frame.attr('src', url+"?"+ "Content-Disposition: attachment ; filename="+that.model.get('fileName'));
                                $(ev.target).after(frame);
                                setTimeout(function() {
                                    frame.remove();
                                }, cleaningDelay);
                            }, triggerDelay);

Add swipe to delete UITableViewCell

Add these two functions:

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {
        // handle delete (by removing the data from your array and updating the tableview)
    }
}

Swift 3.0:

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)
    }
}

Swift 4.2

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {
        // handle delete (by removing the data from your array and updating the tableview)
    }
}

How to get the home directory in Python?

I found that pathlib module also supports this.

from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')

Java FileReader encoding issue

Since Java 11 you may use that:

public FileReader(String fileName, Charset charset) throws IOException;

Bootstrap fullscreen layout with 100% height

_x000D_
_x000D_
<section class="min-vh-100 d-flex align-items-center justify-content-center py-3">
  <div class="container">
    <div class="row justify-content-between align-items-center">
    x
    x
    x
    </div>
  </div>
</section>
_x000D_
_x000D_
_x000D_

What is the largest TCP/IP network port number allowable for IPv4?

Just a followup to smashery's answer. The ephemeral port range (on Linux at least, and I suspect other Unices as well) is not a fixed. This can be controlled by writing to /proc/sys/net/ipv4/ip_local_port_range

The only restriction (as far as IANA is concerned) is that ports below 1024 are designated to be well-known ports. Ports above that are free for use. Often you'll find that ports below 1024 are restricted to superuser access, I believe for this very reason.

Extract digits from string - StringUtils Java

You can split the string and compare with each character

public static String extractNumberFromString(String source) {
    StringBuilder result = new StringBuilder(100);
    for (char ch : source.toCharArray()) {
        if (ch >= '0' && ch <= '9') {
            result.append(ch);
        }
    }

    return result.toString();
}

Testing Code

    @Test
    public void test_extractNumberFromString() {
    String numberString = NumberUtil.extractNumberFromString("+61 415 987 636");
    assertThat(numberString, equalTo("61415987636"));

    numberString = NumberUtil.extractNumberFromString("(02)9295-987-636");
    assertThat(numberString, equalTo("029295987636"));

    numberString = NumberUtil.extractNumberFromString("(02)~!@#$%^&*()+_<>?,.:';9295-{}[=]987-636");
    assertThat(numberString, equalTo("029295987636"));
}

Is Laravel really this slow?

From my Hello World contest, Which one is Laravel? I think you can guess. I used docker container for the test and here is the results

To make http-response "Hello World":

  • Golang with log handler stdout : 6000 rps
  • SpringBoot with Log Handler stdout: 3600 rps
  • Laravel 5 with off log :230 rps

APK signing error : Failed to read key from keystore

Most likely that your key alias does not exist for your keystore file.

This answer should fix your signing issue ;)

How to convert any date format to yyyy-MM-dd

You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:

string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

Here, SourceDate is variable in which you will get selected date.

Oracle SQL Developer: Unable to find a JVM

I just installed SQL Developer 4.0.0.13 and the SetJavaHome can now be overridden by a user-specific configuration file (not sure if this is new to 4.0.0.13 or not).

The location of this user-specific configuration file can be seen in the user.conf property under 'Help -> About' on the 'Properties' tab. For example, mine was set to:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0\product.conf

On Windows 7.

The first section of this file is used to set the JDK that SQLDeveloper should use:

#
# By default, the product launcher will search for a JDK to use, and if none
# can be found, it will ask for the location of a JDK and store its location
# in this file. If a particular JDK should be used instead, uncomment the
# line below and set the path to your preferred JDK.
#
SetJavaHome C:\Program Files (x86)\Java\jdk1.7.0_03

This setting overrides the setting in sqldeveloper.conf

How is returning the output of a function different from printing it?

def add(x, y):
    return x+y

That way it can then become a variable.

sum = add(3, 5)

print(sum)

But if the 'add' function print the output 'sum' would then be None as action would have already taken place after it being assigned.

How can I remove a commit on GitHub?

To delete the commit from the remote repository:

 git push -f origin last_known_good_commit:branch_name

In order delete the commit from your local repository:

git reset --hard HEAD~1

link

How to convert string representation of list to a list?

There is a quick solution:

x = eval('[ "A","B","C" , " D"]')

Unwanted whitespaces in the list elements may be removed in this way:

x = [x.strip() for x in eval('[ "A","B","C" , " D"]')]

Remove the first character of a string

Just do this:

r = "hello"
r = r[1:]
print(r) # ello

Vertically align an image inside a div with responsive height

Here is a technique to align inline elements inside a parent, horizontally and vertically at the same time:

Vertical Alignment

1) In this approach, we create an inline-block (pseudo-)element as the first (or last) child of the parent, and set its height property to 100% to take all the height of its parent.

2) Also, adding vertical-align: middle keeps the inline(-block) elements at the middle of the line space. So, we add that CSS declaration to the first-child and our element (the image) both.

3) Finally, in order to remove the white space character between inline(-block) elements, we could set the font size of the parent to zero by font-size: 0;.

Note: I used Nicolas Gallagher's image replacement technique in the following.

What are the benefits?

  • The container (parent) can have dynamic dimensions.
  • There's no need to specify the dimensions of the image element explicitly.

  • We can easily use this approach to align a <div> element vertically as well; which may have a dynamic content (height and/or width). But note that you have to re-set the font-size property of the div to display the inside text. Online Demo.

<div class="container">
    <div id="element"> ... </div>
</div>
.container {
    height: 300px;
    text-align: center;  /* align the inline(-block) elements horizontally */
    font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.container:before {    /* create a full-height inline block pseudo=element */
    content: ' ';
    display: inline-block;
    vertical-align: middle;  /* vertical alignment of the inline element */
    height: 100%;
}

#element {
    display: inline-block;
    vertical-align: middle;  /* vertical alignment of the inline element */
    font: 16px/1 Arial sans-serif;        /* <-- reset the font property */
}

The output

Vertically align an element in its container

Responsive Container

This section is not going to answer the question as the OP already knows how to create a responsive container. However, I'll explain how it works.

In order to make the height of a container element changes with its width (respecting the aspect ratio), we could use a percentage value for top/bottom padding property.

A percentage value on top/bottom padding or margins is relative to the width of the containing block.

For instance:

.responsive-container {
  width: 60%;

  padding-top: 60%;    /* 1:1 Height is the same as the width */
  padding-top: 100%;   /* width:height = 60:100 or 3:5        */
  padding-top: 45%;    /* = 60% * 3/4 , width:height =  4:3   */
  padding-top: 33.75%; /* = 60% * 9/16, width:height = 16:9   */
}

Here is the Online Demo. Comment out the lines from the bottom and resize the panel to see the effect.

Also, we could apply the padding property to a dummy child or :before/:after pseudo-element to achieve the same result. But note that in this case, the percentage value on padding is relative to the width of the .responsive-container itself.

<div class="responsive-container">
  <div class="dummy"></div>
</div>
.responsive-container { width: 60%; }

.responsive-container .dummy {
  padding-top: 100%;    /*  1:1 square */
  padding-top: 75%;     /*  w:h =  4:3 */
  padding-top: 56.25%;  /*  w:h = 16:9 */
}

Demo #1.
Demo #2 (Using :after pseudo-element)

Adding the content

Using padding-top property causes a huge space at the top or bottom of the content, inside the container.

In order to fix that, we have wrap the content by a wrapper element, remove that element from document normal flow by using absolute positioning, and finally expand the wrapper (bu using top, right, bottom and left properties) to fill the entire space of its parent, the container.

Here we go:

.responsive-container {
  width: 60%;
  position: relative;
}

.responsive-container .wrapper {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}

Here is the Online Demo.


Getting all together

<div class="responsive-container">
  <div class="dummy"></div>

  <div class="img-container">
    <img src="http://placehold.it/150x150" alt="">
  </div>
</div>
.img-container {
  text-align:center; /* Align center inline elements */
  font: 0/0 a;       /* Hide the characters like spaces */
}

.img-container:before {
  content: ' ';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

.img-container img {
  vertical-align: middle;
  display: inline-block;
}

Here is the WORKING DEMO.

Obviously, you could avoid using ::before pseudo-element for browser compatibility, and create an element as the first child of the .img-container:

<div class="img-container">
    <div class="centerer"></div>
    <img src="http://placehold.it/150x150" alt="">
</div>
.img-container .centerer {
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

UPDATED DEMO.

Using max-* properties

In order to keep the image inside of the box in lower width, you could set max-height and max-width property on the image:

.img-container img {
    vertical-align: middle;
    display: inline-block;
    max-height: 100%;  /* <-- Set maximum height to 100% of its parent */
    max-width: 100%;   /* <-- Set maximum width to 100% of its parent */
}

Here is the UPDATED DEMO.

Accidentally committed .idea directory files into git

You should add a .gitignore file to your project and add /.idea to it. You should add each directory / file in one line.

If you have an existing .gitignore file then you should simply add a new line to the file and put /.idea to the new line.

After that run git rm -r --cached .idea command.

If you faced an error you can run git rm -r -f --cached .idea command. After all run git add . and then git commit -m "Removed .idea directory and added a .gitignore file" and finally push the changes by running git push command.

Hadoop "Unable to load native-hadoop library for your platform" warning

This also would work:

export LD_LIBRARY_PATH=/usr/lib/hadoop/lib/native

Hibernate error: ids for this class must be manually assigned before calling save():

For hibernate it is important to know that your object WILL have an id, when you want to persist/save it. Thus, make sure that

    private String U_id;

will have a value, by the time you are going to persist your object. You can do that with the @GeneratedValue annotation or by assigning a value manually.

In the case you need or want to assign your id's manually (and that's what the above error is actually about), I would prefer passing the values for the fields to your constructor, at least for U_id, e.g.

  public Role (String U_id) { ... }

This ensures that your object has an id, by the time you have instantiated it. I don't know what your use case is and how your application behaves in concurrency, however, in some cases this is not recommended. You need to ensure that your id is unique.

Further note: Hibernate will still require a default constructor, as stated in the hibernate documentation. In order to prevent you (and maybe other programmers if you're designing an api) of instantiations of Role using the default constructor, just declare it as private.

Is there a way to avoid null check before the for-each loop iteration starts?

It's already 2017, and you can now use Apache Commons Collections4

The usage:

for(Object obj : CollectionUtils.emptyIfNull(list1)){
    // Do your stuff
}

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

Use this regular expression if you don't want to start with zero:

^[1-9]([0-9]{1,45}$)

If you don't mind starting with zero, use:

^[0-9]{1,45}$

Return value from exec(@sql)

On the one hand you could use sp_executesql:

exec sp_executesql N'select @rowcount=count(*) from anytable', 
                    N'@rowcount int output', @rowcount output;

On the other hand you could use a temporary table:

declare @result table ([rowcount] int);
insert into @result ([rowcount])
exec (N'select count(*) from anytable');
declare @rowcount int = (select top (1) [rowcount] from @result);

How does tuple comparison work in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.

See Common Sequence Operations:

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Also Value Comparisons for further details:

Lexicographical comparison between built-in collections works as follows:

  • For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).
  • Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).

Note 1: < and > do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).

Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.

Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This configuration to your nginx.conf should help you.

https://gist.github.com/baskaran-md/e46cc25ccfac83f153bb

server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    error_page  404     /404.html;
    error_page  403     /403.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    # ...
}

Android: disabling highlight on listView click

From ListView: Disable Focus Highlight,

when you set your ListAdapter use the following code

ListAdapter adapter = new SimpleCursorAdapter(MyList, Layout, c, 
                new String[] { "Name", "Score" }, to) 
{ 
    public boolean areAllItemsEnabled() 
    { 
        return false; 
    } 
    public boolean isEnabled(int position) 
    { 
        return false; 
    } 
}; 

This will override the BaseAdapter class. It also cancels the white border between cells.

How does autowiring work in Spring?

There are 3 ways you can create an instance using @Autowired.

1. @Autowired on Properties

The annotation can be used directly on properties, therefore eliminating the need for getters and setters:

    @Component("userService")
    public class UserService {

        public String getName() {
            return "service name";
        }
    }

    @Component
    public class UserController {

        @Autowired
        UserService userService

    }

In the above example, Spring looks for and injects userService when UserController is created.

2. @Autowired on Setters

The @Autowired annotation can be used on setter methods. In the below example, when the annotation is used on the setter method, the setter method is called with the instance of userService when UserController is created:

public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
            this.userService = userService;
    }
}

3. @Autowired on Constructors

The @Autowired annotation can also be used on constructors. In the below example, when the annotation is used on a constructor, an instance of userService is injected as an argument to the constructor when UserController is created:

public class UserController {

    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService= userService;
    }
}

How to pass credentials to the Send-MailMessage command for sending emails

in addition to UseSsl, you have to include smtp port 587 to make it work.

Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

Why is "except: pass" a bad programming practice?

In my opinion errors have a reason to appear, that my sound stupid, but thats the way it is. Good programming only raises errors when you have to handle them. Also, as i read some time ago, "the pass-Statement is a Statement that Shows code will be inserted later", so if you want to have an empty except-statement feel free to do so, but for a good program there will be a part missing. because you dont handle the things you should have. Appearing exceptions give you the chance to correct input data or to change your data structure so these exceptions dont occur again (but in most cases (Network-exceptions, General input-exceptions) exceptions indicate that the next parts of the program wont execute well. For example a NetworkException can indicate a broken network-connection and the program cant send/recieve data in the next program steps.

But using a pass block for only one execption-block is valid, because you still differenciate beetween the types of exceptions, so if you put all exception-blocks in one, it is not empty:

try:
    #code here
except Error1:
    #exception handle1

except Error2:
    #exception handle2
#and so on

can be rewritten that way:

try:
    #code here
except BaseException as e:
    if isinstance(e, Error1):
        #exception handle1

    elif isinstance(e, Error2):
        #exception handle2

    ...

    else:
        raise

So even multiple except-blocks with pass-statements can result in code, whose structure handles special types of exceptions.

Chart creating dynamically. in .net, c#

Yep.

// FakeChart.cs
// ------------------------------------------------------------------
//
// A Winforms app that produces a contrived chart using
// DataVisualization (MSChart).  Requires .net 4.0.
//
// Author: Dino
//
// ------------------------------------------------------------------
//
// compile: \net4.0\csc.exe /t:winexe /debug+ /R:\net4.0\System.Windows.Forms.DataVisualization.dll FakeChart.cs
//

using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;


namespace Dino.Tools.WebMonitor
{
    public class FakeChartForm1 : Form
    {
        private System.ComponentModel.IContainer components = null;
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;

        public FakeChartForm1 ()
        {
            InitializeComponent();
        }

        private double f(int i)
        {
            var f1 = 59894 - (8128 * i) + (262 * i * i) - (1.6 * i * i * i);
            return f1;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            chart1.Series.Clear();
            var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
            {
                Name = "Series1",
                Color = System.Drawing.Color.Green,
                IsVisibleInLegend = false,
                IsXValueIndexed = true,
                ChartType = SeriesChartType.Line
            };

            this.chart1.Series.Add(series1);

            for (int i=0; i < 100; i++)
            {
                series1.Points.AddXY(i, f(i));
            }
            chart1.Invalidate();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
            this.SuspendLayout();
            //
            // chart1
            //
            chartArea1.Name = "ChartArea1";
            this.chart1.ChartAreas.Add(chartArea1);
            this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
            legend1.Name = "Legend1";
            this.chart1.Legends.Add(legend1);
            this.chart1.Location = new System.Drawing.Point(0, 50);
            this.chart1.Name = "chart1";
            // this.chart1.Size = new System.Drawing.Size(284, 212);
            this.chart1.TabIndex = 0;
            this.chart1.Text = "chart1";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.chart1);
            this.Name = "Form1";
            this.Text = "FakeChart";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
            this.ResumeLayout(false);
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FakeChartForm1());
        }
    }
}

UI:

enter image description here

Convert a string to int using sql query

You could use CAST or CONVERT:

SELECT CAST(MyVarcharCol AS INT) FROM Table

SELECT CONVERT(INT, MyVarcharCol) FROM Table

Global Angular CLI version greater than local version

if you upgraded your Angular Version, you need to change the version of

@angular-devkit/build-angular

inside your

package.json

from your old version to the new angular build version upgraded.

I had upgraded to Angular 10, so i needed to go to https://www.npmjs.com/package/@angular-devkit/build-angular and check which is my version according to Angular 10.

In my case, i founded that the version needs to be 0.1001.7, so i changed my old version to this version in my package.json and run

npm --save install

That was enough.

Setting and getting localStorage with jQuery

Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.

Sample using .text()

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// alert the value to check if we got it
alert(localStorage.getItem('test'));

JSFiddle: https://jsfiddle.net/f3zLa3zc/


Storing the HTML itself

// get html
var html = $('#test')[0].outerHTML;

// set localstorage
localStorage.setItem('htmltest', html);

// test if it works
alert(localStorage.getItem('htmltest'));

JSFiddle:
https://jsfiddle.net/psfL82q3/1/


Update on user comment

A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// bind text to 'blur' event for div
$('#test').on('blur', function() {

    // check the new text
    var newText = $(this).text();

    // overwrite the old text
    localStorage.setItem('test', newText);

    // test if it works
    alert(localStorage.getItem('test'));

});

If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.

JSFiddle:
https://jsfiddle.net/g1b8m1fc/

getting the X/Y coordinates of a mouse click on an image with jQuery

The below code works always even if any image makes the window scroll.

$(function() {
    $("#demo-box").click(function(e) {

      var offset = $(this).offset();
      var relativeX = (e.pageX - offset.left);
      var relativeY = (e.pageY - offset.top);

      alert("X: " + relativeX + "  Y: " + relativeY);

    });
});

Ref: http://css-tricks.com/snippets/jquery/get-x-y-mouse-coordinates/

Plotting with C#

See Samples Environment for Microsoft Chart Controls:

The samples environment for Microsoft Chart Controls for .NET Framework contains over 200 samples for both ASP.NET and Windows Forms. The samples cover every major feature in Chart Controls for .NET Framework. They enable you to see the Chart controls in action as well as use the code as templates for your own web and windows applications.

Seems to be more business oriented, but may be of some value to science students and scientists.

Why is "using namespace std;" considered bad practice?

Do not use it globally

It is considered "bad" only when used globally. Because:

  • You clutter the namespace you are programming in.
  • Readers will have difficulty seeing where a particular identifier comes from, when you use many using namespace xyz.
  • Whatever is true for other readers of your source code is even more true for the most frequent reader of it: yourself. Come back in a year or two and take a look...
  • If you only talk about using namespace std you might not be aware of all the stuff you grab -- and when you add another #include or move to a new C++ revision you might get name conflicts you were not aware of.

You may use it locally

Go ahead and use it locally (almost) freely. This, of course, prevents you from repetition of std:: -- and repetition is also bad.

An idiom for using it locally

In C++03 there was an idiom -- boilerplate code -- for implementing a swap function for your classes. It was suggested that you actually use a local using namespace std -- or at least using std::swap:

class Thing {
    int    value_;
    Child  child_;
public:
    // ...
    friend void swap(Thing &a, Thing &b);
};
void swap(Thing &a, Thing &b) {
    using namespace std;      // make `std::swap` available
    // swap all members
    swap(a.value_, b.value_); // `std::stwap(int, int)`
    swap(a.child_, b.child_); // `swap(Child&,Child&)` or `std::swap(...)`
}

This does the following magic:

  • The compiler will choose the std::swap for value_, i.e. void std::swap(int, int).
  • If you have an overload void swap(Child&, Child&) implemented the compiler will choose it.
  • If you do not have that overload the compiler will use void std::swap(Child&,Child&) and try its best swapping these.

With C++11 there is no reason to use this pattern any more. The implementation of std::swap was changed to find a potential overload and choose it.

WhatsApp API (java/python)

Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.

I want to align the text in a <td> to the top

I was facing such a problem, look at the picture below

enter image description here

and here is its HTML

<tr class="li1">
    <td valign="top">1.</td>
    <td colspan="5" valign="top">
        <p>How to build e-book learning environment</p>
    </td>
</tr>

so I fix it by changing valign Attribute in both td tags to baseline

and it worked

here is the result enter image description here

hope this help you

Programmatically switching between tabs within Swift

If you want to do this from code that you are writing as part of a particular view controller, like in response to a button press or something, you can do this:

@IBAction func pushSearchButton(_ sender: UIButton?) {
    if let tabBarController = self.navigationController?.tabBarController  {
        tabBarController.selectedIndex = 1
    }
}

And you can also add code to handle tab switching using the UITabBarControllerDelegate methods. Using tags on the base view controllers of each tab, you can see where you are and act accordingly: For example

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    
    // if we didn't change tabs, don't do anything
    if tabBarController.selectedViewController?.tabBarItem.tag ==  viewController.tabBarItem.tag {
        return false
    }
    
    if viewController.tabBarItem.tag == 4096 { // some particular tab
        // do stuff appropriate for a transition to this particular tab
    }
    else if viewController.tabBarItem.tag == 2048 { // some other tab
        // do stuff appropriate for a transition to this other tab
    }
}

How can I scroll to a specific location on the page using jquery?

<div id="idVal">
    <!--div content goes here-->
</div>
...
<script type="text/javascript">
     $(document).ready(function(){
         var divLoc = $('#idVal').offset();
         $('html, body').animate({scrollTop: divLoc.top}, "slow");
     });
</script>

This example shows to locate to a particular div id i.e, 'idVal' in this case. If you have subsequent divs/tables that will open up in this page via ajax, then you can assign unique divs and call the script to scroll to the particular location for each contents of divs.

Hope this will be useful.

How can I close a window with Javascript on Mozilla Firefox 3?

function closeWindow() {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
    alert("This will close the window");
    window.open('','_self');
    window.close();
}

closeWindow();

Get top n records for each group of grouped results

I wanted to share this because I spent a long time searching for an easy way to implement this in a java program I'm working on. This doesn't quite give the output you're looking for but its close. The function in mysql called GROUP_CONCAT() worked really well for specifying how many results to return in each group. Using LIMIT or any of the other fancy ways of trying to do this with COUNT didn't work for me. So if you're willing to accept a modified output, its a great solution. Lets say I have a table called 'student' with student ids, their gender, and gpa. Lets say I want to top 5 gpas for each gender. Then I can write the query like this

SELECT sex, SUBSTRING_INDEX(GROUP_CONCAT(cast(gpa AS char ) ORDER BY gpa desc), ',',5) 
AS subcategories FROM student GROUP BY sex;

Note that the parameter '5' tells it how many entries to concatenate into each row

And the output would look something like

+--------+----------------+
| Male   | 4,4,4,4,3.9    |
| Female | 4,4,3.9,3.9,3.8|
+--------+----------------+

You can also change the ORDER BY variable and order them a different way. So if I had the student's age I could replace the 'gpa desc' with 'age desc' and it will work! You can also add variables to the group by statement to get more columns in the output. So this is just a way I found that is pretty flexible and works good if you are ok with just listing results.

How do I add an existing directory tree to a project in Visual Studio?

In Visual Studio 2015, this is how you do it.

If you want to automatically include all descendant files below a specific folder:

<Content Include="Path\To\Folder\**" />

This can be restricted to include only files within the path specified:

<Content Include="Path\To\Folder\*.*" />

Or even only files with a specified extension:

<Content Include="Path\To\Folder\*.jpg" >

How to add two edit text fields in an alert dialog

I found another set of examples for customizing an AlertDialog from a guy named Mossila. I think they're better than Google's examples. To quickly see Google's API demos, you must import their demo jar(s) into your project, which you probably don't want.

But Mossila's example code is fully self-contained. It can be directly cut-and-pasted into your project. It just works! Then you only need to tweak it to your needs. See here

How to replace an entire line in a text file by line number

# Replace the line of the given line number with the given replacement in the given file.
function replace-line-in-file() {
    local file="$1"
    local line_num="$2"
    local replacement="$3"

    # Escape backslash, forward slash and ampersand for use as a sed replacement.
    replacement_escaped=$( echo "$replacement" | sed -e 's/[\/&]/\\&/g' )

    sed -i "${line_num}s/.*/$replacement_escaped/" "$file"
}

What integer hash function are good that accepts an integer hash key?

Depends on how your data is distributed. For a simple counter, the simplest function

f(i) = i

will be good (I suspect optimal, but I can't prove it).

Programmatically change UITextField Keyboard type

It's worth noting that if you want a currently-focused field to update the keyboard type immediately, there's one extra step:

// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress

[textField setKeyboardType:UIKeyboardTypeEmailAddress];
[textField reloadInputViews];

Without the call to reloadInputViews, the keyboard will not change until the selected field (the first responder) loses and regains focus.

A full list of the UIKeyboardType values can be found here, or:

typedef enum : NSInteger {
    UIKeyboardTypeDefault,
    UIKeyboardTypeASCIICapable,
    UIKeyboardTypeNumbersAndPunctuation,
    UIKeyboardTypeURL,
    UIKeyboardTypeNumberPad,
    UIKeyboardTypePhonePad,
    UIKeyboardTypeNamePhonePad,
    UIKeyboardTypeEmailAddress,
    UIKeyboardTypeDecimalPad,
    UIKeyboardTypeTwitter,
    UIKeyboardTypeWebSearch,
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;

VBA Count cells in column containing specified value

This isn't exactly what you are looking for but here is how I've approached this problem in the past;

You can enter a formula like;

=COUNTIF(A1:A10,"Green")

...into a cell. This will count the Number of cells between A1 and A10 that contain the text "Green". You can then select this cell value in a VBA Macro and assign it to a variable as normal.

List all files from a directory recursively with Java

In Java 8, it's a 1-liner via Files.find() with an arbitrarily large depth (eg 999) and BasicFileAttributes of isRegularFile()

public static printFnames(String sDir) {
    Files.find(Paths.get(sDir), 999, (p, bfa) -> bfa.isRegularFile()).forEach(System.out::println);
}

To add more filtering, enhance the lambda, for example all jpg files modified in the last 24 hours:

(p, bfa) -> bfa.isRegularFile()
  && p.getFileName().toString().matches(".*\\.jpg")
  && bfa.lastModifiedTime().toMillis() > System.currentMillis() - 86400000

How to check if all of the following items are in a list?

I would probably use set in the following manner :

set(l).issuperset(set(['a','b'])) 

or the other way round :

set(['a','b']).issubset(set(l)) 

I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/intersection/differences between collections, but it may not be the best option in this situation ...

Getting IP address of client

I use the following static helper method to retrieve the IP of a client:

public static String getClientIpAddr(HttpServletRequest request) {  
    String ip = request.getHeader("X-Forwarded-For");  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("WL-Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_VIA");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("REMOTE_ADDR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getRemoteAddr();  
    }  
    return ip;  
}

How can I display a tooltip message on hover using jQuery?

Following will work like a charm (assuming you have div/span/table/tr/td/etc with "id"="myId")

    $("#myId").hover(function() {
        $(this).css('cursor','pointer').attr('title', 'This is a hover text.');
    }, function() {
        $(this).css('cursor','auto');
    });

As a complimentary, .css('cursor','pointer') will change the mouse pointer on hover.

How do I solve this "Cannot read property 'appendChild' of null" error?

For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.

<html>
    <head>
        <script>
                var div, container = document.getElementById("container")
                for(var i=0;i<5;i++){
                    div = document.createElement("div");
                    div.onclick = function() { 
                        alert("This is a box #"+i);
                    };
                    container.appendChild(div);
                }
            </script>

    </head>
    <body>
        <div id="container"></div>
    </body>
 </html>

https://codepen.io/pcwanderer/pen/MMEREr

Looking at the error in the console for the above code.

Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.

<html>
    <head>
        <style>
        #container{
            height: 200px;
            width: 700px;
            background-color: red;
            margin: 10px;
        }


        div{
            height: 100px;
            width: 100px;
            background-color: purple;
            margin: 20px;
            display: inline-block;
        }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script>
                var div, container = document.getElementById("container")
                for(let i=0;i<5;i++){
                    div = document.createElement("div");
                    div.onclick = function() { 
                        alert("This is a box #"+i);
                    };
                    container.appendChild(div);
                }
            </script>
    </body>
</html>

https://codepen.io/pcwanderer/pen/pXWBQL

I hope this helps. :)

how to Call super constructor in Lombok

If child class has more members, than parent, it could be done not very clean, but short way:

@Data
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class User extends BaseEntity {
    private @NonNull String fullName;
    private @NonNull String email;
    ... 

    public User(Integer id, String fullName, String email, ....) {
        this(fullName, email, ....);
        this.id = id;
    }
}

@Data
@AllArgsConstructor
abstract public class BaseEntity {
   protected Integer id;

   public boolean isNew() {
      return id == null;
   }
}

How to quickly and conveniently disable all console.log statements in my code?

I wrote this:

//Make a copy of the old console.
var oldConsole = Object.assign({}, console);

//This function redefine the caller with the original one. (well, at least i expect this to work in chrome, not tested in others)
function setEnabled(bool) {
    if (bool) {
        //Rewrites the disable function with the original one.
        console[this.name] = oldConsole[this.name];
        //Make sure the setEnable will be callable from original one.
        console[this.name].setEnabled = setEnabled;
    } else {
        //Rewrites the original.
        var fn = function () {/*function disabled, to enable call console.fn.setEnabled(true)*/};
        //Defines the name, to remember.
        Object.defineProperty(fn, "name", {value: this.name});
        //replace the original with the empty one.
        console[this.name] = fn;
        //set the enable function
        console[this.name].setEnabled = setEnabled

    }
}

Unfortunately it doesn't work on use strict mode.

So using console.fn.setEnabled = setEnabled and then console.fn.setEnabled(false) where fn could be almost any console function. For your case would be:

console.log.setEnabled = setEnabled;
console.log.setEnabled(false);

I wrote this too:

var FLAGS = {};
    FLAGS.DEBUG = true;
    FLAGS.INFO = false;
    FLAGS.LOG = false;
    //Adding dir, table, or other would put the setEnabled on the respective console functions.

function makeThemSwitchable(opt) {
    var keysArr = Object.keys(opt);
    //its better use this type of for.
    for (var x = 0; x < keysArr.length; x++) {
        var key = keysArr[x];
        var lowerKey = key.toLowerCase();
        //Only if the key exists
        if (console[lowerKey]) {
            //define the function
            console[lowerKey].setEnabled = setEnabled;
            //Make it enabled/disabled by key.
            console[lowerKey].setEnabled(opt[key]);
        }
    }
}
//Put the set enabled function on the original console using the defined flags and set them.
makeThemSwitchable(FLAGS);

so then you just need to put in the FLAGS the default value (before execute the above code), like FLAGS.LOG = false and the log function would be disabled by default, and still you could enabled it calling console.log.setEnabled(true)

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Template File

<h1>{title}</h1>
<div>{username}</div>

PHP

if (($text = file_get_contents("file.html")) === false) {
    $text = "";
}

$text = str_replace("{title}", "Title Here", $text);
$text = str_replace("{username}", "Username Here", $text);

then you can echo $text as string

What does LayoutInflater in Android do?

LayoutInflater.inflate() provides a means to convert a res/layout/*.xml file defining a view into an actual View object usable in your application source code.

basic two steps: get the inflater and then inflate the resource

How do you get the inflater?

LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

How do you get the view assuming the xml file is "list_item.xml"?

View view = inflater.inflate(R.layout.list_item, parent, false);

AJAX POST and Plus Sign ( + ) -- How to Encode?

If you have to do a curl in php, you should use urlencode() from PHP but individually!

strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")

If you do urlencode(strPOST), you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!

Example 1

$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B

Example 2

$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B

Example 1 is the good way to prepare string for POST in curl

Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!

Iteration ng-repeat only X times in AngularJs

This is the simplest workaround I could think of.

<span ng-repeat="n in [].constructor(5) track by $index">
{{$index}}
</span>

Here's a Plunker example.

Fastest JSON reader/writer for C++

https://github.com/quartzjer/js0n

Ugliest interface possible, but does what you ask. Zero allocations.

http://zserge.com/jsmn.html Another zero-allocation approach.

The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.

Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.

And to answer your "writer" part of the question i doubt that you could beat an efficient

printf("{%s:%s}",name,value)

implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.

EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.

Check if date is in the past Javascript

var datep = $('#datepicker').val();

if(Date.parse(datep)-Date.parse(new Date())<0)
{
   // do something
}

Password masking console application

I have updated Ronnie's version after spending way too much time trying to enter a password only to find out that I had my CAPS LOCK on!

With this version what ever the message is in _CapsLockMessage will "float" at the end of the typing area and will be displayed in red.

This version takes a bit more code and does require a polling loop. On my computer CPU usage about 3% to 4%, but one could always add a small Sleep() value to decrease CPU usage if needed.

    private const string _CapsLockMessage = " CAPS LOCK";

    /// <summary>
    /// Like System.Console.ReadLine(), only with a mask.
    /// </summary>
    /// <param name="mask">a <c>char</c> representing your choice of console mask</param>
    /// <returns>the string the user typed in</returns>
    public static string ReadLineMasked(char mask = '*')
    {
        // Taken from http://stackoverflow.com/a/19770778/486660
        var consoleLine = new StringBuilder();
        ConsoleKeyInfo keyInfo;
        bool isDone;
        bool isAlreadyLocked;
        bool isCapsLockOn;
        int cursorLeft;
        int cursorTop;
        ConsoleColor originalForegroundColor;

        isDone = false;
        isAlreadyLocked = Console.CapsLock;

        while (isDone == false)
        {
            isCapsLockOn = Console.CapsLock;
            if (isCapsLockOn != isAlreadyLocked)
            {
                if (isCapsLockOn)
                {
                    cursorLeft = Console.CursorLeft;
                    cursorTop = Console.CursorTop;
                    originalForegroundColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("{0}", _CapsLockMessage);
                    Console.SetCursorPosition(cursorLeft, cursorTop);
                    Console.ForegroundColor = originalForegroundColor;
                }
                else
                {
                    cursorLeft = Console.CursorLeft;
                    cursorTop = Console.CursorTop;
                    Console.Write("{0}", string.Empty.PadRight(_CapsLockMessage.Length));
                    Console.SetCursorPosition(cursorLeft, cursorTop);
                }
                isAlreadyLocked = isCapsLockOn;
            }

            if (Console.KeyAvailable)
            {
                keyInfo = Console.ReadKey(intercept: true);

                if (keyInfo.Key == ConsoleKey.Enter)
                {
                    isDone = true;
                    continue;
                }

                if (!char.IsControl(keyInfo.KeyChar))
                {
                    consoleLine.Append(keyInfo.KeyChar);
                    Console.Write(mask);
                }
                else if (keyInfo.Key == ConsoleKey.Backspace && consoleLine.Length > 0)
                {
                    consoleLine.Remove(consoleLine.Length - 1, 1);

                    if (Console.CursorLeft == 0)
                    {
                        Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                        Console.Write(' ');
                        Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                    }
                    else
                    {
                        Console.Write("\b \b");
                    }
                }

                if (isCapsLockOn)
                {
                    cursorLeft = Console.CursorLeft;
                    cursorTop = Console.CursorTop;
                    originalForegroundColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("{0}", _CapsLockMessage);
                    Console.CursorLeft = cursorLeft;
                    Console.CursorTop = cursorTop;
                    Console.ForegroundColor = originalForegroundColor;
                }
            }
        }

        Console.WriteLine();

        return consoleLine.ToString();
    }

Open JQuery Datepicker by clicking on an image w/ no input field

<img src='someimage.gif' id="datepicker" />
<input type="hidden" id="dp" />

 $(document).on("click", "#datepicker", function () {
   $("#dp").datepicker({
    dateFormat: 'dd-mm-yy',
    minDate: 'today'}).datepicker( "show" ); 
  });

you just add this code for image clicking or any other html tag clicking event. This is done by initiate the datepicker function when we click the trigger.

How to export a Vagrant virtual machine to transfer it

None of the above answers worked for me. I have been 2 days working out the way to migrate a Vagrant + VirtualBox Machine from a computer to another... It's possible!

First, you need to understand that the virtual machine is separated from your sync / shared folder. So when you pack your machine you're packing it without your files, but with the databases.

What you need to do:

1- Open the CMD of your computer 1 host machine (Command line. Open it as Adminitrator with the right button -> "Run as administrator") and go to your vagrant installed files. On my case: C:/VVV You will see your Vagrantfile an also these folders:

/config/
/database/
/log/
/provision/
/www/
Vagrantfile
...

The /www/ folder is where I have my Sync Folder with my development domains. You may have your sync folder in other place, just be sure to understand what you are doing. Also /config and /database are sync folders.

2- run this command: vagrant package --vagrantfile Vagrantfile

(This command does a package of your virtual machine using you Vagrantfile configuration.)

Here's what you can read on the Vagrant documentation about the command:

A common misconception is that the --vagrantfile option will package a Vagrantfile that is used when vagrant init is used with this box. This is not the case. Instead, a Vagrantfile is loaded and read as part of the Vagrant load process when the box is used. For more information, read about the Vagrantfile load order.

https://www.vagrantup.com/docs/cli/package.html

When finnished, you will have a package.box file.

3- Copy all these files (/config, /database, Vagrantfile, package.box, etc.) and paste them on your Computer 2 just where you want to install your virtual machine (on my case D:/VVV).

Now you have a copy of everything you need on your computer 2 host.

4- run this: vagrant box add package.box --name VVV

(The --name is used to name your virtual machine. On my case it's named VVV) (You can use --force if you already have a virtual machine with this name and want to overwrite it. (Use carefully !))

This will unpack your new vagrant Virtual machine.

5- When finnished, run: vagrant up

The machine will install and you should see it on the "Oracle virtual machine box manager". If you cannot see the virtual machine, try running the Oracle VM box as administrator (right click -> Run as administrator)

You now may have everything ok but remember to see if your hosts are as you expected:

c:/windows/system32/hosts

6- Maybe it's a good idea to copy your host file from your Computer 1 to your Computer 2. Or copy the lines you need. In my case these are the hosts I need:

192.168.50.4 test.dev
192.168.50.4 vvv.dev
...

Where the 192.168.50.4 is the IP of my Virtual machine and test.dev and vvv.dev are developing hosts.

I hope this can help you :) I'll be happy if you feedback your go.

Some particularities of my case that you may find:

When I ran vagrant up, there was a problem with mysql, it wasn't working. I had to run on the Virtual server (right click on the oracle virtual machine -> Show console): apt-get install mysql-server

After this, I ran again vagrant up and everything was working but without data on the databases. So I did a mysqldump all-tables from the Computer 1 and upload them to Computer 2.

OTHER NOTES: My virtual machine is not exactly on Computer 1 and Computer 2. For example, I made some time ago internal configuration to use NFS (to speed up the server sync folders) and I needed to run again this command on the Computer 2 host: vagrant plugin install vagrant-winnfsd

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Here is another way to reproduce this error in Python2.7 with numpy:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate(a,b)   #note the lack of tuple format for a and b
print(c) 

The np.concatenate method produces an error:

TypeError: only length-1 arrays can be converted to Python scalars

If you read the documentation around numpy.concatenate, then you see it expects a tuple of numpy array objects. So surrounding the variables with parens fixed it:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate((a,b))  #surround a and b with parens, packaging them as a tuple
print(c) 

Then it prints:

[1 2 3 4 5 6]

What's going on here?

That error is a case of bubble-up implementation - it is caused by duck-typing philosophy of python. This is a cryptic low-level error python guts puke up when it receives some unexpected variable types, tries to run off and do something, gets part way through, the pukes, attempts remedial action, fails, then tells you that "you can't reformulate the subspace responders when the wind blows from the east on Tuesday".

In more sensible languages like C++ or Java, it would have told you: "you can't use a TypeA where TypeB was expected". But Python does it's best to soldier on, does something undefined, fails, and then hands you back an unhelpful error. The fact we have to be discussing this is one of the reasons I don't like Python, or its duck-typing philosophy.

How to save username and password in Git?

For windows users look at the .gitconfig file and check what has been configured for the credential helper if you have the following...

[credential "helperselector"] selected = wincred

you'll find the credentials in the Windows Credential Manager.

enter image description here

There you can edit the credential.

EDIT: Wincred has been deprecated, see...

https://github.com/git-for-windows/git-sdk-64/tree/main/mingw64/doc/git-credential-manager

So alternatively you may want to reconfigure git to use the built-in GIT credential manager...

git config --global credential.helper manager

Generate random numbers uniformly over an entire range

If RAND_MAX is 32767, you can double the number of bits easily.

int BigRand()
{
    assert(INT_MAX/(RAND_MAX+1) > RAND_MAX);
    return rand() * (RAND_MAX+1) + rand();
}

How can I add private key to the distribution certificate?

This site explain step by step that what you need to do Certificates, Identifiers & Profiles and as your question

"Valid Signing identity not found"?

You need the private key that were used to sign the code base with provisioning profile. . If you don't have then you can generate a new signing request on the iOS developer portal.

For Export:

Xcode -> Organizer, select your team. Click Export. Specify a filename and a password, and click Save.`

For Import:

Xcode -> Organizer, select your team. Click Import. Select the file containing your code signing assets. Enter the password for the file, and click Open.

Converting pixels to dp

Probably the best way if you have the dimension inside values/dimen is to get the dimension directly from getDimension() method, it will return you the dimension already converted into pixel value.

context.getResources().getDimension(R.dimen.my_dimension)

Just to better explain this,

getDimension(int resourceId) 

will return the dimension already converted to pixel AS A FLOAT.

getDimensionPixelSize(int resourceId)

will return the same but truncated to int, so AS AN INTEGER.

See Android reference

Date formatting in WPF datagrid

This is a very old question, but I found a new solution, so I wrote about it.

First of all, is this way of solution possible while using AutoGenerateColumns?

Yes, that can be done with AttachedProperty as follows.

<DataGrid AutoGenerateColumns="True" 
   local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
   ItemsSource="{Binding}" />

AttachedProperty

There are two AttachedProperty defined that allow you to specify two formats. DateTimeFormatAutoGenerate for DateTime and TimeSpanFormatAutoGenerate for TimeSpan.

class DataGridOperation
{
    public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
    public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));

    public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
    public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));

    private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is DataGrid dGrid))
            return;

        if ((e.NewValue is string format))
            dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
    }

    private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
    {
        if (e.PropertyType == typeof(T))
            (e.Column as DataGridTextColumn).Binding.StringFormat = format;
    }
}

How to use

View

<Window
   x:Class="DataGridAutogenerateCustom.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:DataGridAutogenerateCustom"
   Width="400" Height="250">
   <Window.DataContext>
      <local:MainWindowViewModel />
   </Window.DataContext>
   <StackPanel>
      <TextBlock Text="DEFAULT FORMAT" />
      <DataGrid ItemsSource="{Binding Dates}" />

      <TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
      <DataGrid
         local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
         local:DataGridOperation.TimeSpanFormatAutoGenerate="dd\-hh\-mm\-ss"
         ItemsSource="{Binding Dates}" />
   </StackPanel>
</Window>

ViewModel

public class MainWindowViewModel
{
    public DatePairs[] Dates { get; } = new DatePairs[]
    {
        new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
        new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
    };
}

public class DatePairs
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan Span => EndDate - StartDate;
}

demo_wpf_datagrid

How to fix "Attempted relative import in non-package" even with __init__.py

This is very confusing, and if you are using IDE like pycharm, it's little more confusing. What worked for me: 1. Make pycharm project settings (if you are running python from a VE or from python directory) 2. There is no wrong the way you defined. sometime it works with from folder1.file1 import class

if it does not work, use import folder1.file1 3. Your environment variable should be correctly mentioned in system or provide it in your command line argument.

How to get JSON response from http.Get

The ideal way is not to use ioutil.ReadAll, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a target structure.

var myClient = &http.Client{Timeout: 10 * time.Second}

func getJson(url string, target interface{}) error {
    r, err := myClient.Get(url)
    if err != nil {
        return err
    }
    defer r.Body.Close()

    return json.NewDecoder(r.Body).Decode(target)
}

Example use:

type Foo struct {
    Bar string
}

func main() {
    foo1 := new(Foo) // or &Foo{}
    getJson("http://example.com", foo1)
    println(foo1.Bar)

    // alternately:

    foo2 := Foo{}
    getJson("http://example.com", &foo2)
    println(foo2.Bar)
}

You should not be using the default *http.Client structure in production as this answer originally demonstrated! (Which is what http.Get/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.

SELECT * FROM multiple tables. MySQL

What you do here is called a JOIN (although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.

But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!

If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).

In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):

SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg
dew      4       ./images/dew-1.jpg

In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:

SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew      4       ./images/dew-1.jpg,./images/dew-2.jpg

However, this can get dangerous if you have , within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.

Default value in an asp.net mvc view model

What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.

If you load the search criteria from elsewhere, then you should probably have some mapping logic.

Random float number generation

For C++, it can generate real float numbers within the range specified by dist variable

#include <random>  //If it doesnt work then use   #include <tr1/random>
#include <iostream>

using namespace std;

typedef std::tr1::ranlux64_base_01 Myeng; 
typedef std::tr1::normal_distribution<double> Mydist;

int main() { 
       Myeng eng; 
       eng.seed((unsigned int) time(NULL)); //initializing generator to January 1, 1970);
       Mydist dist(1,10); 

       dist.reset(); // discard any cached values 
       for (int i = 0; i < 10; i++)
       {
           std::cout << "a random value == " << (int)dist(eng) << std::endl; 
       }

       return (0);
}

Java - escape string to prevent SQL injection

From:Source

public String MysqlRealScapeString(String str){
  String data = null;
  if (str != null && str.length() > 0) {
    str = str.replace("\\", "\\\\");
    str = str.replace("'", "\\'");
    str = str.replace("\0", "\\0");
    str = str.replace("\n", "\\n");
    str = str.replace("\r", "\\r");
    str = str.replace("\"", "\\\"");
    str = str.replace("\\x1a", "\\Z");
    data = str;
  }
  return data;
}

TLS 1.2 in .NET Framework 4.0

According to this, you will need .NET 4.5 installed. For more details, visit the webpage. The gist of it is that after you have .NET 4.5 installed, your 4.0 apps will use the 4.5 System.dll. You can enable TLS 1.2 in two ways:

  • At the beginning of the application, add this code: ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
  • Set the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319: SchUseStrongCrypto to DWORD 1

How to extract filename.tar.gz file

The other scenario you mush verify is that the file you're trying to unpack is not empty and is valid.

In my case I wasn't downloading the file correctly, after double check and I made sure I had the right file I could unpack it without any issues.

Angular js init ng-model from default values

As others pointed out, it is not good practice to initialize data on views. Initializing data on Controllers, however, is recommended. (see http://docs.angularjs.org/guide/controller)

So you can write

<input name="card[description]" ng-model="card.description">

and

$scope.card = { description: 'Visa-4242' };

$http.get('/getCardInfo.php', function(data) {
   $scope.card = data;
});

This way the views do not contain data, and the controller initializes the value while the real values are being loaded.

Find common substring between two strings

This is the classroom problem called 'Longest sequence finder'. I have given some simple code that worked for me, also my inputs are lists of a sequence which can also be a string:

def longest_substring(list1,list2):
    both=[]
    if len(list1)>len(list2):
        small=list2
        big=list1
    else:
        small=list1
        big=list2
    removes=0
    stop=0
    for i in small:
        for j in big:
            if i!=j:
                removes+=1
                if stop==1:
                    break
            elif i==j:
                both.append(i)
                for q in range(removes+1):
                    big.pop(0)
                stop=1
                break
        removes=0
    return both

Count words in a string method?

Hi I just figured out with StringTokenizer like this:

String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();

Mailto links do nothing in Chrome but work in Firefox?

I found this answer on a Google forum that has worked me. In the footnotes it mentions 'googleapps.exe' - I don't have this and it has still worked. Simply follow the instructions below but close down all applications before making changes to the Registry. Also I saved the existing value just in case it didn't work.


Simply type "run" in your search bar, then type "regedit" then travel to:

HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\shell\open\command\ 

edit (double click) "(Default)" to:

"C:\Program Files (x86)\Google\Google Apps\googleapps.exe" --domain= --mailto.google.com="%1" 

That's it! Save and close it and it should work beautifully!

Using this method prevents you from having to download the GMail Notifier, which for those of us with GTalk don't need since it does it for us. I'm not sure why Google can't solve this issue easily.. i've heard Google Apps haven't been tested fully on Windows 7 but it's obvious the same tag works with it.

Note: The only thing with this solution is you need to have the googleapps.exe file on your machine. I believe I got it with my free GooglePack from their site which has now been discontinued. I tried searching the net for a way to download it but weirdly enough it seems it's reserved only for Businesses now and there is no download link available from the web because everyone who has it streamed it using the google updater.. Odd. Anyway good luck!

What is the difference between DBMS and RDBMS?

DBMS: is a software system that allows Defining, Creation, Querying, Update, and Administration of data stored in data files.

Features:

  • Normal book keeping system, Flat files, MS Excel, FoxPRO, XML, etc.
  • Less or No provision for: Constraints, Security, ACID rules, users, etc.

RDBMS: is a DBMS that is based on Relational model that stores data in tabular form.

  • SQL Server, Sybase, Oracle, MySQL, IBM DB2, MS Access, etc.

Features:

  • Database, with Tables having relations maintained by FK
  • DDL, DML
  • Data Integrity & ACID rules
  • Multiple User Access
  • Backup & Restore
  • Database Administration

ng-model for `<input type="file"/>` (with directive DEMO)

I create a directive and registered on bower.

This lib will help you modeling input file, not only return file data but also file dataurl or base 64.

{
    "lastModified": 1438583972000,
    "lastModifiedDate": "2015-08-03T06:39:32.000Z",
    "name": "gitignore_global.txt",
    "size": 236,
    "type": "text/plain",
    "data": "data:text/plain;base64,DQojaWdub3JlIHRodW1ibmFpbHMgY3JlYXRlZCBieSB3aW5kb3dz…xoDQoqLmJhaw0KKi5jYWNoZQ0KKi5pbGsNCioubG9nDQoqLmRsbA0KKi5saWINCiouc2JyDQo="
}

https://github.com/mistralworks/ng-file-model/

HTML - Arabic Support

As mentioned above, by default text editors will not use UTF-8 as the standard encoding for documents. However most editors will allow you to change that in the settings. Even for each specific document.

MySQL DAYOFWEEK() - my week begins with monday

Try to use the WEEKDAY() function.

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

Struct memory layout in C

It's implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is:

  • Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.)
  • If necessary, padding is added before each struct member, to ensure correct alignment.
  • Each primitive type T requires an alignment of sizeof(T) bytes.

So, given the following struct:

struct ST
{
   char ch1;
   short s;
   char ch2;
   long long ll;
   int i;
};
  • ch1 is at offset 0
  • a padding byte is inserted to align...
  • s at offset 2
  • ch2 is at offset 4, immediately after s
  • 3 padding bytes are inserted to align...
  • ll at offset 8
  • i is at offset 16, right after ll
  • 4 padding bytes are added at the end so that the overall struct is a multiple of 8 bytes. I checked this on a 64-bit system: 32-bit systems may allow structs to have 4-byte alignment.

So sizeof(ST) is 24.

It can be reduced to 16 bytes by rearranging the members to avoid padding:

struct ST
{
   long long ll; // @ 0
   int i;        // @ 8
   short s;      // @ 12
   char ch1;     // @ 14
   char ch2;     // @ 15
} ST;

Check for false

You can use something simpler:

if(!var){
    console.log('var is false'); 
}

Reflection - get attribute name and value on property

Necromancing.
For those that still have to maintain .NET 2.0, or those that want to do it without LINQ:

public static object GetAttribute(System.Reflection.MemberInfo mi, System.Type t)
{
    object[] objs = mi.GetCustomAttributes(t, true);

    if (objs == null || objs.Length < 1)
        return null;

    return objs[0];
}



public static T GetAttribute<T>(System.Reflection.MemberInfo mi)
{
    return (T)GetAttribute(mi, typeof(T));
}


public delegate TResult GetValue_t<in T, out TResult>(T arg1);

public static TValue GetAttributValue<TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t<TAttribute, TValue> value) where TAttribute : System.Attribute
{
    TAttribute[] objAtts = (TAttribute[])mi.GetCustomAttributes(typeof(TAttribute), true);
    TAttribute att = (objAtts == null || objAtts.Length < 1) ? default(TAttribute) : objAtts[0];
    // TAttribute att = (TAttribute)GetAttribute(mi, typeof(TAttribute));

    if (att != null)
    {
        return value(att);
    }
    return default(TValue);
}

Example usage:

System.Reflection.FieldInfo fi = t.GetField("PrintBackground");
wkHtmlOptionNameAttribute att = GetAttribute<wkHtmlOptionNameAttribute>(fi);
string name = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, delegate(wkHtmlOptionNameAttribute a){ return a.Name;});

or simply

string aname = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, a => a.Name );

How do you select the entire excel sheet with Range using VBA?

Here is what I used, I know it could use some perfecting, but I think it will help others...

''STYLING''

Dim sheet As Range

' Find Number of rows used
Dim Final As Variant
    Final = Range("A1").End(xlDown).Row

' Find Last Column
Dim lCol As Long
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column

Set sheet = ActiveWorkbook.ActiveSheet.Range("A" & Final & "", Cells(1, lCol ))
With sheet
    .Interior.ColorIndex = 1
End With

Make index.html default, but allow index.php to be visited if typed in

If you're using WordPress, there is now a filter hook to resolve this:

remove_filter('template_redirect', 'redirect_canonical'); 

(Put this in your theme's functions.php)

This tells WordPress to not redirect index.php back to the root page, but to sit where it is. That way, index.html can be assigned to be the default page in .htaccess and can work alongside index.php.

How do you easily horizontally center a <div> using CSS?

CSS, HTML:

_x000D_
_x000D_
div.mydiv {width: 200px; margin: 0 auto}
_x000D_
<div class="mydiv">_x000D_
    _x000D_
    I am in the middle_x000D_
    _x000D_
</div>
_x000D_
_x000D_
_x000D_

Your diagram shows a block level element also (which a div usually is), not an inline one.

Of the top of my head, min-width is supported in FF2+/Safari3+/IE7+. Can be done for IE6 using hackety CSS, or a simple bit of JS.

All shards failed

If you're running a single node cluster for some reason, you might simply need to do avoid replicas, like this:

curl -XPUT -H 'Content-Type: application/json' 'localhost:9200/_settings' -d '
{
    "index" : {
        "number_of_replicas" : 0
    }
}'

Doing this you'll force to use es without replicas

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

The offending lines are the following:

MaxConnections=90
InitialConnections=80

You can increase the values to allow more connections.

Swap two items in List<T>

There is no existing Swap-method, so you have to create one yourself. Of course you can linqify it, but that has to be done with one (unwritten?) rules in mind: LINQ-operations do not change the input parameters!

In the other "linqify" answers, the (input) list is modified and returned, but this action brakes that rule. If would be weird if you have a list with unsorted items, do a LINQ "OrderBy"-operation and than discover that the input list is also sorted (just like the result). This is not allowed to happen!

So... how do we do this?

My first thought was just to restore the collection after it was finished iterating. But this is a dirty solution, so do not use it:

static public IEnumerable<T> Swap1<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.

    // Swap the items.
    T temp = source[index1];
    source[index1] = source[index2];
    source[index2] = temp;

    // Return the items in the new order.
    foreach (T item in source)
        yield return item;

    // Restore the collection.
    source[index2] = source[index1];
    source[index1] = temp;
}

This solution is dirty because it does modify the input list, even if it restores it to the original state. This could cause several problems:

  1. The list could be readonly which will throw an exception.
  2. If the list is shared by multiple threads, the list will change for the other threads during the duration of this function.
  3. If an exception occurs during the iteration, the list will not be restored. (This could be resolved to write an try-finally inside the Swap-function, and put the restore-code inside the finally-block).

There is a better (and shorter) solution: just make a copy of the original list. (This also makes it possible to use an IEnumerable as a parameter, instead of an IList):

static public IEnumerable<T> Swap2<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.

    // If nothing needs to be swapped, just return the original collection.
    if (index1 == index2)
        return source;

    // Make a copy.
    List<T> copy = source.ToList();

    // Swap the items.
    T temp = copy[index1];
    copy[index1] = copy[index2];
    copy[index2] = temp;

    // Return the copy with the swapped items.
    return copy;
}

One disadvantage of this solution is that it copies the entire list which will consume memory and that makes the solution rather slow.

You might consider the following solution:

static public IEnumerable<T> Swap3<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.
    // It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.

    using (IEnumerator<T> e = source.GetEnumerator())
    {
        // Iterate to the first index.
        for (int i = 0; i < index1; i++)
            yield return source[i];

        // Return the item at the second index.
        yield return source[index2];

        if (index1 != index2)
        {
            // Return the items between the first and second index.
            for (int i = index1 + 1; i < index2; i++)
                yield return source[i];

            // Return the item at the first index.
            yield return source[index1];
        }

        // Return the remaining items.
        for (int i = index2 + 1; i < source.Count; i++)
            yield return source[i];
    }
}

And if you want to input parameter to be IEnumerable:

static public IEnumerable<T> Swap4<T>(this IEnumerable<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.
    // It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.

    using(IEnumerator<T> e = source.GetEnumerator())
    {
        // Iterate to the first index.
        for(int i = 0; i < index1; i++) 
        {
            if (!e.MoveNext())
                yield break;
            yield return e.Current;
        }

        if (index1 != index2)
        {
            // Remember the item at the first position.
            if (!e.MoveNext())
                yield break;
            T rememberedItem = e.Current;

            // Store the items between the first and second index in a temporary list. 
            List<T> subset = new List<T>(index2 - index1 - 1);
            for (int i = index1 + 1; i < index2; i++)
            {
                if (!e.MoveNext())
                    break;
                subset.Add(e.Current);
            }

            // Return the item at the second index.
            if (e.MoveNext())
                yield return e.Current;

            // Return the items in the subset.
            foreach (T item in subset)
                yield return item;

            // Return the first (remembered) item.
            yield return rememberedItem;
        }

        // Return the remaining items in the list.
        while (e.MoveNext())
            yield return e.Current;
    }
}

Swap4 also makes a copy of (a subset of) the source. So worst case scenario, it is as slow and memory consuming as function Swap2.

Notification Icon with the new Firebase Cloud Messaging system

Use a server implementation to send messages to your client and use data type of messages rather than notification type of messages.

This will help you get a callback to onMessageReceived irrespective if your app is in background or foreground and you can generate your custom notification then

generate a random number between 1 and 10 in c

You need a different seed at every execution.

You can start to call at the beginning of your program:

srand(time(NULL));

Note that % 10 yields a result from 0 to 9 and not from 1 to 10: just add 1 to your % expression to get 1 to 10.

Plotting multiple curves same graph and same scale

(The typical method would be to use plot just once to set up the limits, possibly to include the range of all series combined, and then to use points and lines to add the separate series.) To use plot multiple times with par(new=TRUE) you need to make sure that your first plot has a proper ylim to accept the all series (and in another situation, you may need to also use the same strategy for xlim):

# first plot
plot(x, y1, ylim=range(c(y1,y2)))

# second plot  EDIT: needs to have same ylim
par(new = TRUE)
plot(x, y2, ylim=range(c(y1,y2)), axes = FALSE, xlab = "", ylab = "")

enter image description here

This next code will do the task more compactly, by default you get numbers as points but the second one gives you typical R-type-"points":

  matplot(x, cbind(y1,y2))
  matplot(x, cbind(y1,y2), pch=1)

No appenders could be found for logger(log4j)?

It looks like you need to add the location of your log4j.properties file to the Classpath in Eclipse.

Make sure your project is open in Eclipse, then click on the "Run" menu at the top of Eclipse and click on the following:

  1. Run
  2. Run Configurations
  3. Classpath (tab)
  4. User Entries
  5. Advanced (button on the right)
  6. Add Folders
  7. then navigate to the folder that contains your log4j.properties file
  8. Apply
  9. Run

The error message should no longer appear.

Close a div by clicking outside

An other way which makes then your jsfiddle less buggy (needed double click on open).

This doesn't use any delegated event to body level

Set tabindex="-1" to DIV .popup ( and for style CSS outline:0 )

DEMO

$(".link").click(function(e){
    e.preventDefault();
    $(".popup").fadeIn(300,function(){$(this).focus();});
});

$('.close').click(function() {
   $(".popup").fadeOut(300);
});
$(".popup").on('blur',function(){
    $(this).fadeOut(300);
});

Do I cast the result of malloc?

From the Wikipedia:

Advantages to casting

  • Including the cast may allow a C program or function to compile as C++.

  • The cast allows for pre-1989 versions of malloc that originally returned a char *.

  • Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the malloc() call (although modern compilers and static analyzers can warn on such behaviour without requiring the cast).

Disadvantages to casting

  • Under the ANSI C standard, the cast is redundant.

  • Adding the cast may mask failure to include the header stdlib.h, in which the prototype for malloc is found. In the absence of a prototype for malloc, the standard requires that the C compiler assume malloc returns an int. If there is no cast, a warning is issued when this integer is assigned to the pointer; however, with the cast, this warning is not produced, hiding a bug. On certain architectures and data models (such as LP64 on 64-bit systems, where long and pointers are 64-bit and int is 32-bit), this error can actually result in undefined behaviour, as the implicitly declared malloc returns a 32-bit value whereas the actually defined function returns a 64-bit value. Depending on calling conventions and memory layout, this may result in stack smashing. This issue is less likely to go unnoticed in modern compilers, as they uniformly produce warnings that an undeclared function has been used, so a warning will still appear. For example, GCC's default behaviour is to show a warning that reads "incompatible implicit declaration of built-in function" regardless of whether the cast is present or not.

  • If the type of the pointer is changed at its declaration, one may also, need to change all lines where malloc is called and cast.

Although malloc without casting is preferred method and most experienced programmers choose it, you should use whichever you like having aware of the issues.

i.e: If you need to compile C program as C++ (Although it is a separate language) you must cast the result of use malloc.

PostgreSQL: Which version of PostgreSQL am I running?

If Select version() returns with Memo try using the command this way:

Select version::char(100) 

or

Select version::varchar(100)

Can the :not() pseudo-class have multiple arguments?

If you install the "cssnext" Post CSS plugin, then you can safely start using the syntax that you want to use right now.

Using cssnext will turn this:

input:not([type="radio"], [type="checkbox"]) {
  /* css here */
}

Into this:

input:not([type="radio"]):not([type="checkbox"]) {
  /* css here */
}

https://cssnext.github.io/features/#not-pseudo-class

Thymeleaf using path variables to th:href

Your code looks syntactically correct, but I think your property doesn't exist to create the URL.

I just tested it, and it works fine for me.

Try using category.idCategory instead of category.id, for example…

  <tr th:each="category : ${categories}">
    <td th:text="${category.idCategory}"></td>
    <td th:text="${category.name}"></td>
    <td>
      <a th:href="@{'/category/edit/' + ${category.idCategory}}">view</a>
    </td>
  </tr>

IE11 prevents ActiveX from running

There is no solution to this problem. As of IE11 on Windows 8, Microsoft no longer allows ActiveX plugins to run in its browser space. There is absolutely nothing that a third party developer can do about it.

A similar thing has recently happened with the Chrome browser which no longer supports NPAPI plugins. Instead Chrome only supports PPAPI plugins which are useless for system level tasks once performed by NPAPI plugins.

So developers needing browser support for system interactive plugins can only recommend either the Firefox browser or the ASPS web browser.

Editor does not contain a main type

If it is maven project please check the java file is created under src/main/java

If you are not getting please change the JRE path and create the java files in above folder structure

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

How to run Spring Boot web application in Eclipse itself?

Choose the project in eclipse - > Select run as -> Choose Java application. This displays a popup forcing you to select something, try searching your class having the main method in the search box. Once you find it, select it and hit ok. This will launch the spring boot application.

I do not have the spring tool suite installed in eclipse yet and still, it works. I hope this helps.

ReferenceError: document is not defined (in plain JavaScript)

try: window.document......

var body = window.document.getElementsByTagName("body")[0];

How can I save multiple documents concurrently in Mongoose/Node.js?

Mongoose 4.4 added a method called insertMany

Shortcut for validating an array of documents and inserting them into MongoDB if they're all valid. This function is faster than .create() because it only sends one operation to the server, rather than one for each document.

Quoting vkarpov15 from issue #723:

The tradeoffs are that insertMany() doesn't trigger pre-save hooks, but it should have better performance because it only makes 1 round-trip to the database rather than 1 for each document.

The method's signature is identical to create:

Model.insertMany([ ... ], (err, docs) => {
  ...
})

Or, with promises:

Model.insertMany([ ... ]).then((docs) => {
  ...
}).catch((err) => {
  ...
})

Where is HttpContent.ReadAsAsync?

Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.

What are these ^M's that keep showing up in my files in emacs?

As everyone has mentioned. It's different line ending style. MacOSX uses Unix line endings - i.e. LF (line feed).

Windows uses both CR (carriage return) & LF (line feed) as a line ending. Since you're using both windows and mac thats where the problem stems from.

If you create a file in windows and then bring it onto the mac you might see these ^M characters at the end of the lines.

If you want to remove them you can do this very easily in emacs. Just highlight and copy the ^M character and do a query-replace ^M with and you'e done.

EDIT: Some other links that may be of help. http://xahlee.org/emacs/emacs_adv_tips.html

This one helps you configure emacs to use a particular type of line-ending style. http://www.emacswiki.org/emacs/EndOfLineTips

How to get a value from a cell of a dataframe?

These are fast access for scalars

In [15]: df = pandas.DataFrame(numpy.random.randn(5,3),columns=list('ABC'))

In [16]: df
Out[16]: 
          A         B         C
0 -0.074172 -0.090626  0.038272
1 -0.128545  0.762088 -0.714816
2  0.201498 -0.734963  0.558397
3  1.563307 -1.186415  0.848246
4  0.205171  0.962514  0.037709

In [17]: df.iat[0,0]
Out[17]: -0.074171888537611502

In [18]: df.at[0,'A']
Out[18]: -0.074171888537611502

Array Length in Java

if you mean by "logical size", the index of array, then simply int arrayLength = arr.length-1; since the the array index starts with "0", so the logical or "array index" will always be less than the actual size by "one".

Specify multiple attribute selectors in CSS

Just to add that there should be no space between the selector and the opening bracket.

td[someclass] 

will work. But

td [someclass] 

will not.

Where are shared preferences stored?

I just tried to get path of shared preferences below like this.This is work for me.

File f = getDatabasePath("MyPrefsFile.xml");

if (f != null)
    Log.i("TAG", f.getAbsolutePath());

Removing duplicates from a String in Java

You can't. You can create a new String that has duplicates removed. Why aren't you using StringBuilder (or StringBuffer, presumably)?

You can run through the string and store the unique characters in a char[] array, keeping track of how many unique characters you've seen. Then you can create a new String using the String(char[], int, int) constructor.

Also, the problem is a little ambiguous—does “duplicates” mean adjacent repetitions? (In other words, what should happen with abcab?)

replace String with another in java

Try this: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29

String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");

System.out.println(r);

This would print out "Brother How are you!"