Programs & Examples On #Qa

Quality assurance, or QA for short, is the systematic monitoring and evaluation of the various aspects of a project, service or facility to maximize the probability that minimum standards of quality are being attained by the production process. QA cannot absolutely guarantee the production of quality products.

What tools do you use to test your public REST API?

I am using DevHttpClient Plugin for chrome, its handy. it does also saves previous actions. clean UI as well

Best way to stress test a website

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

The obvious downside, however, is the price.

Should black box or white box testing be the emphasis for testers?

  • *Black box testing: Is the test at system level to check the functionality of the system, to ensure that the system performs all the functions that it was designed for, Its mainly to uncover defects found at the user point. Its better to hire a professional tester to black box your system, 'coz the developer usually tests with a perspective that the codes he had written is good and meets the functional requirements of the clients so he could miss out a lot of things (I don't mean to offend anybody)
  • Whitebox is the first test that is done in the SDLC.This is to uncover bugs like runtime errors and compilation errrors It can be done either by testers or by Developer himself, But I think its always better that the person who wrote the code tests it.He understands them more than another person.*

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

I had problems using pdftk with the cat parameter had a better success with output.

The following command worked for me:

pdftk file_1.pdf file_1.pdf file_1.pdf file_1.pdf cat output.pdf

Using cat produced the following error:

Error: Unexpected text in page range end, here: 
    output.pdf
    Exiting.
    Acceptable keywords, for example: "even" or "odd".
    To rotate pages, use: "north" "south" "east"
        "west" "left" "right" or "down"
Errors encountered.  No output created.
Done.  Input errors, so no output created.

http://www.pdflabs.com/docs/pdftk-cli-examples/.

I created a 172mb PDF is no time at all.

How-to turn off all SSL checks for postman for a specific site

There is an option in Postman if you download it from https://www.getpostman.com instead of the chrome store (most probably it has been introduced in the new versions and the chrome one will be updated later) not sure about the old ones.

In the settings, turn off the SSL certificate verification option enter image description here

Be sure to remember to reactivate it afterwards, this is a security feature.

If you really want to use the chrome app, you could always add an exception to chrome for the url: Enter the url you would like to open in the chrome browser, you'll get a warning with a link at the bottom of the page to add an exception, which if you do, it will also allow postman to access your url. But the first option of using the postman stand-alone app is much better.

I hope this can help.

How to avoid 'cannot read property of undefined' errors?

You can avoid getting an error by giving a default value before getting the property

_x000D_
_x000D_
var test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];

for (i=0; i<test.length; i++) {
    const obj = test[i]
    // No error, just undefined, which is ok
    console.log(((obj.a || {}).b || {}).c);
}
_x000D_
_x000D_
_x000D_

This works great with arrays too:

_x000D_
_x000D_
const entries = [{id: 1, name: 'Scarllet'}]
// Giving a default name when is empty
const name = (entries.find(v => v.id === 100) || []).name || 'no-name'
console.log(name)
_x000D_
_x000D_
_x000D_

Class type check in TypeScript

TypeScript have a way of validating the type of a variable in runtime. You can add a validating function that returns a type predicate. So you can call this function inside an if statement, and be sure that all the code inside that block is safe to use as the type you think it is.

Example from the TypeScript docs:

function isFish(pet: Fish | Bird): pet is Fish {
   return (<Fish>pet).swim !== undefined;
}

// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
  pet.swim();
}
else {
  pet.fly();
}

See more at: https://www.typescriptlang.org/docs/handbook/advanced-types.html

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

Convert varchar into datetime in SQL Server

use Try_Convert:Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

DECLARE @DateString VARCHAR(10) ='20160805'
SELECT TRY_CONVERT(DATETIME,@DateString)

SET @DateString ='Invalid Date'
SELECT TRY_CONVERT(DATETIME,@DateString)

Link:MSDN TRY_CONVERT (Transact-SQL)

Selecting the last value of a column

I'm surprised no one had ever given this answer before. But this should be the shortest and it even works in excel :

=ARRAYFORMULA(LOOKUP(2,1/(G2:G<>""),G2:G))

G2:G<>"" creates a array of 1/true(1) and 1/false(0). Since LOOKUP does a top down approach to find 2 and Since it'll never find 2,it comes up to the last non blank row and gives the position of that.

The other way to do this, as others might've mentioned, is:

=INDEX(G2:G,MAX((ISBLANK(G2:G)-1)*-ROW(G2:G))-1)

Finding the MAXimum ROW of the non blank row and feeding it to INDEX

In a zero blank interruption array, Using INDIRECT RC notation with COUNTBLANK is another option. If V4:V6 is occupied with entries, then,

V18:

=INDIRECT("R[-"&COUNTBLANK(V4:V17)+1&"]C",0)

will give the position of V6.

for loop in Python

In Python you generally have for in loops instead of general for loops like C/C++, but you can achieve the same thing with the following code.

for k in range(1, c+1, 2):
  do something with k

Reference Loop in Python.

How can I embed a YouTube video on GitHub wiki pages?

Markdown does not officially support video embeddings but you can embed raw HTML in it. I tested out with GitHub Pages and it works flawlessly.

  1. Go to the Video page on YouTube and click on the Share Button
  2. Choose Embed
  3. Copy and Paste the HTML snippet in your markdown

The snippet looks like:

    <iframe width="560" height="315"
src="https://www.youtube.com/embed/MUQfKFzIOeU" 
frameborder="0" 
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" 
allowfullscreen></iframe>

PS: You can check out the live preview here

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

keep using the id


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserVerification extends Model
{
    protected $table = 'user_verification';
    protected $fillable =   [
                            'id',
                            'email',
                            'verification_token'
                            ];
    //$timestamps = false;
    protected $primaryKey = 'verification_token';
}

and get the email :

$usr = User::find($id);
$token = $usr->verification_token;
$email = UserVerification::find($token);

Error while inserting date - Incorrect date value:

You need to convert the date to YYYY-MM-DD in order to insert it as a MySQL date using the default configuration.

One way to do that is STR_TO_DATE():

insert into your_table (...)
values (...,str_to_date('07-25-2012','%m-%d-%Y'),...);

How to make a div with no content have a width?

There are different methods to make the empty DIV with float: left or float: right visible.

Here presents the ones I know:

  • set width(or min-width) with height (or min-height)
  • or set padding-top
  • or set padding-bottom
  • or set border-top
  • or set border-bottom
  • or use pseudo-elements: ::before or ::after with:
    • {content: "\200B";}
    • or {content: "."; visibility: hidden;}
  • or put &nbsp; inside DIV (this sometimes can bring unexpected effects eg. in combination with text-decoration: underline;)

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX is supported by Chrome.

Chrome check parameters defined in : control panel/Internet option/Security.

Nevertheless,if it's possible to define four different area with IE, Chrome only check "Internet" area.

Can gcc output C code after preprocessing?

Suppose we have a file as Message.cpp or a .c file

Steps 1: Preprocessing (Argument -E )

g++ -E .\Message.cpp > P1

P1 file generated has expanded macros and header file contents and comments are stripped off.

Step 2: Translate Preprocessed file to assembly (Argument -S). This task is done by compiler

g++ -S .\Message.cpp

An assembler (ASM) is generated (Message.s). It has all the assembly code.

Step 3: Translate assembly code to Object code. Note: Message.s was generated in Step2. g++ -c .\Message.s

An Object file with the name Message.o is generated. It is the binary form.

Step 4: Linking the object file. This task is done by linker

g++ .\Message.o -o MessageApp

An exe file MessageApp.exe is generated here.

#include <iostream>
using namespace std;

 //This a sample program
  int main()
{
cout << "Hello" << endl;
 cout << PQR(P,K) ;
getchar();
return 0;
}

How to enable zoom controls and pinch zoom in a WebView?

Try this code, I get working fine.

 webSettings.setSupportZoom(true);
 webSettings.setBuiltInZoomControls(true);
 webSettings.setDisplayZoomControls(false);

Convert an object to an XML string

Here are conversion method for both ways. this = instance of your class

public string ToXML()
    {
        using(var stringwriter = new System.IO.StringWriter())
        { 
            var serializer = new XmlSerializer(this.GetType());
            serializer.Serialize(stringwriter, this);
            return stringwriter.ToString();
        }
    }

 public static YourClass LoadFromXMLString(string xmlText)
    {
        using(var stringReader = new System.IO.StringReader(xmlText))
        {
            var serializer = new XmlSerializer(typeof(YourClass ));
            return serializer.Deserialize(stringReader) as YourClass ;
        }
    }

Controller 'ngModel', required by directive '...', can't be found

As described here: Angular NgModelController, you should provide the <input with the required controller ngModel

<input submit-required="true" ng-model="user.Name"></input>

Calling a class function inside of __init__

How about:

class MyClass(object):
    def __init__(self, filename):
        self.filename = filename 
        self.stats = parse_file(filename)

def parse_file(filename):
    #do some parsing
    return results_from_parse

By the way, if you have variables named stat1, stat2, etc., the situation is begging for a tuple: stats = (...).

So let parse_file return a tuple, and store the tuple in self.stats.

Then, for example, you can access what used to be called stat3 with self.stats[2].

UIButton title text color

use

Objective-C

[headingButton setTitleColor:[UIColor colorWithRed:36/255.0 green:71/255.0 blue:113/255.0 alpha:1.0] forState:UIControlStateNormal];

Swift

headingButton.setTitleColor(.black, for: .normal)

How do I edit an incorrect commit message in git ( that I've pushed )?

The message from Linus Torvalds may answer your question:

Modify/edit old commit messages

Short answer: you can not (if pushed).


extract (Linus refers to BitKeeper as BK):

Side note, just out of historical interest: in BK you could.

And if you're used to it (like I was) it was really quite practical. I would apply a patch-bomb from Andrew, notice something was wrong, and just edit it before pushing it out.

I could have done the same with git. It would have been easy enough to make just the commit message not be part of the name, and still guarantee that the history was untouched, and allow the "fix up comments later" thing.

But I didn't.

Part of it is purely "internal consistency". Git is simply a cleaner system thanks to everything being SHA1-protected, and all objects being treated the same, regardless of object type. Yeah, there are four different kinds of objects, and they are all really different, and they can't be used in the same way, but at the same time, even if their encoding might be different on disk, conceptually they all work exactly the same.

But internal consistency isn't really an excuse for being inflexible, and clearly it would be very flexible if we could just fix up mistakes after they happen. So that's not a really strong argument.

The real reason git doesn't allow you to change the commit message ends up being very simple: that way, you can trust the messages. If you allowed people to change them afterwards, the messages are inherently not very trustworthy.


To be complete, you could rewrite your local commit history in order to reflect what you want, as suggested by sykora (with some rebase and reset --hard, gasp!)

However, once you publish your revised history again (with a git push origin +master:master, the + sign forcing the push to occur, even if it doesn't result in a "fast-forward" commit)... you might get into some trouble.

Extract from this other SO question:

I actually once pushed with --force to git.git repository and got scolded by Linus BIG TIME. It will create a lot of problems for other people. A simple answer is "don't do it".

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

for anyone who comes across this problem now, with android studio 4.0+ you just have to enable java 8 as mentioned here

android {
    defaultConfig {
            ...
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Finding height in Binary Search Tree

//function to find height of BST

int height(Node* root) {
    if(root == NULL){
        return -1;
    }

    int sum=0;
    int rheight = height(root->right);
    int lheight = height(root->left);

    if(lheight>rheight){
        sum = lheight +1;
    }
    if(rheight > lheight){
        sum = rheight + 1;
    }

    return sum;
}

How does Python's super() work with multiple inheritance?

Another not yet covered point is passing parameters for initialization of classes. Since the destination of super depends on the subclass the only good way to pass parameters is packing them all together. Then be careful to not have the same parameter name with different meanings.

Example:

class A(object):
    def __init__(self, **kwargs):
        print('A.__init__')
        super().__init__()

class B(A):
    def __init__(self, **kwargs):
        print('B.__init__ {}'.format(kwargs['x']))
        super().__init__(**kwargs)


class C(A):
    def __init__(self, **kwargs):
        print('C.__init__ with {}, {}'.format(kwargs['a'], kwargs['b']))
        super().__init__(**kwargs)


class D(B, C): # MRO=D, B, C, A
    def __init__(self):
        print('D.__init__')
        super().__init__(a=1, b=2, x=3)

print(D.mro())
D()

gives:

[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
D.__init__
B.__init__ 3
C.__init__ with 1, 2
A.__init__

Calling the super class __init__ directly to more direct assignment of parameters is tempting but fails if there is any super call in a super class and/or the MRO is changed and class A may be called multiple times, depending on the implementation.

To conclude: cooperative inheritance and super and specific parameters for initialization aren't working together very well.

Android Material: Status bar color won't change

While colouring the status bar is not supported <5.0, on 4.4 you can use a work around to achieve a darker colour:

Make the status bar translucent

<item name="android:windowTranslucentStatus">true</item>

Then use AppCompat's Toolbar for your appbar, making sure that it fits system windows:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    ...
    android:fitsSystemWindows="true"/>

Make sure to set your toolbar as your activity's toolbar:

protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

The toolbar stretches underneath the status bar, and the semi translucency of the status bar makes it appear to be a darker secondary colour. If that's not the colour you want, this combination allows you to fit a view underneath your status bar sporting the background colour of your choice (though it's still tinted darker by the status bar).

Kind of an edge case workaround due to 4.4 only, but there ya go.

How to join a slice of strings into a single string?

Use a slice, not an arrray. Just create it using

reg := []string {"a","b","c"}

An alternative would have been to convert your array to a slice when joining :

fmt.Println(strings.Join(reg[:],","))

Read the Go blog about the differences between slices and arrays.

Assert that a WebElement is not present using Selenium WebDriver with java

It's easier to do this:

driver.findElements(By.linkText("myLinkText")).size() < 1

How to access a dictionary key value present inside a list?

If you know which dict in the list has the key you're looking for, then you already have the solution (as presented by Matt and Ignacio). However, if you don't know which dict has this key, then you could do this:

def getValueOf(k, L):
    for d in L:
        if k in d:
            return d[k]

How to remove \n from a list element?

from this link:

you can use rstrip() method. Example

mystring = "hello\n"    
print(mystring.rstrip('\n'))

Keeping ASP.NET Session Open / Alive

Whenever you make a request to the server the session timeout resets. So you can just make an ajax call to an empty HTTP handler on the server, but make sure the handler's cache is disabled, otherwise the browser will cache your handler and won't make a new request.

KeepSessionAlive.ashx.cs

public class KeepSessionAlive : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            context.Response.Cache.SetNoStore();
            context.Response.Cache.SetNoServerCaching();
        }
    }

.JS:

window.onload = function () {
        setInterval("KeepSessionAlive()", 60000)
}

 function KeepSessionAlive() {
 url = "/KeepSessionAlive.ashx?";
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", url, true);
        xmlHttp.send();
        }

@veggerby - There is no need for the overhead of storing variables in the session. Just preforming a request to the server is enough.

AngularJS: Service vs provider vs factory

Using as reference this page and the documentation (which seems to have greatly improved since the last time I looked), I put together the following real(-ish) world demo which uses 4 of the 5 flavours of provider; Value, Constant, Factory and full blown Provider.

HTML:

<div ng-controller="mainCtrl as main">
    <h1>{{main.title}}*</h1>
    <h2>{{main.strapline}}</h2>
    <p>Earn {{main.earn}} per click</p>
    <p>You've earned {{main.earned}} by clicking!</p>
    <button ng-click="main.handleClick()">Click me to earn</button>
    <small>* Not actual money</small>
</div>

app

var app = angular.module('angularProviders', []);

// A CONSTANT is not going to change
app.constant('range', 100);

// A VALUE could change, but probably / typically doesn't
app.value('title', 'Earn money by clicking');
app.value('strapline', 'Adventures in ng Providers');

// A simple FACTORY allows us to compute a value @ runtime.
// Furthermore, it can have other dependencies injected into it such
// as our range constant.
app.factory('random', function randomFactory(range) {
    // Get a random number within the range defined in our CONSTANT
    return Math.random() * range;
});

// A PROVIDER, must return a custom type which implements the functionality 
// provided by our service (see what I did there?).
// Here we define the constructor for the custom type the PROVIDER below will 
// instantiate and return.
var Money = function(locale) {

    // Depending on locale string set during config phase, we'll
    // use different symbols and positioning for any values we 
    // need to display as currency
    this.settings = {
        uk: {
            front: true,
            currency: '£',
            thousand: ',',
            decimal: '.'
        },
        eu: {
            front: false,
            currency: '€',
            thousand: '.',
            decimal: ','
        }
    };

    this.locale = locale;
};

// Return a monetary value with currency symbol and placement, and decimal 
// and thousand delimiters according to the locale set in the config phase.
Money.prototype.convertValue = function(value) {

    var settings = this.settings[this.locale],
        decimalIndex, converted;

    converted = this.addThousandSeparator(value.toFixed(2), settings.thousand);

    decimalIndex = converted.length - 3;

    converted = converted.substr(0, decimalIndex) +
        settings.decimal +
        converted.substr(decimalIndex + 1);    

    converted = settings.front ?
            settings.currency + converted : 
            converted + settings.currency; 

    return converted;   
};

// Add supplied thousand separator to supplied value
Money.prototype.addThousandSeparator = function(value, symbol) {
   return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, symbol);
};

// PROVIDER is the core recipe type - VALUE, CONSTANT, SERVICE & FACTORY
// are all effectively syntactic sugar built on top of the PROVIDER construct
// One of the advantages of the PROVIDER is that we can configure it before the
// application starts (see config below).
app.provider('money', function MoneyProvider() {

    var locale;

    // Function called by the config to set up the provider
    this.setLocale = function(value) {
        locale = value;   
    };

    // All providers need to implement a $get method which returns
    // an instance of the custom class which constitutes the service
    this.$get = function moneyFactory() {
        return new Money(locale);
    };
});

// We can configure a PROVIDER on application initialisation.
app.config(['moneyProvider', function(moneyProvider) {
    moneyProvider.setLocale('uk');
    //moneyProvider.setLocale('eu'); 
}]);

// The ubiquitous controller
app.controller('mainCtrl', function($scope, title, strapline, random, money) {

    // Plain old VALUE(s)
    this.title = title;
    this.strapline = strapline;

    this.count = 0;

    // Compute values using our money provider    
    this.earn = money.convertValue(random); // random is computed @ runtime
    this.earned = money.convertValue(0);

    this.handleClick = function() { 
        this.count ++;
        this.earned = money.convertValue(random * this.count);
    };
});

Working demo.

Is there a way to cast float as a decimal without rounding and preserving its precision?

Have you tried:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

UPDATE:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

You may be able to use this in your conversion process...

How to recompile with -fPIC

Before compiling make sure that "rules.mk" file is included properly in Makefile or include it explicitly by:

"source rules.mk"

Why does integer division in C# return an integer and not a float?

As a little trick to know what you are obtaining you can use var, so the compiler will tell you the type to expect:

int a = 1;
int b = 2;
var result = a/b;

your compiler will tell you that result would be of type int here.

Notepad++: Multiple words search in a file (may be in different lines)?

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to SearchFind in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (cat|town)

  • Filters = *.txt

  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

  • Search mode = Regular Expression

Show Curl POST Request Headers? Is there a way to do this?

Here is all you need:

curl_setopt($curlHandle, CURLINFO_HEADER_OUT, true); // enable tracking
... // do curl request    
$headerSent = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT ); // request headers

running php script (php function) in linux bash

Simply this should do:

php test.php

How can I declare and define multiple variables in one line using C++?

Possible approaches:

  • Initialize all local variables with zero.
  • Have an array, memset or {0} the array.
  • Make it global or static.
  • Put them in struct, and memset or have a constructor that would initialize them to zero.

Google Maps API v3 adding an InfoWindow to each marker

In My case (Using Javascript insidde Razor) This worked perfectly inside an Foreach loop

google.maps.event.addListener(marker, 'click', function() {
    marker.info.open(map, this);
});

Ajax passing data to php script

You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:

$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: { album: this.title },
    success: function(response) {
        content.html(response);
    }
});

or in its shorter form:

$.post('test.php', { album: this.title }, function() {
    content.html(response);
});

and if you wanted to use a GET request:

$.ajax({  
    type: 'GET',
    url: 'test.php', 
    data: { album: this.title },
    success: function(response) {
        content.html(response);
    }
});

or in its shorter form:

$.get('test.php', { album: this.title }, function() {
    content.html(response);
});

and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.

How can I render repeating React elements?

You can put expressions inside braces. Notice in the compiled JavaScript why a for loop would never be possible inside JSX syntax; JSX amounts to function calls and sugared function arguments. Only expressions are allowed.

(Also: Remember to add key attributes to components rendered inside loops.)

JSX + ES2015:

render() {
  return (
    <table className="MyClassName">
      <thead>
        <tr>
          {this.props.titles.map(title =>
            <th key={title}>{title}</th>
          )}
        </tr>
      </thead>
      <tbody>
        {this.props.rows.map((row, i) =>
          <tr key={i}>
            {row.map((col, j) =>
              <td key={j}>{col}</td>
            )}
          </tr>
        )}
      </tbody>
    </table>
  );
} 

JavaScript:

render: function() {
  return (
    React.DOM.table({className: "MyClassName"}, 
      React.DOM.thead(null, 
        React.DOM.tr(null, 
          this.props.titles.map(function(title) {
            return React.DOM.th({key: title}, title);
          })
        )
      ), 
      React.DOM.tbody(null, 
        this.props.rows.map(function(row, i) {
          return (
            React.DOM.tr({key: i}, 
              row.map(function(col, j) {
                return React.DOM.td({key: j}, col);
              })
            )
          );
        })
      )
    )
  );
} 

How to add an Android Studio project to GitHub

You need to create the project on GitHub first. After that go to the project directory and run in terminal:

git init
git remote add origin https://github.com/xxx/yyy.git
git add .
git commit -m "first commit"
git push -u origin master

Do checkbox inputs only post data if they're checked?

I resolved the problem with this code:

HTML Form

<input type="checkbox" id="is-business" name="is-business" value="off" onclick="changeValueCheckbox(this)" >
<label for="is-business">Soy empresa</label>

and the javascript function by change the checkbox value form:

//change value of checkbox element
function changeValueCheckbox(element){
   if(element.checked){
    element.value='on';
  }else{
    element.value='off';
  }
}

and the server checked if the data post is "on" or "off". I used playframework java

        final Map<String, String[]> data = request().body().asFormUrlEncoded();

        if (data.get("is-business")[0].equals('on')) {
            login.setType(new MasterValue(Login.BUSINESS_TYPE));
        } else {
            login.setType(new MasterValue(Login.USER_TYPE));
        }

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

SQL> sqlplus "/ as sysdba"

SQL> startup

  Oracle instance started
  ------
  Database mounted.
  Database opened.

SQL> Quit

I also got same problem.I tried above mentioned steps and then it worked for me.You can try.

What is the difference between XAMPP or WAMP Server & IIS?

In addition to the above, WAMP supports 64 bit PHP on Windows systems while XAMPP only offers 32 bit versions. This actually made me switch to WAMP on my Windows machine since you need 64 bit PHP 7 to get bigint numbers correctly from MySQL

SQL - How to select a row having a column with max value

In Oracle DB:

create table temp_test1 (id number, value number, description varchar2(20));

insert into temp_test1 values(1, 22, 'qq');
insert into temp_test1 values(2, 22, 'qq');
insert into temp_test1 values(3, 22, 'qq');
insert into temp_test1 values(4, 23, 'qq1');
insert into temp_test1 values(5, 23, 'qq1');
insert into temp_test1 values(6, 23, 'qq1');

SELECT MAX(id), value, description FROM temp_test1 GROUP BY value, description;

Result:
    MAX(ID) VALUE DESCRIPTION
    -------------------------
    6         23    qq1
    3         22    qq

How to convert 'binary string' to normal string in Python3?

If the answer from falsetru didn't work you could also try:

>>> b'a string'.decode('utf-8')
'a string'

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

I'm not sure how to erase through the command line, but it's fairly easily to do it through the Keychain Access app. Just go to Applications -> Utilties -> Keychain Access, then enter "github.com". You can either delete the invalid item or update the password from with the app.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

To add slightly to the other answers, if you actually want to catch SIGTERM (the default signal sent by the kill command), you can use syscall.SIGTERM in place of os.Interrupt. Beware that the syscall interface is system-specific and might not work everywhere (e.g. on windows). But it works nicely to catch both:

c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
....

SQL "IF", "BEGIN", "END", "END IF"?

Based on your description of what you want to do, the code seems to be correct as it is. ENDIF isn't a valid SQL loop control keyword. Are you sure that the INSERTS are actually pulling data to put into @Classes? In fact, if it was bad it just wouldn't run.

What you might want to try is to put a few PRINT statements in there. Put a PRINT above each of the INSERTS just outputting some silly text to show that that line is executing. If you get both outputs, then your SELECT...INSERT... is suspect. You could also just do the SELECT in place of the PRINT (that is, without the INSERT) and see exactly what data is being pulled.

Where is database .bak file saved from SQL Server Management Studio?

You may want to take a look here, this tool saves a BAK file from a remote SQL Server to your local harddrive: FIDA BAK to local

Get exit code of a background process

Our team had the same need with a remote SSH-executed script which was timing out after 25 minutes of inactivity. Here is a solution with the monitoring loop checking the background process every second, but printing only every 10 minutes to suppress an inactivity timeout.

long_running.sh & 
pid=$!

# Wait on a background job completion. Query status every 10 minutes.
declare -i elapsed=0
# `ps -p ${pid}` works on macOS and CentOS. On both OSes `ps ${pid}` works as well.
while ps -p ${pid} >/dev/null; do
  sleep 1
  if ((++elapsed % 600 == 0)); then
    echo "Waiting for the completion of the main script. $((elapsed / 60))m and counting ..."
  fi
done

# Return the exit code of the terminated background process. This works in Bash 4.4 despite what Bash docs say:
# "If neither jobspec nor pid specifies an active child process of the shell, the return status is 127."
wait ${pid}

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

how to add a jpg image in Latex

You need to use a graphics library. Put this in your preamble:

\usepackage{graphicx}

You can then add images like this:

\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}

This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

And here we see figure \ref{overflow}.

Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions

Encoding Error in Panda read_csv

Try calling read_csv with encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' (these are some of the various encodings found on Windows).

Convert UTC to local time in Rails 3

It is easy to configure it using your system local zone, Just in your application.rb add this

config.time_zone = Time.now.zone

Then, rails should show you timestamps in your localtime or you can use something like this instruction to get the localtime

Post.created_at.localtime

Calling UserForm_Initialize() in a Module

From a module:

UserFormName.UserForm_Initialize

Just make sure that in your userform, you update the sub like so:

Public Sub UserForm_Initialize() so it can be called from outside the form.

Alternately, if the Userform hasn't been loaded:

UserFormName.Show will end up calling UserForm_Initialize because it loads the form.

Finding rows that don't contain numeric data in Oracle

I was thinking you could use a regexp_like condition and use the regular expression to find any non-numerics. I hope this might help?!

SELECT * FROM table_with_column_to_search WHERE REGEXP_LIKE(varchar_col_with_non_numerics, '[^0-9]+');

Best way to replace multiple characters in a string?

Late to the party, but I lost a lot of time with this issue until I found my answer.

Short and sweet, translate is superior to replace. If you're more interested in funcionality over time optimization, do not use replace.

Also use translate if you don't know if the set of characters to be replaced overlaps the set of characters used to replace.

Case in point:

Using replace you would naively expect the snippet "1234".replace("1", "2").replace("2", "3").replace("3", "4") to return "2344", but it will return in fact "4444".

Translation seems to perform what OP originally desired.

Capitalize the first letter of both words in a two word string

You could also use the snakecase package:

install.packages("snakecase")
library(snakecase)

name <- c("zip code", "state", "final count")
to_title_case(name)
#> [1] "Zip Code"    "State"       "Final Count"

# or 
to_upper_camel_case(name, sep_out = " ")
#> [1] "Zip Code"    "State"       "Final Count"

https://github.com/Tazinho/snakecase

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

Some solutions didn't work for me but the best option I found was the example below when i decided to use the flex option.

_x000D_
_x000D_
html, body{
    height: 100%;   
}

body{
    display: flex;
    flex-direction: column;
}

.main-contents{ 
    flex: 1 0 auto;
    min-height: 100%;
    margin-bottom: -77px;
  background-color: #CCC;
}

.footer{
    height:  77px;
    min-height: 77px;
    width: 100%;
    bottom: 0;
    left: 0;
    background: #000000;
    flex-shrink: 0;
    flex-direction: row;
    position: relative;
    
    
}

.footer-text{
  color: #FFF;
}

@media screen and (max-width: 767px){
    #content{
        padding-bottom: 0;
    }
    .footer{
        position: relative;
        /*position: absolute;*/
        height: 77px;
        width: 100%;
        bottom: 0;
        left: 0;
    }

}
_x000D_
<html>
  <body>
    <div class="main-contents" >
      this is the main content
    </div>
  </body>

  <footer class="footer">
    <p class="footer-text">This is the sticky footer</p>
  </footer>

</html>
_x000D_
_x000D_
_x000D_

Setting session variable using javascript

It is very important to understand both sessionStorage and localStorage as they both have different uses:

From MDN:

All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again.

sessionStorage - Saves data until the browser is closed, the data is deleted when the tab/browser is closed.

localStorage - Saves data "forever" even after the browser is closed BUT you shouldn't count on the data you store to be there later, the data might get deleted by the browser at any time because of pretty much anything, or deleted by the user, best practice would be to validate that the data is there first, and continue the rest if it is there. (or set it up again if its not there)

To understand more, read here: localStorage | sessionStorage

Difference between "or" and || in Ruby?

It's a matter of operator precedence.

|| has a higher precedence than or.

So, in between the two you have other operators including ternary (? :) and assignment (=) so which one you choose can affect the outcome of statements.

Here's a ruby operator precedence table.

See this question for another example using and/&&.

Also, be aware of some nasty things that could happen:

a = false || true  #=> true
a  #=> true

a = false or true  #=> true
a  #=> false

Both of the previous two statements evaluate to true, but the second sets a to false since = precedence is lower than || but higher than or.

how to split the ng-repeat data with three columns using bootstrap

The most reliable and technically correct approach is to transform the data in the controller. Here's a simple chunk function and usage.

function chunk(arr, size) {
  var newArr = [];
  for (var i=0; i<arr.length; i+=size) {
    newArr.push(arr.slice(i, i+size));
  }
  return newArr;
}

$scope.chunkedData = chunk(myData, 3);

Then your view would look like this:

<div class="row" ng-repeat="rows in chunkedData">
  <div class="span4" ng-repeat="item in rows">{{item}}</div>
</div>

If you have any inputs within the ng-repeat, you will probably want to unchunk/rejoin the arrays as the data is modified or on submission. Here's how this would look in a $watch, so that the data is always available in the original, merged format:

$scope.$watch('chunkedData', function(val) {
  $scope.data = [].concat.apply([], val);
}, true); // deep watch

Many people prefer to accomplish this in the view with a filter. This is possible, but should only be used for display purposes! If you add inputs within this filtered view, it will cause problems that can be solved, but are not pretty or reliable.

The problem with this filter is that it returns new nested arrays each time. Angular is watching the return value from the filter. The first time the filter runs, Angular knows the value, then runs it again to ensure it is done changing. If both values are the same, the cycle is ended. If not, the filter will fire again and again until they are the same, or Angular realizes an infinite digest loop is occurring and shuts down. Because new nested arrays/objects were not previously tracked by Angular, it always sees the return value as different from the previous. To fix these "unstable" filters, you must wrap the filter in a memoize function. lodash has a memoize function and the latest version of lodash also includes a chunk function, so we can create this filter very simply using npm modules and compiling the script with browserify or webpack.

Remember: display only! Filter in the controller if you're using inputs!

Install lodash:

npm install lodash-node

Create the filter:

var chunk = require('lodash-node/modern/array/chunk');
var memoize = require('lodash-node/modern/function/memoize');

angular.module('myModule', [])
.filter('chunk', function() {
  return memoize(chunk);
});

And here's a sample with this filter:

<div ng-repeat="row in ['a','b','c','d','e','f'] | chunk:3">
  <div class="column" ng-repeat="item in row">
    {{($parent.$index*row.length)+$index+1}}. {{item}}
  </div>
</div>

Order items vertically

1  4
2  5
3  6

Regarding vertical columns (list top to bottom) rather than horizontal (left to right), the exact implementation depends on the desired semantics. Lists that divide up unevenly can be distributed different ways. Here's one way:

<div ng-repeat="row in columns">
  <div class="column" ng-repeat="item in row">
    {{item}}
  </div>
</div>
var data = ['a','b','c','d','e','f','g'];
$scope.columns = columnize(data, 3);
function columnize(input, cols) {
  var arr = [];
  for(i = 0; i < input.length; i++) {
    var colIdx = i % cols;
    arr[colIdx] = arr[colIdx] || [];
    arr[colIdx].push(input[i]);
  }
  return arr;
}

However, the most direct and just plainly simple way to get columns is to use CSS columns:

.columns {
  columns: 3;
}
<div class="columns">
  <div ng-repeat="item in ['a','b','c','d','e','f','g']">
    {{item}}
  </div>
</div>

How should I do integer division in Perl?

Hope it works

int(9/4) = 2.

Thanks Manojkumar

Redirection of standard and error output appending to the same log file

Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.

$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)

Check if a class `active` exist on element with jquery

If Condition to check, currently class active or not

$('#next').click(function(){
    if($('p:last').hasClass('active'){
       $('.active').removeClass();
    }else{
       $('.active').addClass();
    }
});

How to get all files under a specific directory in MATLAB?

I used the code mentioned in this great answer and expanded it to support 2 additional parameters which I needed in my case. The parameters are file extensions to filter on and a flag indicating whether to concatenate the full path to the name of the file or not.

I hope it is clear enough and someone will finds it beneficial.

function fileList = getAllFiles(dirName, fileExtension, appendFullPath)

  dirData = dir([dirName '/' fileExtension]);      %# Get the data for the current directory
  dirWithSubFolders = dir(dirName);
  dirIndex = [dirWithSubFolders.isdir];  %# Find the index for directories
  fileList = {dirData.name}';  %'# Get a list of the files
  if ~isempty(fileList)
    if appendFullPath
      fileList = cellfun(@(x) fullfile(dirName,x),...  %# Prepend path to files
                       fileList,'UniformOutput',false);
    end
  end
  subDirs = {dirWithSubFolders(dirIndex).name};  %# Get a list of the subdirectories
  validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
                                               %#   that are not '.' or '..'
  for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dirName,subDirs{iDir});    %# Get the subdirectory path
    fileList = [fileList; getAllFiles(nextDir, fileExtension, appendFullPath)];  %# Recursively call getAllFiles
  end

end

Example for running the code:

fileList = getAllFiles(dirName, '*.xml', 0); %#0 is false obviously

Why does the 260 character path length limit exist in Windows?

You can mount a folder as a drive. From the command line, if you have a path C:\path\to\long\folder you can map it to drive letter X: using:

subst x: \path\to\long\folder

What is the difference between public, protected, package-private and private in Java?

It's actually a bit more complicated than a simple grid shows. The grid tells you whether an access is allowed, but what exactly constitutes an access? Also, access levels interact with nested classes and inheritance in complex ways.

The "default" access (specified by the absence of a keyword) is also called package-private. Exception: in an interface, no modifier means public access; modifiers other than public are forbidden. Enum constants are always public.

Summary

Is an access to a member with this access specifier allowed?

  • Member is private: Only if member is defined within the same class as calling code.
  • Member is package private: Only if the calling code is within the member's immediately enclosing package.
  • Member is protected: Same package, or if member is defined in a superclass of the class containing the calling code.
  • Member is public: Yes.

What access specifiers apply to

Local variables and formal parameters cannot take access specifiers. Since they are inherently inaccessible to the outside according to scoping rules, they are effectively private.

For classes in the top scope, only public and package-private are permitted. This design choice is presumably because protected and private would be redundant at the package level (there is no inheritance of packages).

All the access specifiers are possible on class members (constructors, methods and static member functions, nested classes).

Related: Java Class Accessibility

Order

The access specifiers can be strictly ordered

public > protected > package-private > private

meaning that public provides the most access, private the least. Any reference possible on a private member is also valid for a package-private member; any reference to a package-private member is valid on a protected member, and so on. (Giving access to protected members to other classes in the same package was considered a mistake.)

Notes

  • A class's methods are allowed to access private members of other objects of the same class. More precisely, a method of class C can access private members of C on objects of any subclass of C. Java doesn't support restricting access by instance, only by class. (Compare with Scala, which does support it using private[this].)
  • You need access to a constructor to construct an object. Thus if all constructors are private, the class can only be constructed by code living within the class (typically static factory methods or static variable initializers). Similarly for package-private or protected constructors.
    • Only having private constructors also means that the class cannot be subclassed externally, since Java requires a subclass's constructors to implicitly or explicitly call a superclass constructor. (It can, however, contain a nested class that subclasses it.)

Inner classes

You also have to consider nested scopes, such as inner classes. An example of the complexity is that inner classes have members, which themselves can take access modifiers. So you can have a private inner class with a public member; can the member be accessed? (See below.) The general rule is to look at scope and think recursively to see whether you can access each level.

However, this is quite complicated, and for full details, consult the Java Language Specification. (Yes, there have been compiler bugs in the past.)

For a taste of how these interact, consider this example. It is possible to "leak" private inner classes; this is usually a warning:

class Test {
    public static void main(final String ... args) {
        System.out.println(Example.leakPrivateClass()); // OK
        Example.leakPrivateClass().secretMethod(); // error
    }
}

class Example {
    private static class NestedClass {
        public void secretMethod() {
            System.out.println("Hello");
        }
    }
    public static NestedClass leakPrivateClass() {
        return new NestedClass();
    }
}

Compiler output:

Test.java:4: secretMethod() in Example.NestedClass is defined in an inaccessible class or interface
        Example.leakPrivateClass().secretMethod(); // error
                                  ^
1 error

Some related questions:

Postgresql, update if row with some unique value exists, else insert

I found this post more relevant in this scenario:

WITH upsert AS (
     UPDATE spider_count SET tally=tally+1 
     WHERE date='today' AND spider='Googlebot' 
     RETURNING *
)
INSERT INTO spider_count (spider, tally) 
SELECT 'Googlebot', 1 
WHERE NOT EXISTS (SELECT * FROM upsert)

Download and open PDF file using Ajax

This snippet is for angular js users which will face the same problem, Note that the response file is downloaded using a programmed click event. In this case , the headers were sent by server containing filename and content/type.

$http({
    method: 'POST', 
    url: 'DownloadAttachment_URL',
    data: { 'fileRef': 'filename.pdf' }, //I'm sending filename as a param
    headers: { 'Authorization': $localStorage.jwt === undefined ? jwt : $localStorage.jwt },
    responseType: 'arraybuffer',
}).success(function (data, status, headers, config) {
    headers = headers();
    var filename = headers['x-filename'];
    var contentType = headers['content-type'];
    var linkElement = document.createElement('a');
    try {
        var blob = new Blob([data], { type: contentType });
        var url = window.URL.createObjectURL(blob);

        linkElement.setAttribute('href', url);
        linkElement.setAttribute("download", filename);

        var clickEvent = new MouseEvent("click", {
            "view": window,
            "bubbles": true,
            "cancelable": false
        });
        linkElement.dispatchEvent(clickEvent);
    } catch (ex) {
        console.log(ex);
    }
}).error(function (data, status, headers, config) {
}).finally(function () {

});

How to view the committed files you have not pushed yet?

The push command has a -n/--dry-run option which will compute what needs to be pushed but not actually do it. Does that work for you?

Oracle Error ORA-06512

ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).

In a comment you said

"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"

Well, your code does this:

IF ((pNum < 12) OR (pNum > 14)) THEN     
    RAISE vSOME_EX;

That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?

ORA-06510: PL/SQL: unhandled user-defined exception

If so, all you need to do is add an exception block to handle the error. Perhaps:

PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
    vSOME_EX EXCEPTION;

BEGIN 
    IF ((pNum < 12) OR (pNum > 14)) THEN     
        RAISE vSOME_EX;
    ELSE  
        EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
    END IF;
exception
    when vsome_ex then
         raise_application_error(-20000
                                 , 'This is not a valid table:  M'||pNum||'GR');

END PX;

The documentation covers handling PL/SQL exceptions in depth.

If input value is blank, assign a value of "empty" with Javascript

This can be done using HTML5's placeHolder or using JavaScript. Checkout this post.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

make sure the bind address configuration option in the my.cnf file in /etc/ is the same with localhost or virtual serve ip address. plus check to make sure that the directory for creating the socket file is well specified.

In Android, how do I set margins in dp programmatically?

For a quick one-line setup use

((LayoutParams) cvHolder.getLayoutParams()).setMargins(0, 0, 0, 0);

but be carfull for any wrong use to LayoutParams, as this will have no if statment instance chech

How do I get class name in PHP?

I think it's important to mention little difference between 'self' and 'static' in PHP as 'best answer' uses 'static' which can give confusing result to some people.

<?php
class X {
    function getStatic() {
        // gets THIS class of instance of object
        // that extends class in which is definied function
        return static::class;
    }
    function getSelf() {
        // gets THIS class of class in which function is declared
        return self::class;
    }
}

class Y extends X {
}
class Z extends Y {
}

$x = new X();
$y = new Y();
$z = new Z();

echo 'X:' . $x->getStatic() . ', ' . $x->getSelf() . 
    ', Y: ' . $y->getStatic() . ', ' . $y->getSelf() . 
    ', Z: ' . $z->getStatic() . ', ' . $z->getSelf();

Results:

X: X, X
Y: Y, X
Z: Z, X

Are there any disadvantages to always using nvarchar(MAX)?

The main disadvantage I can see is that let's say you have this:

Which one gives you the most information about the data needed for the UI?

This

            CREATE TABLE [dbo].[BusData](
                [ID] [int] IDENTITY(1,1) NOT NULL,
                [RecordId] [nvarchar](MAX) NULL,
                [CompanyName] [nvarchar](MAX) NOT NULL,
                [FirstName] [nvarchar](MAX) NOT NULL,
                [LastName] [nvarchar](MAX) NOT NULL,
                [ADDRESS] [nvarchar](MAX) NOT NULL,
                [CITY] [nvarchar](MAX) NOT NULL,
                [County] [nvarchar](MAX) NOT NULL,
                [STATE] [nvarchar](MAX) NOT NULL,
                [ZIP] [nvarchar](MAX) NOT NULL,
                [PHONE] [nvarchar](MAX) NOT NULL,
                [COUNTRY] [nvarchar](MAX) NOT NULL,
                [NPA] [nvarchar](MAX) NULL,
                [NXX] [nvarchar](MAX) NULL,
                [XXXX] [nvarchar](MAX) NULL,
                [CurrentRecord] [nvarchar](MAX) NULL,
                [TotalCount] [nvarchar](MAX) NULL,
                [Status] [int] NOT NULL,
                [ChangeDate] [datetime] NOT NULL
            ) ON [PRIMARY]

Or This?

            CREATE TABLE [dbo].[BusData](
                [ID] [int] IDENTITY(1,1) NOT NULL,
                [RecordId] [nvarchar](50) NULL,
                [CompanyName] [nvarchar](50) NOT NULL,
                [FirstName] [nvarchar](50) NOT NULL,
                [LastName] [nvarchar](50) NOT NULL,
                [ADDRESS] [nvarchar](50) NOT NULL,
                [CITY] [nvarchar](50) NOT NULL,
                [County] [nvarchar](50) NOT NULL,
                [STATE] [nvarchar](2) NOT NULL,
                [ZIP] [nvarchar](16) NOT NULL,
                [PHONE] [nvarchar](18) NOT NULL,
                [COUNTRY] [nvarchar](50) NOT NULL,
                [NPA] [nvarchar](3) NULL,
                [NXX] [nvarchar](3) NULL,
                [XXXX] [nvarchar](4) NULL,
                [CurrentRecord] [nvarchar](50) NULL,
                [TotalCount] [nvarchar](50) NULL,
                [Status] [int] NOT NULL,
                [ChangeDate] [datetime] NOT NULL
            ) ON [PRIMARY]

database vs. flat files

Difference between database and flat files are given below:

  • Database provide more flexibility whereas flat file provide less flexibility.

  • Database system provide data consistency whereas flat file can not provide data consistency.

  • Database is more secure over flat files.
  • Database support DML and DDL whereas flat files can not support these.

  • Less data redundancy in database whereas more data redundancy in flat files.

Python socket receive - incoming packets always have a different size

You could try always sending the first 4 bytes of your data as data size and then read complete data in one shot. Use the below functions on both client and server-side to send and receive data.

def send_data(conn, data):
    serialized_data = pickle.dumps(data)
    conn.sendall(struct.pack('>I', len(serialized_data)))
    conn.sendall(serialized_data)


def receive_data(conn):
    data_size = struct.unpack('>I', conn.recv(4))[0]
    received_payload = b""
    reamining_payload_size = data_size
    while reamining_payload_size != 0:
        received_payload += conn.recv(reamining_payload_size)
        reamining_payload_size = data_size - len(received_payload)
    data = pickle.loads(received_payload)

    return data

you could find sample program at https://github.com/vijendra1125/Python-Socket-Programming.git

Fastest way to count number of occurrences in a Python list

By the use of Counter dictionary counting the occurrences of all element as well as most common element in python list with its occurrence value in most efficient way.

If our python list is:-

l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']

To find occurrence of every items in the python list use following:-

\>>from collections import Counter

\>>c=Counter(l)

\>>print c

Counter({'1': 6, '2': 4, '7': 3, '10': 2})

To find most/highest occurrence of items in the python list:-

\>>k=c.most_common()

\>>k

[('1', 6), ('2', 4), ('7', 3), ('10', 2)]

For Highest one:-

\>>k[0][1]

6

For the item just use k[0][0]

\>>k[0][0]

'1'

For nth highest item and its no of occurrence in the list use follow:-

**for n=2 **

\>>print k[n-1][0] # For item

2

\>>print k[n-1][1] # For value

4

Virtual Serial Port for Linux

There is also tty0tty http://sourceforge.net/projects/tty0tty/ which is a real null modem emulator for linux.

It is a simple kernel module - a small source file. I don't know why it only got thumbs down on sourceforge, but it works well for me. The best thing about it is that is also emulates the hardware pins (RTC/CTS DSR/DTR). It even implements TIOCMGET/TIOCMSET and TIOCMIWAIT iotcl commands!

On a recent kernel you may get compilation errors. This is easy to fix. Just insert a few lines at the top of the module/tty0tty.c source (after the includes):

#ifndef init_MUTEX
#define init_MUTEX(x) sema_init((x),1)
#endif

When the module is loaded, it creates 4 pairs of serial ports. The devices are /dev/tnt0 to /dev/tnt7 where tnt0 is connected to tnt1, tnt2 is connected to tnt3, etc. You may need to fix the file permissions to be able to use the devices.

edit:

I guess I was a little quick with my enthusiasm. While the driver looks promising, it seems unstable. I don't know for sure but I think it crashed a machine in the office I was working on from home. I can't check until I'm back in the office on monday.

The second thing is that TIOCMIWAIT does not work. The code seems to be copied from some "tiny tty" example code. The handling of TIOCMIWAIT seems in place, but it never wakes up because the corresponding call to wake_up_interruptible() is missing.

edit:

The crash in the office really was the driver's fault. There was an initialization missing, and the completely untested TIOCMIWAIT code caused a crash of the machine.

I spent yesterday and today rewriting the driver. There were a lot of issues, but now it works well for me. There's still code missing for hardware flow control managed by the driver, but I don't need it because I'll be managing the pins myself using TIOCMGET/TIOCMSET/TIOCMIWAIT from user mode code.

If anyone is interested in my version of the code, send me a message and I'll send it to you.

Image scaling causes poor quality in firefox/internet explorer but not chrome

Seems Chrome downscaling is best but the real question is why use such a massive image on the web if you use show is so massively scaled down? Downloadtimes as seen on the test page above are terrible. Especially for responsive websites a certain amount of scaling makes sense, actually more a scale up than scale down though. But never in such a (sorry pun) scale.

Seems this is more a theoretical problem which Chrome seems to deal with nicely but actually should not happen and actually should not be used in practice IMHO.

How to run VBScript from command line without Cscript/Wscript

When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by

assoc | grep -i vbs
.vbs=VBSFile

ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*

to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.

As

cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]

Options:
 //B         Batch mode: Suppresses script errors and prompts from displaying
 //D         Enable Active Debugging
 //E:engine  Use engine for executing script
 //H:CScript Changes the default script host to CScript.exe
 //H:WScript Changes the default script host to WScript.exe (default)
 //I         Interactive mode (default, opposite of //B)
 //Job:xxxx  Execute a WSF job
 //Logo      Display logo (default)
 //Nologo    Prevent logo display: No banner will be shown at execution time
 //S         Save current command line options for this user
 //T:nn      Time out in seconds:  Maximum time a script is permitted to run
 //X         Execute script in debugger
 //U         Use Unicode for redirected I/O from the console

shows, you can use //E and //S to permanently switch your default host to cscript.exe.

If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable

set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1

contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.

Update wrt comment:

If you 'don't want to specify the full path of my vbscript everytime' you may:

  1. put your CONVERTER.VBS in a folder that is included in the PATH environment variable; the shell will then search all pathes - if necessary taking the PATHEXT and the ftype/assoc info into account - for a matching 'executable'.
  2. put a CONVERTER.BAT/.CMD into a path directory that contains a line like cscript p:\ath\to\CONVERTER.VBS

In both cases I would type out the extension to avoid (nasty) surprises.

Drawing in Java using Canvas

Suggestions:

  • Don't use Canvas as you shouldn't mix AWT with Swing components unnecessarily.
  • Instead use a JPanel or JComponent.
  • Don't get your Graphics object by calling getGraphics() on a component as the Graphics object obtained will be transient.
  • Draw in the JPanel's paintComponent() method.
  • All this is well explained in several tutorials that are easily found. Why not read them first before trying to guess at this stuff?

Key tutorial links:

Modifying local variable from inside lambda

This is fairly close to an XY problem. That is, the question being asked is essentially how to mutate a captured local variable from a lambda. But the actual task at hand is how to number the elements of a list.

In my experience, upward of 80% of the time there is a question of how to mutate a captured local from within a lambda, there's a better way to proceed. Usually this involves reduction, but in this case the technique of running a stream over the list indexes applies well:

IntStream.range(0, list.size())
         .forEach(i -> list.get(i).setOrdinal(i));

Counting the number of files in a directory using Java

If you have directories containing really (>100'000) many files, here is a (non-portable) way to go:

String directoryPath = "a path";

// -f flag is important, because this way ls does not sort it output,
// which is way faster
String[] params = { "/bin/sh", "-c",
    "ls -f " + directoryPath + " | wc -l" };
Process process = Runtime.getRuntime().exec(params);
BufferedReader reader = new BufferedReader(new InputStreamReader(
    process.getInputStream()));
String fileCount = reader.readLine().trim() - 2; // accounting for .. and .
reader.close();
System.out.println(fileCount);

Node.js project naming conventions for files & folders

There are no conventions. There are some logical structure.

The only one thing that I can say: Never use camelCase file and directory names. Why? It works but on Mac and Windows there are no different between someAction and some action. I met this problem, and not once. I require'd a file like this:

var isHidden = require('./lib/isHidden');

But sadly I created a file with full of lowercase: lib/ishidden.js. It worked for me on mac. It worked fine on mac of my co-worker. Tests run without errors. After deploy we got a huge error:

Error: Cannot find module './lib/isHidden'

Oh yeah. It's a linux box. So camelCase directory structure could be dangerous. It's enough for a colleague who is developing on Windows or Mac.

So use underscore (_) or dash (-) separator if you need.

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

I resolved this by adding following code to the HTML page, since we are using the third party API which is not controlled by us.

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> 

Hope this would help, and for a record as well.

Find duplicate records in MySQL

Another solution would be to use table aliases, like so:

SELECT p1.id, p2.id, p1.address
FROM list AS p1, list AS p2
WHERE p1.address = p2.address
AND p1.id != p2.id

All you're really doing in this case is taking the original list table, creating two pretend tables -- p1 and p2 -- out of that, and then performing a join on the address column (line 3). The 4th line makes sure that the same record doesn't show up multiple times in your set of results ("duplicate duplicates").

How does one extract each folder name from a path?

Maybe call Directory.GetParent in a loop? That's if you want the full path to each directory and not just the directory names.

Delete all rows in a table based on another table

PostgreSQL implementation would be:

DELETE FROM t1
USING t2
WHERE t1.id = t2.id;

LINQ orderby on date field in descending order

env.OrderByDescending(x => x.ReportDate)

How to extract the n-th elements from a list of tuples?

n = 1 # N. . .
[x[n] for x in elements]

What is the syntax of the enhanced for loop in Java?

An enhanced for loop is just limiting the number of parameters inside the parenthesis.

for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}

Can be written as:

for (int myValue : myArray) {
    System.out.println(myValue);
}

PHP AES encrypt / decrypt

These are compact methods to encrypt / decrypt strings with PHP using AES256 CBC:

function encryptString($plaintext, $password, $encoding = null) {
    $iv = openssl_random_pseudo_bytes(16);
    $ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
    return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}

function decryptString($ciphertext, $password, $encoding = null) {
    $ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
    if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
    return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}

Usage:

$enc = encryptString("mysecretText", "myPassword");
$dec = decryptString($enc, "myPassword");

Disable native datepicker in Google Chrome

I agree with Robertc, the best way is not to use type=date but my JQuery Mobile Datepicker plugin uses it. So I have to make some changes:

I'm using jquery.ui.datepicker.mobile.js and made this changes:

From (line 51)

$( "input[type='date'], input:jqmData(type='date')" ).each(function(){

to

$( "input[plug='date'], input:jqmData(plug='date')" ).each(function(){

and in the form use, type text and add the var plug:

<input type="text" plug="date" name="date" id="date" value="">

How can I convert String to Int?

Try this:

int x = Int32.Parse(TextBoxD1.Text);

or better yet:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

Also, since Int32.TryParse returns a bool you can use its return value to make decisions about the results of the parsing attempt:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

If you are curious, the difference between Parse and TryParse is best summed up like this:

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed. - MSDN

Forward declaring an enum in C++

Seems it can not be forward-declared in GCC!

Interesting discussion here

Truncate number to two decimal places without rounding

I fixed using following simple way-

var num = 15.7784514;
Math.floor(num*100)/100;

Results will be 15.77

Convert datetime to Unix timestamp and convert it back in python

This class will cover your needs, you can pass the variable into ConvertUnixToDatetime & call which function you want it to operate based off.

from datetime import datetime
import time

class ConvertUnixToDatetime:
    def __init__(self, date):
        self.date = date

    # Convert unix to date object
    def convert_unix(self):
        unix = self.date

        # Check if unix is a string or int & proceeds with correct conversion
        if type(unix).__name__ == 'str':
            unix = int(unix[0:10])
        else:
            unix = int(str(unix)[0:10])

        date = datetime.utcfromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S')

        return date

    # Convert date to unix object
    def convert_date(self):
        date = self.date

        # Check if datetime object or raise ValueError
        if type(date).__name__ == 'datetime':
            unixtime = int(time.mktime(date.timetuple()))
        else:
            raise ValueError('You are trying to pass a None Datetime object')
        return type(unixtime).__name__, unixtime


if __name__ == '__main__':

    # Test Date
    date_test = ConvertUnixToDatetime(datetime.today())
    date_test = date_test.convert_date()
    print(date_test)

    # Test Unix
    unix_test = ConvertUnixToDatetime(date_test[1])
    print(unix_test.convert_unix())

What's the main difference between Java SE and Java EE?

Java SE stands for Java standard edition and is normally for developing desktop applications, forms the core/base API.

Java EE stands for Java enterprise edition for applications which run on servers, for example web sites.

Java ME stands for Java micro edition for applications which run on resource constrained devices (small scale devices) like cell phones, for example games.

How to add values in a variable in Unix shell scripting?

In ksh ,bash ,sh:

$ count7=0                     
$ count1=5
$ 
$ (( count7 += count1 ))
$ echo $count7
$ 5

BeanFactory vs ApplicationContext

To add onto what Miguel Ping answered, here is another section from the documentation that answers this as well:

Short version: use an ApplicationContext unless you have a really good reason for not doing so. For those of you that are looking for slightly more depth as to the 'but why' of the above recommendation, keep reading.

(posting this for any future Spring novices who might read this question)

How to convert empty spaces into null values, using SQL Server?

A case statement should do the trick when selecting from your source table:

CASE
  WHEN col1 = ' ' THEN NULL
  ELSE col1
END col1

Also, one thing to note is that your LTRIM and RTRIM reduce the value from a space (' ') to blank (''). If you need to remove white space, then the case statement should be modified appropriately:

CASE
  WHEN LTRIM(RTRIM(col1)) = '' THEN NULL
  ELSE LTRIM(RTRIM(col1))
END col1

what is right way to do API call in react js?

Render function should be pure, it's mean that it only uses state and props to render, never try to modify the state in render, this usually causes ugly bugs and decreases performance significantly. It's also a good point if you separate data-fetching and render concerns in your React App. I recommend you read this article which explains this idea very well. https://medium.com/@learnreact/container-components-c0e67432e005#.sfydn87nm

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

The problem is that these two queries are each returning more than one row:

select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')
select isbn from dbo.lending where lended_date between @fdate and @tdate

You have two choices, depending on your desired outcome. You can either replace the above queries with something that's guaranteed to return a single row (for example, by using SELECT TOP 1), OR you can switch your = to IN and return multiple rows, like this:

select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close'))

Automatically accept all SDK licences

I was getting this error:

License for package Android SDK Build-Tools 30.0.2 not accepted.

So, I went to Tools -> SDK Manager -> SDK Tools. Then I installed Google Play Licensing Library. It solved the problem.

enter image description here

Liquibase lock - reasons?

Edit june 2020

Don't follow this advice. It's caused trouble to many people over the years. It worked for me a long time ago and I posted it in good faith, but it's clearly not the way to do it. The DATABASECHANGELOCK table needs to have stuff in it, so it's a bad idea to just delete everything from it without dropping the table.

Leos Literak, for instance, followed these instructions and the server failed to start.

Original answer

It's possibly due to a killed liquibase process not releasing its lock on the DATABASECHANGELOGLOCK table. Then,

DELETE FROM DATABASECHANGELOGLOCK;

might help you.

Edit: @Adrian Ber's answer provides a better solution than this. Only do this if you have any problems doing his solution.

What is AF_INET, and why do I need it?

You need arguments like AF_UNIX or AF_INET to specify which type of socket addressing you would be using to implement IPC socket communication. AF stands for Address Family.

As in BSD standard Socket (adopted in Python socket module) addresses are represented as follows:

  1. A single string is used for the AF_UNIX/AF_LOCAL address family. This option is used for IPC on local machines where no IP address is required.

  2. A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer. Used to communicate between processes over the Internet.

AF_UNIX , AF_INET6 , AF_NETLINK , AF_TIPC , AF_CAN , AF_BLUETOOTH , AF_PACKET , AF_RDS are other option which could be used instead of AF_INET.

This thread about the differences between AF_INET and PF_INET might also be useful.

Set environment variables from file of key/value pairs

I have upvoted user4040650's answer because it's both simple, and it allows comments in the file (i.e. lines starting with #), which is highly desirable for me, as comments explaining the variables can be added. Just rewriting in the context of the original question.

If the script is callled as indicated: minientrega.sh prac1, then minientrega.sh could have:

set -a # export all variables created next
source $1
set +a # stop exporting

# test that it works
echo "Ficheros: $MINIENTREGA_FICHEROS"

The following was extracted from the set documentation:

This builtin is so complicated that it deserves its own section. set allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables.

set [--abefhkmnptuvxBCEHPT] [-o option-name] [argument …] set [+abefhkmnptuvxBCEHPT] [+o option-name] [argument …]

If no options or arguments are supplied, set displays the names and values of all shell variables and functions, sorted according to the current locale, in a format that may be reused as input for setting or resetting the currently-set variables. Read-only variables cannot be reset. In POSIX mode, only shell variables are listed.

When options are supplied, they set or unset shell attributes. Options, if specified, have the following meanings:

-a Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands.

And this as well:

Using ‘+’ rather than ‘-’ causes these options to be turned off. The options can also be used upon invocation of the shell. The current set of options may be found in $-.

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

What is causing the error `string.split is not a function`?

In clausule if, use (). For example:

stringtorray = "xxxx,yyyyy,zzzzz";
if (xxx && (stringtoarray.split(',') + "")) { ...

Comparing user-inputted characters in C

Because comparison doesn't work that way. 'Y' || 'y' is a logical-or operator; it returns 1 (true) if either of its arguments is true. Since 'Y' and 'y' are both true, you're comparing *answer with 1.

What you want is if(*answer == 'Y' || *answer == 'y') or perhaps:

switch (*answer) {
  case 'Y':
  case 'y':
    /* Code for Y */
    break;
  default:
    /* Code for anything else */
}

Reading a file line by line in Go

EDIT: As of go1.1, the idiomatic solution is to use bufio.Scanner

I wrote up a way to easily read each line from a file. The Readln(*bufio.Reader) function returns a line (sans \n) from the underlying bufio.Reader struct.

// Readln returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
func Readln(r *bufio.Reader) (string, error) {
  var (isPrefix bool = true
       err error = nil
       line, ln []byte
      )
  for isPrefix && err == nil {
      line, isPrefix, err = r.ReadLine()
      ln = append(ln, line...)
  }
  return string(ln),err
}

You can use Readln to read every line from a file. The following code reads every line in a file and outputs each line to stdout.

f, err := os.Open(fi)
if err != nil {
    fmt.Printf("error opening file: %v\n",err)
    os.Exit(1)
}
r := bufio.NewReader(f)
s, e := Readln(r)
for e == nil {
    fmt.Println(s)
    s,e = Readln(r)
}

Cheers!

Cleaning up old remote git branches

Consider to run :

git fetch --prune

On a regular basis in each repo to remove local branches that have been tracking a remote branch that is deleted (no longer exists in remote GIT repo).

This can be further simplified by

git config remote.origin.prune true

this is a per-repo setting that will make any future git fetch or git pull to automatically prune.

To set this up for your user, you may also edit the global .gitconfig and add

[fetch]
    prune = true

However, it's recommended that this is done using the following command:

git config --global fetch.prune true

or to apply it system wide (not just for the user)

git config --system fetch.prune true

How to redirect page after click on Ok button on sweet alert?

None of the above solutions worked for me, I had to use .then

swal({
  title: 'Success!',
  text: message,
  type: 'success',
  confirmButtonText: 'OK'
}).then(() => {
  console.log('triggered redirect here');
});

Random record from MongoDB

Using Python (pymongo), the aggregate function also works.

collection.aggregate([{'$sample': {'size': sample_size }}])

This approach is a lot faster than running a query for a random number (e.g. collection.find([random_int]). This is especially the case for large collections.

How do I lowercase a string in C?

Looping the pointer to gain better performance:

#include <ctype.h>

char* toLower(char* s) {
  for(char *p=s; *p; p++) *p=tolower(*p);
  return s;
}
char* toUpper(char* s) {
  for(char *p=s; *p; p++) *p=toupper(*p);
  return s;
}

Check if date is a valid one

How to check if a string is a valid date using Moment, when the date and date format are different

Sorry, but did any of the given solutions on this thread actually answer the question that was asked?

I have a String date and a date format which is different. Ex.: date: 2016-10-19 dateFormat: "DD-MM-YYYY". I need to check if this date is a valid date.

The following works for me...

const date = '2016-10-19';
const dateFormat = 'DD-MM-YYYY';
const toDateFormat = moment(new Date(date)).format(dateFormat);
moment(toDateFormat, dateFormat, true).isValid();

// Note: `new Date()` circumvents the warning that
// Moment throws (https://momentjs.com/guides/#/warnings/js-date/),
// but may not be optimal.

But honestly, don't understand why moment.isDate()(as documented) only accepts an object. Should also support a string in my opinion.

Serialize form data to JSON

Here is what I use for this situation as a module (in my formhelper.js):

define(function(){
    FormHelper = {};

    FormHelper.parseForm = function($form){
        var serialized = $form.serializeArray();
        var s = '';
        var data = {};
        for(s in serialized){
            data[serialized[s]['name']] = serialized[s]['value']
        }
        return JSON.stringify(data);
    }

    return FormHelper;
});

It kind of sucks that I can't seem to find another way to do what I want to do.

This does return this JSON for me:

{"first_name":"John","last_name":"Smith","age":"30"}

How can I get session id in php and show it?

You have uniqid function for unique id

You can add prefix to make it more unique

Source : http://pk1.php.net/uniqid

Any tools to generate an XSD schema from an XML instance document?

In VS2010 if you load an XML file into the editor, click the XML menu >> Create Schema.

GitHub: How to make a fork of public repository private?

There is one more option now ( January-2015 )

  1. Create a new private repo
  2. On the empty repo screen there is an "import" option/button enter image description here
  3. click it and put the existing github repo url There is no github option mention but it works with github repos too. enter image description here
  4. DONE

Could not load file or assembly '***.dll' or one of its dependencies

I had the same problem. For me, it was caused by the default settings in the local IIS server on my machine. So the easy way to fix it, was to use the built in Visual Studio development server instead :)

Newer IIS versions on x64 machines have a setting that doesn't allow 32 bit applications to run by default. To enable 32 bit applications in the local IIS, select the relevant application pool in IIS manager, click "Advanced settings", and change "Enable 32-Bit Applications" from False to True

C pointer to array/array of pointers disambiguation

In pointer to an integer if pointer is incremented then it goes next integer.

in array of pointer if pointer is incremented it jumps to next array

how to get 2 digits after decimal point in tsql?

Your format syntax is wrong actual syntax is

 FORMAT ( value, format [, culture ] )

Please follow this link it helps you

Click here for more details

Can I change the height of an image in CSS :before/:after pseudo-elements?

You can change the height or width of the Before or After element like this:

.element:after {
  display: block;
  content: url('your-image.png');
  height: 50px; //add any value you need for height or width
  width: 50px;
}

Open mvc view in new window from controller

I assigned the javascript in my Controller:

model.linkCode = "window.open('https://www.yahoo.com', '_blank')";

And in my view:

@section Scripts{
    <script @Html.CspScriptNonce()>

    $(function () {

        @if (!String.IsNullOrEmpty(Model.linkCode))
        {
            WriteLiteral(Model.linkCode);
        }
    });

That opened a new tab with the link, and went to it.

Interestingly, run locally it engaged a popup blocker, but seemed to work fine on the servers.

Check date between two other dates spring data jpa

You can also write a custom query using @Query

@Query(value = "from EntityClassTable t where yourDate BETWEEN :startDate AND :endDate")
public List<EntityClassTable> getAllBetweenDates(@Param("startDate")Date startDate,@Param("endDate")Date endDate);

Where does Java's String constant pool live, the heap or the stack?

String pooling

String pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. You can achieve this goal by keeping your own Map (with possibly soft or weak references depending on your requirements) and using map values as canonicalised values. Or you can use String.intern() method which is provided to you by JDK.

At times of Java 6 using String.intern() was forbidden by many standards due to a high possibility to get an OutOfMemoryException if pooling went out of control. Oracle Java 7 implementation of string pooling was changed considerably. You can look for details in http://bugs.sun.com/view_bug.do?bug_id=6962931 and http://bugs.sun.com/view_bug.do?bug_id=6962930.

String.intern() in Java 6

In those good old days all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool. Besides explicitly interned strings, PermGen string pool also contained all literal strings earlier used in your program (the important word here is used – if a class or method was never loaded/called, any constants defined in it will not be loaded).

The biggest issue with such string pool in Java 6 was its location – the PermGen. PermGen has a fixed size and can not be expanded at runtime. You can set it using -XX:MaxPermSize=96m option. As far as I know, the default PermGen size varies between 32M and 96M depending on the platform. You can increase its size, but its size will still be fixed. Such limitation required very careful usage of String.intern – you’d better not intern any uncontrolled user input using this method. That’s why string pooling at times of Java 6 was mostly implemented in the manually managed maps.

String.intern() in Java 7

Oracle engineers made an extremely important change to the string pooling logic in Java 7 – the string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application. Technically, this alone could be a sufficient reason to reconsider using String.intern() in your Java 7 programs. But there are other reasons.

String pool values are garbage collected

Yes, all strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It applies to all discussed versions of Java. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.

Being eligible for garbage collection and residing in the heap, a JVM string pool seems to be a right place for all your strings, isn’t it? In theory it is true – non-used strings will be garbage collected from the pool, used strings will allow you to save memory in case then you get an equal string from the input. Seems to be a perfect memory saving strategy? Nearly so. You must know how the string pool is implemented before making any decisions.

source.

Set cookies for cross origin requests

Note for Chrome Browser released in 2020.

A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure.

So if your backend server does not set SameSite=None, Chrome will use SameSite=Lax by default and will not use this cookie with { withCredentials: true } requests.

More info https://www.chromium.org/updates/same-site.

Firefox and Edge developers also want to release this feature in the future.

Spec found here: https://tools.ietf.org/html/draft-west-cookie-incrementalism-01#page-8

Wait until an HTML5 video loads

you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.

_x000D_
_x000D_
<video preload="none">
_x000D_
_x000D_
_x000D_

Check if not nil and not empty in Rails shortcut?

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
  %w(city state bio contact twitter mail).each do |attr|
    instance_variable_set "@#{attr}", @user[attr].present?
  end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

Hadoop cluster setup - java.net.ConnectException: Connection refused

I was getting the same issue and found that OpenSSH service was not running and it was causing the issue. After starting the SSH service it worked.

To check if SSH service is running or not:

ssh localhost

To start the service, if OpenSSH is already installed:

sudo /etc/init.d/ssh start

Interface/enum listing standard mime-type constants

There is now also the class org.apache.http.entity.ContentType from package org.apache.httpcomponents.httpcore, starting from 4.2 up.

What is the difference between int, Int16, Int32 and Int64?

Nothing. The sole difference between the types is their size (and, hence, the range of values they can represent).

python exception message capturing

There are some cases where you can use the e.message or e.messages.. But it does not work in all cases. Anyway the more safe is to use the str(e)

try:
  ...
except Exception as e:
  print(e.message)

How to call a JavaScript function, declared in <head>, in the body when I want to call it

I'm not sure what you mean by "myself".

Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.

e.g. On page load:

<body onload="myfunction();">

Or on mouseover:

<table onmouseover="myfunction();">

As a result the first question is, "What do you want to do to cause the function to execute?"

After you determine that it will be much easier to give you a direct answer.

What’s the best way to check if a file exists in C++? (cross platform)

Use boost::filesystem:

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}

Update multiple rows with different values in a single SQL query

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

You could do:

 UPDATE table SET posX=CASE
      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ...
      ELSE posX END, posY = CASE ... END
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

Otherwise, I'd try with indexing on id, or modifying the architecture.

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

how to add json library

AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

How to change an input button image using CSS?

My solution without js and without images is this:

*HTML:

<input type=Submit class=continue_shopping_2 
name=Register title="Confirm Your Data!" 
value="confirm your data">

*CSS:

.continue_shopping_2:hover{
background-color:#FF9933;
text-decoration:none;
color:#FFFFFF;}


.continue_shopping_2{
padding:0 0 3px 0;
cursor:pointer;
background-color:#EC5500;
display:block;
text-align:center;
margin-top:8px;
width:174px;
height:21px;
border-radius:5px;
border-width:1px;
border-style:solid;
border-color:#919191;
font-family:Verdana;
font-size:13px;
font-style:normal;
line-height:normal;
font-weight:bold;
color:#FFFFFF;}

How to create an Observable from static data similar to http one in Angular?

As of July 2018 and the release of RxJS 6, the new way to get an Observable from a value is to import the of operator like so:

import { of } from 'rxjs';

and then create the observable from the value, like so:

of(someValue);

Note, that you used to have to do Observable.of(someValue) like in the currently accepted answer. There is a good article on the other RxJS 6 changes here.

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

The answer posted here by simon-sarris helped me.

This helped me solve my issue.

The Visual Studio installer must have added an errant line to the registry.

open up regedit and take a look at this registry key:

enter image description here

See that key? The Content Type key? change its value from text/plain to text/javascript.

Finally chrome can breathe easy again.

I should note that neither Content Type nor PercievedType are there by default on Windows 7, so you could probably safely delete them both, but the minimum you need to do is that edit.

Anyway I hope this fixes it for you too!

Don't forget to restart your system after the changes.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:

  1. Go to Tools in top nav
  2. Select options, then SQL Service Object Explorer (on left)
  3. On right side of panel, click into the field that contains 200 and change to 300 (or whatever number you wish)
  4. Click OK and voila, you're all set!

SQLAlchemy: how to filter date field?

In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:

qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

Also you can use between:

qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

Inline for loop

What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:

p = [q.index(v) if v in q else 99999 for v in vm]

When using a list comprehension, you do not call list.append because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for keyword, which in this case is q.index(v) if v in q else 99999. Incidentially, if you do use list.append inside a comprehension, then you will get a list of None values because that is what the append method always returns.

How can I adjust DIV width to contents

You could try using float:left; or display:inline-block;.

Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.

However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block will have less of an impact though, so probably best to try that first.

Property '...' has no initializer and is not definitely assigned in the constructor

Can't you just use a Definite Assignment Assertion? (See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions)

i.e. declaring the property as makes!: any[]; The ! assures typescript that there definitely will be a value at runtime.

Sorry I haven't tried this in angular but it worked great for me when I was having the exact same problem in React.

Two-way SSL clarification

In two way ssl the client asks for servers digital certificate and server ask for the same from the client. It is more secured as it is both ways, although its bit slow. Generally we dont follow it as the server doesnt care about the identity of the client, but a client needs to make sure about the integrity of server it is connecting to.

How to prevent text in a table cell from wrapping

Have a look at the white-space property, used like this:

th {
    white-space: nowrap;
}

This will force the contents of <th> to display on one line.

From linked page, here are the various options for white-space:

normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.

nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

How to populate a dropdownlist with json data in jquery?

To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

Matching exact string with JavaScript

Either modify the pattern beforehand so that it only matches the entire string:

var r = /^a$/

or check afterward whether the pattern matched the whole string:

function matchExact(r, str) {
   var match = str.match(r);
   return match && str === match[0];
}

What is the maximum size of a web browser's cookie's key?

You can also use web storage too if the app specs allows you that (it has support for IE8+).

It has 5M (most browsers) or 10M (IE) of memory at its disposal.

"Web Storage (Second Edition)" is the API and "HTML5 Local Storage" is a quick start.

git push rejected

If nothing works, try:

git pull --allow-unrelated-histories <repo> <branch>

then do:

git push --set-upstream origin master

ConnectionTimeout versus SocketTimeout

A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.

A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.

python pandas remove duplicate columns

Note that Gene Burinsky's answer (at the time of writing the selected answer) keeps the first of each duplicated column. To keep the last:

df=df.loc[:, ~df.columns[::-1].duplicated()[::-1]]

Use 'import module' or 'from module import'?

I would like to add to this, there are somethings to consider during the import calls:

I have the following structure:

mod/
    __init__.py
    main.py
    a.py
    b.py
    c.py
    d.py

main.py:

import mod.a
import mod.b as b
from mod import c
import d

dis.dis shows the difference:

  1           0 LOAD_CONST               0 (-1)
              3 LOAD_CONST               1 (None)
              6 IMPORT_NAME              0 (mod.a)
              9 STORE_NAME               1 (mod)

  2          12 LOAD_CONST               0 (-1)
             15 LOAD_CONST               1 (None)
             18 IMPORT_NAME              2 (b)
             21 STORE_NAME               2 (b)

  3          24 LOAD_CONST               0 (-1)
             27 LOAD_CONST               2 (('c',))
             30 IMPORT_NAME              1 (mod)
             33 IMPORT_FROM              3 (c)
             36 STORE_NAME               3 (c)
             39 POP_TOP

  4          40 LOAD_CONST               0 (-1)
             43 LOAD_CONST               1 (None)
             46 IMPORT_NAME              4 (mod.d)
             49 LOAD_ATTR                5 (d)
             52 STORE_NAME               5 (d)
             55 LOAD_CONST               1 (None)

In the end they look the same (STORE_NAME is result in each example), but this is worth noting if you need to consider the following four circular imports:

example1

foo/
   __init__.py
   a.py
   b.py
a.py:
import foo.b 
b.py:
import foo.a
>>> import foo.a
>>>

This works

example2

bar/
   __init__.py
   a.py
   b.py
a.py:
import bar.b as b
b.py:
import bar.a as a
>>> import bar.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "bar\a.py", line 1, in <module>
    import bar.b as b
  File "bar\b.py", line 1, in <module>
    import bar.a as a
AttributeError: 'module' object has no attribute 'a'

No dice

example3

baz/
   __init__.py
   a.py
   b.py
a.py:
from baz import b
b.py:
from baz import a
>>> import baz.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "baz\a.py", line 1, in <module>
    from baz import b
  File "baz\b.py", line 1, in <module>
    from baz import a
ImportError: cannot import name a

Similar issue... but clearly from x import y is not the same as import import x.y as y

example4

qux/
   __init__.py
   a.py
   b.py
a.py:
import b 
b.py:
import a
>>> import qux.a
>>>

This one also works

What is the difference between "::" "." and "->" in c++

-> is for pointers to a class instance

. is for class instances

:: is for classnames - for example when using a static member

How to make a machine trust a self-signed Java application

I was having the same issue. So I went to the Java options through Control Panel. Copied the web address that I was having an issue with to the exceptions and it was fixed.

When and why do I need to use cin.ignore() in C++?

Ignore function is used to skip(discard/throw away) characters in the input stream. Ignore file is associated with the file istream. Consider the function below ex: cin.ignore(120,'/n'); the particular function skips the next 120 input character or to skip the characters until a newline character is read.

How can I check if a key exists in a dictionary?

If you want to retrieve the key's value if it exists, you can also use

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value).

Cookie blocked/not saved in IFRAME in Internet Explorer

For anyone trying to get the P3P Compact Policy working with static content:

It is only possible if you are able to send custom server-side response headers with the static content.

For a more detailed explanation see my answer here: Set P3P code in HTML

How to get the name of a class without the package?

Class.getSimpleName()

Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.

The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

It is actually stripping the package information from the name, but this is hidden from you.

Insert line break inside placeholder attribute of a textarea?

Old answer:

Nope, you can't do that in the placeholder attribute. You can't even html encode newlines like &#13;&#10; in a placeholder.

New answer:

Modern browsers give you several ways to do this. See this JSFiddle:

http://jsfiddle.net/pdXRx/5/

How do you open an SDF file (SQL Server Compact Edition)?

Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).

Steps for open SDF Files:

  1. Click Add Connection

  2. Select Build data context automatically and Default (LINQ to SQL), then Next.

  3. Under Provider choose SQL CE 4.0.

  4. Under Database with Attach database file selected, choose Browse to select your .sdf file.

  5. Click OK.

Extract first item of each sublist

Your code is almost correct. The only issue is the usage of list comprehension.

If you use like: (x[0] for x in lst), it returns a generator object. If you use like: [x[0] for x in lst], it return a list.

When you append the list comprehension output to a list, the output of list comprehension is the single element of the list.

lst = [["a","b","c"], [1,2,3], ["x","y","z"]]
lst2 = []
lst2.append([x[0] for x in lst])
print lst2[0]

lst2 = [['a', 1, 'x']]

lst2[0] = ['a', 1, 'x']

Please let me know if I am incorrect.

Python: list of lists

Time traveller here

List_of_list =[([z for z in range(x-2,x+1) if z >= 0],y) for y in range(10) for x in range(10)]

This should do the trick. And the output is this:

[([0], 0), ([0, 1], 0), ([0, 1, 2], 0), ([1, 2, 3], 0), ([2, 3, 4], 0),  ([3, 4, 5], 0), ([4, 5, 6], 0), ([5, 6, 7], 0), ([6, 7, 8], 0), ([7, 8, 9], 0), ([0], 1), ([0, 1], 1), ([0, 1, 2], 1), ([1, 2, 3], 1), ([2, 3, 4], 1), ([3, 4, 5], 1), ([4, 5, 6], 1), ([5, 6, 7], 1), ([6, 7, 8], 1), ([7, 8, 9], 1), ([0], 2), ([0, 1], 2), ([0, 1, 2], 2), ([1, 2, 3], 2), ([2, 3, 4], 2), ([3, 4, 5], 2), ([4, 5, 6], 2), ([5, 6, 7], 2), ([6, 7, 8], 2), ([7, 8, 9], 2), ([0], 3), ([0, 1], 3), ([0, 1, 2], 3), ([1, 2, 3], 3), ([2, 3, 4], 3), ([3, 4, 5], 3), ([4, 5, 6], 3), ([5, 6, 7], 3), ([6, 7, 8], 3), ([7, 8, 9], 3), ([0], 4), ([0, 1], 4), ([0, 1, 2], 4), ([1, 2, 3], 4), ([2, 3, 4], 4), ([3, 4, 5], 4), ([4, 5, 6], 4), ([5, 6, 7], 4), ([6, 7, 8], 4), ([7, 8, 9], 4), ([0], 5), ([0, 1], 5), ([0, 1, 2], 5), ([1, 2, 3], 5), ([2, 3, 4], 5), ([3, 4, 5], 5), ([4, 5, 6], 5), ([5, 6, 7], 5), ([6, 7, 8], 5), ([7, 8, 9], 5), ([0], 6), ([0, 1], 6), ([0, 1, 2], 6), ([1, 2, 3], 6), ([2, 3, 4], 6), ([3, 4, 5], 6), ([4, 5, 6], 6), ([5, 6, 7], 6), ([6, 7, 8], 6), ([7, 8, 9], 6), ([0], 7), ([0, 1], 7), ([0, 1, 2], 7), ([1, 2, 3], 7), ([2, 3, 4], 7), ([3, 4, 5], 7), ([4, 5, 6], 7), ([5, 6, 7], 7), ([6, 7, 8], 7), ([7, 8, 9], 7), ([0], 8), ([0, 1], 8), ([0, 1, 2], 8), ([1, 2, 3], 8), ([2, 3, 4], 8), ([3, 4, 5], 8), ([4, 5, 6], 8), ([5, 6, 7], 8), ([6, 7, 8], 8), ([7, 8, 9], 8), ([0], 9), ([0, 1], 9), ([0, 1, 2], 9), ([1, 2, 3], 9), ([2, 3, 4], 9), ([3, 4, 5], 9), ([4, 5, 6], 9), ([5, 6, 7], 9), ([6, 7, 8], 9), ([7, 8, 9], 9)]    

This is done by list comprehension(which makes looping elements in a list via one line code possible). The logic behind this one-line code is the following:

(1) for x in range(10) and for y in range(10) are employed for two independent loops inside a list

(2) (a list, y) is the general term of the loop, which is why it is placed before two for's in (1)

(3) the length of the list in (2) cannot exceed 3, and the list depends on x, so

[z for z in range(x-2,x+1)] 

is used

(4) because z starts from zero but range(x-2,x+1) starts from -2 which isn't what we want, so a conditional statement if z >= 0 is placed at the end of the list in (2)

[z for z in range(x-2,x+1) if z >= 0] 

How to import spring-config.xml of one project into spring-config.xml of another project?

<import resource="classpath:spring-config.xml" />

Reference:

Add/remove class with jquery based on vertical scroll?

Its my code

jQuery(document).ready(function(e) {
    var WindowHeight = jQuery(window).height();

    var load_element = 0;

    //position of element
    var scroll_position = jQuery('.product-bottom').offset().top;

    var screen_height = jQuery(window).height();
    var activation_offset = 0;
    var max_scroll_height = jQuery('body').height() + screen_height;

    var scroll_activation_point = scroll_position - (screen_height * activation_offset);

    jQuery(window).on('scroll', function(e) {

        var y_scroll_pos = window.pageYOffset;
        var element_in_view = y_scroll_pos > scroll_activation_point;
        var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;

        if (element_in_view || has_reached_bottom_of_page) {
            jQuery('.product-bottom').addClass("change");
        } else {
            jQuery('.product-bottom').removeClass("change");
        }

    });

});

Its working Fine

What is the Angular equivalent to an AngularJS $watch?

This does not answer the question directly, but I have on different occasions landed on this Stack Overflow question in order to solve something I would use $watch for in angularJs. I ended up using another approach than described in the current answers, and want to share it in case someone finds it useful.

The technique I use to achieve something similar $watch is to use a BehaviorSubject (more on the topic here) in an Angular service, and let my components subscribe to it in order to get (watch) the changes. This is similar to a $watch in angularJs, but require some more setup and understanding.

In my component:

export class HelloComponent {
  name: string;
  // inject our service, which holds the object we want to watch.
  constructor(private helloService: HelloService){
    // Here I am "watching" for changes by subscribing
    this.helloService.getGreeting().subscribe( greeting => {
      this.name = greeting.value;
    });
  }
}

In my service

export class HelloService {
  private helloSubject = new BehaviorSubject<{value: string}>({value: 'hello'});
  constructor(){}
  // similar to using $watch, in order to get updates of our object 
  getGreeting(): Observable<{value:string}> {
    return this.helloSubject;
  }
  // Each time this method is called, each subscriber will receive the updated greeting.
  setGreeting(greeting: string) {
    this.helloSubject.next({value: greeting});
  }
}

Here is a demo on Stackblitz

How to get height and width of device display in angular2 using typescript?

For those who want to get height and width of device even when the display is resized (dynamically & in real-time):

  • Step 1:

In that Component do: import { HostListener } from "@angular/core";

  • Step 2:

In the component's class body write:

@HostListener('window:resize', ['$event'])
onResize(event?) {
   this.screenHeight = window.innerHeight;
   this.screenWidth = window.innerWidth;
}
  • Step 3:

In the component's constructor call the onResize method to initialize the variables. Also, don't forget to declare them first.

constructor() {
  this.onResize();
}    

Complete code:

import { Component, OnInit } from "@angular/core";
import { HostListener } from "@angular/core";

@Component({
  selector: "app-login",
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class FooComponent implements OnInit {
    screenHeight: number;
    screenWidth: number;

    constructor() {
        this.getScreenSize();
    }

    @HostListener('window:resize', ['$event'])
    getScreenSize(event?) {
          this.screenHeight = window.innerHeight;
          this.screenWidth = window.innerWidth;
          console.log(this.screenHeight, this.screenWidth);
    }

}

How to call a function after delay in Kotlin?

You could launch a coroutine, delay it and then call the function:

 /*GlobalScope.*/launch {
   delay(1000)
   yourFn()
 }

If you are outside of a class or object prepend GlobalScope to let the coroutine run there, otherwise it is recommended to implement the CoroutineScope in the surrounding class, which allows to cancel all coroutines associated to that scope if necessary.

How to prevent user from typing in text field without disabling the field?

Markup

<asp:TextBox ID="txtDateOfBirth" runat="server" onkeydown="javascript:preventInput(event);" onpaste="return false;"
                                TabIndex="1">

Script

function preventInput(evnt) {
//Checked In IE9,Chrome,FireFox
if (evnt.which != 9) evnt.preventDefault();}

How to import module when module name has a '-' dash or hyphen in it?

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

What's NSLocalizedString equivalent in Swift?

The NSLocalizedString exists also in the Swift's world.

func NSLocalizedString(
    key: String,
    tableName: String? = default,
    bundle: NSBundle = default,
    value: String = default,
    #comment: String) -> String

The tableName, bundle, and value parameters are marked with a default keyword which means we can omit these parameters while calling the function. In this case, their default values will be used.

This leads to a conclusion that the method call can be simplified to:

NSLocalizedString("key", comment: "comment")

Swift 5 - no change, still works like that.

How to prevent caching of my Javascript file?

<script src="test.js?random=<?php echo uniqid(); ?>"></script>

EDIT: Or you could use the file modification time so that it's cached on the client.

<script src="test.js?random=<?php echo filemtime('test.js'); ?>"></script>

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources" For example:

_x000D_
_x000D_
<GlobalNamingResources>_x000D_
    <!-- Editable user database that can also be used by_x000D_
         UserDatabaseRealm to authenticate users_x000D_
    -->_x000D_
  <!-- Other previus resouces -->_x000D_
    <Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
    maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
    type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
  </GlobalNamingResources>
_x000D_
_x000D_
_x000D_ In your web application you need a link to that resource (ResourceLink):

project explore

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
   <ResourceLink name="jdbc/your_jndi"_x000D_
      global="jdbc/your_jndi"_x000D_
      auth="Container"_x000D_
      type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
_x000D_
_x000D_

So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml

persistence.xml location

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
 version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
 <persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
  <provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
  <properties>_x000D_
   <property name="javax.persistence.jdbc.driver"   value="org.postgresql.Driver" />_x000D_
   <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
   _x000D_
   <!--  <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
   <property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
   <property name="hibernate.show_sql" value="false" />_x000D_
   <property name="hibernate.format_sql" value="true"/>     _x000D_
  </properties>_x000D_
 </persistence-unit>_x000D_
</persistence>
_x000D_
_x000D_
_x000D_

So in your spring.xml you can do that:

_x000D_
_x000D_
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
   <property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
  </bean>_x000D_
     _x000D_
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
              <property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
              <property name="dataSource" ref="postGresDataSource" />_x000D_
              <property name="jpaVendorAdapter"> _x000D_
                 <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
              </property>_x000D_
        </bean>
_x000D_
_x000D_
_x000D_ Look above that entityManagerFactory bean refers to your UNIT_NAME configured at persistence xml and the bean postGresDataSource has a property that points to your JNDI resource in Tomcat.

_x000D_
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
_x000D_
_x000D_

In this example I used spring with xml but you can do this programmaticaly if you prefer.

That's it, I hope helped.

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

For those who came here looking for the answer and didnt type 3306 wrong...If like myself, you have wasted hours with no luck searching for this answer, then possibly this may help.

If you are seeing this: (HY000/2002): No connection could be made because the target machine actively refused it

Then my understanding is that it cant connect for one of the following below. Now which..

1) is your wamp, mamp, etc icon GREEN? Either way, right-click the icon --> click tools --> test both the port used for Apache (typically 80) and for Mariadb (3307?). Should say 'It is correct' for both.

2) Error comes from a .php file. So, check your dbconnect.php.

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_pw";
$dbname = "your_dbname";
$port = "3307";
?>

Is your setup correct? Does your user exist? Do they have rights? Does port match the tested port in 1)? Doesn't have to be 3307 and user can be root. You can also left click the green icon --> click MariaDB and view used port as shown in the image below. All good? Positive? ok!

enter image description here

3) Error comes when you login to phpmyadmin. So, check your my.ini.

enter image description here

Open my.ini by left clicking the green icon --> click MariaDB -->

; The following options will be passed to all MariaDB clients
[client]
;password = your_password
port = 3307
socket = /tmp/mariadb.sock

; Here follows entries for some specific programs

; The MariaDB server
[wampmariadb64]
;skip-grant-tables
port = 3307
socket = /tmp/mariadb.sock

Make sure the ports match the port MariaDB is being testing on. Then finally..

[mysqld]
port = 3307

At the bottom of my.ini, make sure this port matches as well.

4) 1-3 done? restart your WAMP and cross your fingers!

How to split a string between letters and digits (or between digits and letters)?

You can try this:

Pattern p = Pattern.compile("[a-z]+|\\d+");
Matcher m = p.matcher("123abc345def");
ArrayList<String> allMatches = new ArrayList<>();
while (m.find()) {
    allMatches.add(m.group());
}

The result (allMatches) will be:

["123", "abc", "345", "def"]

Deep copy, shallow copy, clone

Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.


In the Java context, we first need to make a distinction between "copying a value" and "copying an object".

int a = 1;
int b = a;     // copying a value
int[] s = new int[]{42};
int[] t = s;   // copying a value (the object reference for the array above)

StringBuffer sb = new StringBuffer("Hi mom");
               // copying an object.
StringBuffer sb2 = new StringBuffer(sb);

In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new, either explicitly or under the hood.


Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:

public class Example {
    public int foo;
    public int[] bar;
    public Example() { };
    public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}

Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ... 

The normal interpretation is that a "shallow" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to the same array as in the original; e.g.

Example eg2 = new Example(eg1.foo, eg1.bar);

The normal interpretation of a "deep" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to a copy of the original array; e.g.

Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));

(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)

Two more questions / areas of uncertainty exist:

  • How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?

  • What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?


Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:

  • The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).

  • In fact, the specification does not even specifically state that clone produces a new object.

Here's what the javadoc says:

"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case that x.clone().equals(x) will be true, this is not an absolute requirement."

Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.

In short, clone potentially means something different for every Java class.


Some people argue (as @supercat does in comments) that the Java clone() method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.

In C#, why is String a reference type that behaves like a value type?

Not only strings are immutable reference types. Multi-cast delegates too. That is why it is safe to write

protected void OnMyEventHandler()
{
     delegate handler = this.MyEventHandler;
     if (null != handler)
     {
        handler(this, new EventArgs());
     }
}

I suppose that strings are immutable because this is the most safe method to work with them and allocate memory. Why they are not Value types? Previous authors are right about stack size etc. I would also add that making strings a reference types allow to save on assembly size when you use the same constant string in the program. If you define

string s1 = "my string";
//some code here
string s2 = "my string";

Chances are that both instances of "my string" constant will be allocated in your assembly only once.

If you would like to manage strings like usual reference type, put the string inside a new StringBuilder(string s). Or use MemoryStreams.

If you are to create a library, where you expect a huge strings to be passed in your functions, either define a parameter as a StringBuilder or as a Stream.

How to get a list of programs running with nohup

You can also just use the top command and your user ID will indicate the jobs running and the their times.

$ top

(this will show all running jobs)

$ top -U [user ID]

(This will show jobs that are specific for the user ID)

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

In my case I had system variable path has "C:\ProgramData\Oracle\Java\javapath" location.

In "C:\ProgramData\Oracle\Java\javapath" location java, javaw only there. So I am getting the same error.

Once I removed all files in "C:\ProgramData\Oracle\Java\javapath" folder my error got resolved.

Object Dump JavaScript

Firebug + console.log(myObjectInstance)

How do I order my SQLITE database in descending order, for an android app?

About efficient method. You can use CursorLoader. For example I included my action. And you must implement ContentProvider for your data base. https://developer.android.com/reference/android/content/ContentProvider.html

If you implement this, you will call you data base very efficient.

public class LoadEntitiesActionImp implements LoaderManager.LoaderCallbacks<Cursor> {

   public interface OnLoadEntities {
       void onSuccessLoadEntities(List<Entities> entitiesList);
   }

    private OnLoadEntities onLoadEntities;

    private final Context context;

    private final LoaderManager loaderManager;

    public LoadEntitiesActionImp(Context context, LoaderManager loaderManager) {
        this.context = context;
        this.loaderManager = loaderManager;
    }

    public void setCallback(OnLoadEntities onLoadEntities) {
        this.onLoadEntities = onLoadEntities;
    }

    public void loadEntities() {
        loaderManager.initLoader(LOADER_ID, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(context, YOUR_URI, null, YOUR_SELECTION, YOUR_ARGUMENTS_FOR_SELECTION, YOUR_SORT_ORDER);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }

How do I set up CLion to compile and run?

I met some problems in Clion and finally, I solved them. Here is some experience.

  1. Download and install MinGW
  2. g++ and gcc package should be installed by default. Use the MinGW installation manager to install mingw32-libz and mingw32-make. You can open MinGW installation manager through C:\MinGW\libexec\mingw-get.exe This step is the most important step. If Clion cannot find make, C compiler and C++ compiler, recheck the MinGW installation manager to make every necessary package is installed.
  3. In Clion, open File->Settings->Build,Execution,Deployment->Toolchains. Set MinGW home as your local MinGW file.
  4. Start your "Hello World"!

TypeError: can't pickle _thread.lock objects

I had the same problem with Pool() in Python 3.6.3.

Error received: TypeError: can't pickle _thread.RLock objects

Let's say we want to add some number num_to_add to each element of some list num_list in parallel. The code is schematically like this:

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1 

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list)) 
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

    def run_parallel(self, num, shared_new_num_list):
        new_num = num + self.num_to_add # uses class parameter
        shared_new_num_list.append(new_num)

The problem here is that self in function run_parallel() can't be pickled as it is a class instance. Moving this parallelized function run_parallel() out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add and then you have to pass it as an argument.

Solution:

def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
    new_num = num + to_add
    shared_new_num_list.append(new_num)

class DataGenerator:
    def __init__(self, num_list, num_to_add)
        self.num_list = num_list # e.g. [4,2,5,7]
        self.num_to_add = num_to_add # e.g. 1

        self.run()

    def run(self):
        new_num_list = Manager().list()

        pool = Pool(processes=50)
        results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
                      for num in num_list]
        roots = [r.get() for r in results]
        pool.close()
        pool.terminate()
        pool.join()

Other suggestions above didn't help me.

How to prevent IFRAME from redirecting top-level window

With HTML5 the iframe sandbox attribute was added. At the time of writing this works on Chrome, Safari, Firefox and recent versions of IE and Opera but does pretty much what you want:

<iframe src="url" sandbox="allow-forms allow-scripts"></iframe>

If you want to allow top-level redirects specify sandbox="allow-top-navigation".

Is there any way to configure multiple registries in a single npmrc file

On version 4.4.1, if you can change package name, use:

npm config set @myco:registry http://reg.example.com

Where @myco is your package scope.

You can install package in this way:

npm install @myco/my-package

For more info: https://docs.npmjs.com/misc/scope

Bundle ID Suffix? What is it?

If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.

In Bundle ID Suffix you should write full name of bundle ID.

Example:

Bundle ID suffix = thebestapp (NOT CORRECT!!!!)

Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)

The reason for this is explained in the Developer Portal:

The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g. ABCDE12345), and an App ID Suffix (a Bundle ID search string, e.g. com.mycompany.appname). [emphasis added]

So in this case the suffix is the full string com.awesomeapps.thebestapp.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Passing variable number of arguments around

Let's say you have a typical variadic function you've written. Because at least one argument is required before the variadic one ..., you have to always write an extra argument in usage.

Or do you?

If you wrap your variadic function in a macro, you need no preceding arg. Consider this example:

#define LOGI(...)
    ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))

This is obviously far more convenient, since you needn't specify the initial argument every time.

Using isKindOfClass with Swift

Another approach using the new Swift 2 syntax is to use guard and nest it all in one conditional.

guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
    return //Do Nothing
}
//Do something with picker