Programs & Examples On #Vtd xml

Virtual Token Descriptor for eXtensible Markup Language (VTD-XML) refers to a collection of cross-platform XML processing technologies centered on a non-extractive XML, "document-centric" parsing technique called Virtual Token Descriptor (VTD).

Best XML parser for Java

I have found dom4j to be the tool for working with XML. Especially compared to Xerces.

sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

The minimum configuration to properly run sqlplus from the shell is to set ORACLE_HOME and LD_LIBRARY_PATH. For ease of use, you might want to set the PATH accordingly too.

Assuming you have unzipped the required archives in /opt/oracle/instantclient_11_1:

$ export ORACLE_HOME=/opt/oracle/instantclient_11_1
$ export LD_LIBRARY_PATH="$ORACLE_HOME"
$ export PATH="$ORACLE_HOME:$PATH"

$ sqlplus

SQL*Plus: Release 11.1.0.7.0 - Production on Wed Dec 31 14:06:06 2014
...

Getting the source of a specific image element with jQuery

If you do not specifically need the alt text of an image, then you can just target the class/id of the image.

$('img.propImg').each(function(){ 
     enter code here
}

I know it’s not quite answering the question, though I’d spent ages trying to figure this out and this question gave me the solution :). In my case I needed to hide any image tags with a specific src.

$('img.propImg').each(function(){ //for each loop that gets all the images. 
        if($(this).attr('src') == "img/{{images}}") { // if the src matches this
        $(this).css("display", "none") // hide the image.
    }
});

How to show only next line after the matched one?

perl one-liner alert

just for fun... print only one line after match

perl -lne '$next = ($.+1) if /match/; $. == $next && print' data.txt

even more fun... print the next ten lines after match

perl -lne 'push @nexts, (($.+1)..($.+10)) if /match/; $. ~~ @nexts && print' data.txt

kinda cheating though since there's actually two commands

Back to previous page with header( "Location: " ); in PHP

Storing previous url in a session variable is bad, because the user might right click on multiple pages and then come back and save.

unless you save the previous url in the session variable to a hidden field in the form and after save header( "Location: save URL of calling page" );

Python not working in the command line of git bash

2 workarounds, rather than a solution: In my Git Bash, following command hangs and I don't get the prompt back:

% python

So I just use:

% winpty python

As some people have noted above, you can also use:

% python -i

2020-07-14: Git 2.27.0 has added optional experimental support for pseudo consoles, which allow running Python from the command line: enter image description here

See attached session.enter image description here

How to move from one fragment to another fragment on click of an ImageView in Android?

Add this code where you want to click and load Fragment. I hope it's work for you.


Fragment fragment = new yourfragment();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

React - Component Full Screen (with height 100%)

I had trouble until i used the inspector and realized react puts everything inside a div with id='root' granting that 100% height along with body and html worked for me.

I'm getting favicon.ico error

Also, be careful so your href location isn't faulty. Study case:

My index page was in a temporary sub-folder named LAYOUTS. To reach the favicon.png from inside the IMAGES folder, which was a sibling of the LAYOUTS folder, I had to put a path in my href like this

href="../images/favicon-32x32.png"

Double periods are necessary for folder navigation "upwards", then the forward slash + images string gets you into the images folder (performing a tree branch "jump") and finally you get to reference your file by writing favicon-32x32.png.

This explanation is useful for those that start out from scratch and it would have been useful to have seen it a couple of times since I would forget that I had certain *.php files outside the LAYOUTS folder which needed different tree hrefs on my links, from the HEAD section of each page.

Reference the path to your favicon image accordingly.

ArrayList - How to modify a member of an object?

You can do this:

myList.get(3).setEmail("new email");

Disabling Chrome Autofill

None of the other solutions to these question worked for me.

The only think that worked is this one:

It removes "name" and "id" attributes from elements and assigns them back after 1ms. Put this in document get ready.

$(document).ready(function() {
    $('form[autocomplete="off"] input, input[autocomplete="off"]').each(function () {

                var input = this;
                var name = $(input).attr('name');
                var id = $(input).attr('id');

                $(input).removeAttr('name');
                $(input).removeAttr('id');

                setTimeout(function () {
                    $(input).attr('name', name);
                    $(input).attr('id', id);
                }, 1);
            });
});

Variable declaration in a header file

What about this solution?

#ifndef VERSION_H
#define VERSION_H

static const char SVER[] = "14.2.1";
static const char AVER[] = "1.1.0.0";

#else

extern static const char SVER[];
extern static const char AVER[];

#endif /*VERSION_H */

The only draw back I see is that the include guard doesn't save you if you include it twice in the same file.

How to generate a random int in C?

This is a good way to get a random number between two numbers of your choice.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

    #define randnum(min, max) \
        ((rand() % (int)(((max) + 1) - (min))) + (min))

int main()
{
    srand(time(NULL));

    printf("%d\n", randnum(1, 70));
}

Output the first time: 39

Output the second time: 61

Output the third time: 65

You can change the values after randnum to whatever numbers you choose, and it will generate a random number for you between those two numbers.

Unsupported major.minor version 52.0 when rendering in Android Studio

For those of you, who are still facing this. I got this problem after I upgraded to Android Studio to 2.1.2. I was stuck at this problem for about an hour, I tried these solutions:

  1. multidexEnabled true
  2. increasing the memory for deamon thread
  3. upgraded to Java 8

I double checked the gradle scripts and found this:

 compileSdkVersion 23
 buildToolsVersion "24.0.0"

changed to:

compileSdkVersion 23
buildToolsVersion "23.0.3"

I don't know how this caused the error, but this did the trick for me. Please let me know how this worked if you know the answer. Thanks

Iterating through all the cells in Excel VBA or VSTO 2005

You basically can loop over a Range

Get a sheet

myWs = (Worksheet)MyWb.Worksheets[1];

Get the Range you're interested in If you really want to check every cell use Excel's limits

The Excel 2007 "Big Grid" increases the maximum number of rows per worksheet from 65,536 to over 1 million, and the number of columns from 256 (IV) to 16,384 (XFD). from here http://msdn.microsoft.com/en-us/library/aa730921.aspx#Office2007excelPerf_BigGridIncreasedLimitsExcel

and then loop over the range

        Range myBigRange = myWs.get_Range("A1", "A256");

        string myValue;

        foreach(Range myCell in myBigRange )
        {
            myValue = myCell.Value2.ToString();
        }

Python: Passing variables between functions

Your return is useless if you don't assign it

list=defineAList()

Launch Image does not show up in my iOS App

I had the same issue after I started using Xcode 6.1 and changed my launcher images. I had all images in an Asset Catalog. I would get only a black screen instead of the expected static image. After trying so many things, I realised the problem was that the Asset Catalog had the Project 'Target Membership' ticked-off in its FileInspector view. Ticking it to ON did the magic and the image started to appear on App launch.

How to force a component's re-rendering in Angular 2?

Other answers here provide solutions for triggering change detection cycles that will update component's view (which is not same as full re-render).

Full re-render, which would destroy and reinitialize component (calling all lifecycle hooks and rebuilding view) can be done by using ng-template, ng-container and ViewContainerRef in following way:

<div>
  <ng-container #outlet >
  </ng-container>
</div>

<ng-template #content>
  <child></child>
</ng-template>

Then in component having reference to both #outlet and #content we can clear outlets' content and insert another instance of child component:

@ViewChild("outlet", {read: ViewContainerRef}) outletRef: ViewContainerRef;
@ViewChild("content", {read: TemplateRef}) contentRef: TemplateRef<any>;

private rerender() {
    this.outletRef.clear();
    this.outletRef.createEmbeddedView(this.contentRef);
}

Additionally initial content should be inserted on AfterContentInit hook:

ngAfterContentInit() {
    this.outletRef.createEmbeddedView(this.contentRef);
}

Full working solution can be found here https://stackblitz.com/edit/angular-component-rerender .

How to get system time in Java without creating a new Date

You can use System.currentTimeMillis().

At least in OpenJDK, Date uses this under the covers.

The call in System is to a native JVM method, so we can't say for sure there's no allocation happening under the covers, though it seems unlikely here.

TreeMap sort by value

I know this post specifically asks for sorting a TreeMap by values, but for those of us that don't really care about implementation but do want a solution that keeps the collection sorted as elements are added, I would appreciate feedback on this TreeSet-based solution. For one, elements are not easily retrieved by key, but for the use case I had at hand (finding the n keys with the lowest values), this was not a requirement.

  TreeSet<Map.Entry<Integer, Double>> set = new TreeSet<>(new Comparator<Map.Entry<Integer, Double>>()
  {
    @Override
    public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2)
    {
      int valueComparison = o1.getValue().compareTo(o2.getValue());
      return valueComparison == 0 ? o1.getKey().compareTo(o2.getKey()) : valueComparison;
    }
  });
  int key = 5;
  double value = 1.0;
  set.add(new AbstractMap.SimpleEntry<>(key, value));

JavaScript - Replace all commas in a string

Just for fun:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Instead of

<button ng-click="removeTask({{task.id}})">remove</button>

do this:

<button ng-click="removeTask(task.id)">remove</button>

Please see this fiddle:

http://jsfiddle.net/JSWorld/Hp4W7/34/

How to edit incorrect commit message in Mercurial?

Update: Mercurial has added --amend which should be the preferred option now.


You can rollback the last commit (but only the last one) with hg rollback and then reapply it.

Important: this permanently removes the latest commit (or pull). So if you've done a hg update that commit is no longer in your working directory then it's gone forever. So make a copy first.

Other than that, you cannot change the repository's history (including commit messages), because everything in there is check-summed. The only thing you could do is prune the history after a given changeset, and then recreate it accordingly.

None of this will work if you have already published your changes (unless you can get hold of all copies), and you also cannot "rewrite history" that include GPG-signed commits (by other people).

Run jQuery function onclick

Why do you need to attach it to the HTML? Just bind the function with hover

$("div.system_box").hover(function(){ mousin }, 
                          function() { mouseout });

If you do insist to have JS references inside the html, which is usualy a bad idea you can use:

onmouseover="yourJavaScriptCode()"

after topic edit:

<div class="system_box" data-target="sms_box">

...

$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });

How to change value of ArrayList element in java

You're trying to change the value in the list, but all you're doing is changing the reference of x. Doing the following only changes x, not anything in the collection:

x = Integer.valueOf(9);

Additionally, Integer is immutable, meaning you can't change the value inside the Integer object (which would require a different method to do anyway). This means you need to replace the whole object. There is no way to do this with an Iterator (without adding your own layer of boxing). Do the following instead:

a.set(0, 9);

How to wait for the 'end' of 'resize' event and only then perform an action?

Here is VERY simple script to trigger both a 'resizestart' and 'resizeend' event on the window object.

There is no need to muck around with dates and times.

The d variable represents the number of milliseconds between resize events before triggering the resize end event, you can play with this to change how sensitive the end event is.

To listen to these events all you need to do is:

resizestart: $(window).on('resizestart', function(event){console.log('Resize Start!');});

resizeend: $(window).on('resizeend', function(event){console.log('Resize End!');});

(function ($) {
    var d = 250, t = null, e = null, h, r = false;

    h = function () {
        r = false;
        $(window).trigger('resizeend', e);
    };

    $(window).on('resize', function (event) {
        e = event || e;
        clearTimeout(t);

        if (!r) {
            $(window).trigger('resizestart', e);
            r = true;
        }

        t = setTimeout(h, d);
    });
}(jQuery));

Delete all local git branches

The 'git branch -d' subcommand can delete more than one branch. So, simplifying @sblom's answer but adding a critical xargs:

git branch -D `git branch --merged | grep -v \* | xargs`

or, further simplified to:

git branch --merged | grep -v \* | xargs git branch -D 

Importantly, as noted by @AndrewC, using git branch for scripting is discouraged. To avoid it use something like:

git for-each-ref --format '%(refname:short)' refs/heads | grep -v master | xargs git branch -D

Caution warranted on deletes!

$ mkdir br
$ cd br; git init
Initialized empty Git repository in /Users/ebg/test/br/.git/
$ touch README; git add README; git commit -m 'First commit'
[master (root-commit) 1d738b5] First commit
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README
$ git branch Story-123-a
$ git branch Story-123-b
$ git branch Story-123-c
$ git branch --merged
  Story-123-a
  Story-123-b
  Story-123-c
* master
$ git branch --merged | grep -v \* | xargs
Story-123-a Story-123-b Story-123-c
$ git branch --merged | grep -v \* | xargs git branch -D
Deleted branch Story-123-a (was 1d738b5).
Deleted branch Story-123-b (was 1d738b5).
Deleted branch Story-123-c (was 1d738b5).

lvalue required as left operand of assignment error when using C++

To assign, you should use p=p+1; instead of p+1=p;

int main()
{

   int x[3]={4,5,6};
   int *p=x;
   p=p+1; /*You just needed to switch the terms around*/
   cout<<p<<endl;
   getch();
}

Docker can't connect to docker daemon

I had the same problem - "Can't connect to docker daemon." (except I didn't get any 'file not found' errors on trying to start the server.)

'ps' showed that "/usr/bin/docker -d" was still running

I realised that I'd never actually succeeded in running the server myself though. Every attempt had produced

...
2014/03/24 21:57:29 pid file found, ensure docker is not running or delete /var/run/docker.pid

So I belatedly realised that installing docker had maybe registered the daemon with upstart, which had started it for me. Hence, trying to kill the daemon to manually restart it fails (operation not permitted). So I did a

sudo kill -9 <PID>

on the daemon process. Another daemon immediately took its place, and this new one DOES now let my CLI client connect:

$ sudo docker info
Containers: 0
Images: 0
Driver: aufs
 Root Dir: /var/lib/docker/aufs
 Dirs: 0
WARNING: No memory limit support
WARNING: No swap limit support

Javascript get object key name

An ES6 update... though both filter and map might need customization.

Object.entries(theObj) returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.

Saves a ton of work on iterating over parts of an object Object.keys(theObj), or Object.values() separately.

_x000D_
_x000D_
const buttons = {_x000D_
    button1: {_x000D_
        text: 'Close',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    },_x000D_
    button2: {_x000D_
        text: 'OK',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    },_x000D_
    button3: {_x000D_
        text: 'Cancel',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
list = Object.entries(buttons)_x000D_
    .filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options_x000D_
    .map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)_x000D_
    _x000D_
console.log(list)
_x000D_
_x000D_
_x000D_

How to install a certificate in Xcode (preparing for app store submission)

In Xcode 5 this has been moved to:

Xcode>Preferences>Accounts>View Details button>

setInterval in a React app

I see 4 issues with your code:

  • In your timer method you are always setting your current count to 10
  • You try to update the state in render method
  • You do not use setState method to actually change the state
  • You are not storing your intervalId in the state

Let's try to fix that:

componentDidMount: function() {
   var intervalId = setInterval(this.timer, 1000);
   // store intervalId in the state so it can be accessed later:
   this.setState({intervalId: intervalId});
},

componentWillUnmount: function() {
   // use intervalId from the state to clear the interval
   clearInterval(this.state.intervalId);
},

timer: function() {
   // setState method is used to update the state
   this.setState({ currentCount: this.state.currentCount -1 });
},

render: function() {
    // You do not need to decrease the value here
    return (
      <section>
       {this.state.currentCount}
      </section>
    );
}

This would result in a timer that decreases from 10 to -N. If you want timer that decreases to 0, you can use slightly modified version:

timer: function() {
   var newCount = this.state.currentCount - 1;
   if(newCount >= 0) { 
       this.setState({ currentCount: newCount });
   } else {
       clearInterval(this.state.intervalId);
   }
},

Flexbox: 4 items per row

I believe this example is more barebones and easier to understand then @dowomenfart.

.child {
    display: inline-block;
    margin: 0 1em;
    flex-grow: 1;
    width: calc(25% - 2em);
}

This accomplishes the same width calculations while cutting straight to the meat. The math is way easier and em is the new standard due to its scalability and mobile-friendliness.

How to install and run Typescript locally in npm?

As of npm 5.2.0, once you've installed locally via

npm i typescript --save-dev

...you no longer need an entry in the scripts section of package.json -- you can now run the compiler with npx:

npx tsc

Now you don't have to update your package.json file every time you want to compile with different arguments.

Enter export password to generate a P12 certificate

OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.

You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword to pass the password YourPassword from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.

Count number of occurences for each unique value

If you need to have the number of unique values as an additional column in the data frame containing your values (a column which may represent sample size for example), plyr provides a neat way:

data_frame <- data.frame(v = rep(c(1,2, 2, 2), 25))

library("plyr")
data_frame <- ddply(data_frame, .(v), transform, n = length(v))

how to get html content from a webview?

Android WebView is just another render engine that render HTML contents downloaded from a HTTP server, much like Chrome or FireFox. I don't know the reason why you need get the rendered page (or screenshot) from WebView. For most of situation, this is not necessary. You can always get the raw HTML content from HTTP server directly.

There are already answers posted talking about getting the raw stream using HttpUrlConnection or HttpClient. Alternatively, there is a very handy library when dealing with HTML content parse/process on Android: JSoup, it provide very simple API to get HTML contents form HTTP server, and provide an abstract representation of HTML document to help us manage HTML parsing not only in a more OO style but also much easily:

// Single line of statement to get HTML document from HTTP server.
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();

It is handy when, for example, you want to download HTML document first then add some custom css or javascript to it before passing it to WebView for rendering. Much more on their official web site, worth to check it out.

Using Git, show all commits that are in one branch, but not the other(s)

While some of the answers posted here will help find what you seek, the following sub-command of git branch is a more suitable solution for your task.

--merged is used to find all branches which can be safely deleted, since those branches are fully contained by HEAD.

While in master one could run the command to enumerate the branches one could safely remove, like so:

git branch --merged
  develop
  fpg_download_links
* master
  master_merge_static

# Delete local and remote tracking branches you don't want
git branch -d fpg_download_links
git push origin :fpg_download_links
git branch -d master_merge_static
git push origin :master_merge_static

# There is also a flag to specify remote branches in the output
git branch --remotes --merged

PHP string "contains"

PHP 8 or newer:

Use the str_contains function.

if (str_contains($str, "."))
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

PHP 7 or older:

if (strpos($str, '.') !== FALSE)
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

Note that you need to use the !== operator. If you use != or <> and the '.' is found at position 0, the comparison will evaluate to true because 0 is loosely equal to false.

How can I know which radio button is selected via jQuery?

If you have Multiple radio buttons in single form then

var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();

var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();

This is working for me.

OraOLEDB.Oracle provider is not registered on the local machine

Do the following test:

Open a Command Prompt and type: tnsping instance_name

where instance_name is the name of the instance you want to connect (if it's a XE database, use "tnsping xe"

If it returns ok, follow steps of Der Wolf's answer. If doesn't return ok, follow steps of Annjawn's answer.

It solved for me in both cases.

Converting a date in MySQL from string field

STR_TO_DATE allows you to do this, and it has a format argument.

Binding value to input in Angular JS

You don't need to set the value at all. ng-model takes care of it all:

  • set the input value from the model
  • update the model value when you change the input
  • update the input value when you change the model from js

Here's the fiddle for this: http://jsfiddle.net/terebentina/9mFpp/

What's the proper way to install pip, virtualenv, and distribute for Python?

There is no problem to do sudo python setup.py install, if you're sure it's what you want to do.

The difference is that it will use the site-packages directory of your OS as a destination for .py files to be copied.

so, if you want pip to be accessible os wide, that's probably the way to go. I do not say that others way are bad, but this is probably fair enough.

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

Plot width settings in ipython notebook

If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:

width = 12
height = 12
plt.figure(figsize=(width, height))

How to prevent rm from reporting that a file was not found?

As far as rm -f doing "anything else", it does force (-f is shorthand for --force) silent removal in situations where rm would otherwise ask you for confirmation. For example, when trying to remove a file not writable by you from a directory that is writable by you.

Match all elements having class name starting with a specific string

It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:

<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>

In this way you can set rules for all myclass elements and then more specific rules for one, two and three.

.myclass { color: #f00; }

.two { font-weight: bold; }

etc.

Apply vs transform on a group object

I am going to use a very simple snippet to illustrate the difference:

test = pd.DataFrame({'id':[1,2,3,1,2,3,1,2,3], 'price':[1,2,3,2,3,1,3,1,2]})
grouping = test.groupby('id')['price']

The DataFrame looks like this:

    id  price   
0   1   1   
1   2   2   
2   3   3   
3   1   2   
4   2   3   
5   3   1   
6   1   3   
7   2   1   
8   3   2   

There are 3 customer IDs in this table, each customer made three transactions and paid 1,2,3 dollars each time.

Now, I want to find the minimum payment made by each customer. There are two ways of doing it:

  1. Using apply:

    grouping.min()

The return looks like this:

id
1    1
2    1
3    1
Name: price, dtype: int64

pandas.core.series.Series # return type
Int64Index([1, 2, 3], dtype='int64', name='id') #The returned Series' index
# lenght is 3
  1. Using transform:

    grouping.transform(min)

The return looks like this:

0    1
1    1
2    1
3    1
4    1
5    1
6    1
7    1
8    1
Name: price, dtype: int64

pandas.core.series.Series # return type
RangeIndex(start=0, stop=9, step=1) # The returned Series' index
# length is 9    

Both methods return a Series object, but the length of the first one is 3 and the length of the second one is 9.

If you want to answer What is the minimum price paid by each customer, then the apply method is the more suitable one to choose.

If you want to answer What is the difference between the amount paid for each transaction vs the minimum payment, then you want to use transform, because:

test['minimum'] = grouping.transform(min) # ceates an extra column filled with minimum payment
test.price - test.minimum # returns the difference for each row

Apply does not work here simply because it returns a Series of size 3, but the original df's length is 9. You cannot integrate it back to the original df easily.

Getting the thread ID from a thread

To get the OS ID use:

AppDomain.GetCurrentThreadId()

How do I discard unstaged changes in Git?

As you type git status, (use "git checkout -- ..." to discard changes in working directory) is shown.

e.g. git checkout -- .

How to log a method's execution time exactly in milliseconds?

An example of fine-grained timing using mach_absolute_time() in Swift 4:

let start = mach_absolute_time()

// do something

let elapsedMTU = mach_absolute_time() - start
var timebase = mach_timebase_info()
if mach_timebase_info(&timebase) == 0 {
    let elapsed = Double(elapsedMTU) * Double(timebase.numer) / Double(timebase.denom)
    print("render took \(elapsed)")
}
else {
    print("timebase error")
}

The entity name must immediately follow the '&' in the entity reference

If you use XHTML, for some reason, note that XHTML 1.0 C 4 says: “Use external scripts if your script uses < or & or ]]> or --.” That is, don’t embed script code inside a script element but put it into a separate JavaScript file and refer to it with <script src="foo.js"></script>.

VBA - Select columns using numbers?

You can use resize like this:

For n = 1 To 5
    Columns(n).Resize(, 5).Select
    '~~> rest of your code
Next

In any Range Manipulation that you do, always keep at the back of your mind Resize and Offset property.

Avoid printStackTrace(); use a logger call instead

If you call printStackTrace() on an exception the trace is written to System.err and it's hard to route it elsewhere (or filter it). Instead of doing this you are adviced to use a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.error("some exception message", e)).

Doing that allows you to:

  • write the log statement to different locations at once, e.g. the console and a file
  • filter the log statements by severity (error, warning, info, debug etc.) and origin (normally package or class based)
  • have some influence on the log format without having to change the code
  • etc.

Rounding Bigdecimal values with 2 Decimal Places

Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)

Code example:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
    BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(b);
}

DataGridView.Clear()

I don't like messing with the DataSource personally so after discussing the issue with an IT friend I was able to discover this way which is simple and doesn't effect the DataSource. Hope this helps!

foreach (DataGridViewRow row in dataGridView1.Rows) 
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        cell.Value = "";
    }
}

Get the row(s) which have the max value in groups using groupby

Easy solution would be to apply : idxmax() function to get indices of rows with max values. This would filter out all the rows with max value in the group.

In [365]: import pandas as pd

In [366]: df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})

In [367]: df                                                                                                       
Out[367]: 
   count  mt   sp  val
0      3  S1  MM1    a
1      2  S1  MM1    n
2      5  S3  MM1   cb
3      8  S3  MM2   mk
4     10  S4  MM2   bg
5      1  S4  MM2  dgb
6      2  S2  MM4   rd
7      2  S2  MM4   cb
8      7  S2  MM4  uyi


### Apply idxmax() and use .loc() on dataframe to filter the rows with max values:
In [368]: df.loc[df.groupby(["sp", "mt"])["count"].idxmax()]                                                       
Out[368]: 
   count  mt   sp  val
0      3  S1  MM1    a
2      5  S3  MM1   cb
3      8  S3  MM2   mk
4     10  S4  MM2   bg
8      7  S2  MM4  uyi

### Just to show what values are returned by .idxmax() above:
In [369]: df.groupby(["sp", "mt"])["count"].idxmax().values                                                        
Out[369]: array([0, 2, 3, 4, 8])

Get value from text area

use the val() method:

$(document).ready(function () {
    var j = $("textarea");
    if (j.val().length > 0) {
        alert(j.val());
    }
});

Twig ternary operator, Shorthand if-then-else

{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

How to write "not in ()" sql query using join

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

Android Fragment onAttach() deprecated

you are probably using android.support.v4.app.Fragment. For this instead of onAttach method, just use getActivity() to get the FragmentActivity with which the fragment is associated with. Else you could use onAttach(Context context) method.

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Java: Calling a super method which calls an overridden method

During my research for a similar case, I have been ending up by checking the stack trace in the subclass method to find out from where the call is coming from. There are probably smarter ways to do so, but it works out for me and it's a dynamic approach.

public void method2(){
        Exception ex=new Exception();
        StackTraceElement[] ste=ex.getStackTrace();
        if(ste[1].getClassName().equals(this.getClass().getSuperclass().getName())){
            super.method2();
        }
        else{
            //subclass method2 code
        }
}

I think the question to have a solution for the case is reasonable. There are of course ways to solve the issue with different method names or even different parameter types, like already mentioned in the thread, but in my case I dindn't like to confuse by different method names.

Right Align button in horizontal LinearLayout

I know this question was asked awhile ago, but I have done this before and it allows for more control when aligning items.If you look at it like web programming, it helps. You just nest another LinearLayout that will contain your button inside of it. You can then change the gravity of the button's layout and make it go to the right while the TextView is still on the left.

Try this code:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"             
android:orientation="horizontal" 
android:layout_marginTop="35dp">

<TextView
    android:id="@+id/lblExpenseCancel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/cancel" 
    android:textColor="#404040"         
    android:layout_marginLeft="10dp" 
    android:textSize="20sp" 
    android:layout_marginTop="9dp"/>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="right"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/btnAddExpense"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:background="@drawable/stitch_button"
        android:layout_marginLeft="10dp"                    
        android:text="@string/add" 
        android:layout_gravity="right" 
        android:layout_marginRight="15dp"/>

</LinearLayout>

You may have to play with the padding on the nested layout so that it acts how you want it.

Inserting a blank table row with a smaller height

I wanted to achieve the same as asked in this question but accepted answer did not work for me in May, 2018 (maybe answer is too old or some other reason). I am using bootsrap 3.3.7 and ionic v1. You need to set line-height to do set height of specific row.

_x000D_
_x000D_
.blank_row {_x000D_
  line-height: 3px;_x000D_
}
_x000D_
<table class="action_table">_x000D_
  <tbody>_x000D_
    <tr class="header_row">_x000D_
      <td>Header Item</td>_x000D_
      <td>Header Item 2</td>_x000D_
      <td>Header Item 3</td>_x000D_
    </tr>_x000D_
    <tr class="blank_row">_x000D_
      <td bgcolor="#000" colspan="3">&nbsp;</td>_x000D_
    </tr>_x000D_
    <tr class="data_row">_x000D_
      <td>Data Item</td>_x000D_
      <td>Data Item 2</td>_x000D_
      <td>Data Item 3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I return NULL from a generic method in C#?

solution of TheSoftwareJedi works,

also you can archive it with using couple of value and nullable types:

static T? FindThing<T>(IList collection, int id) where T : struct, IThing
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return thing;
    }
    return null;
}

JavaScript, getting value of a td with id name

Have you tried: getElementbyId('ID_OF_ID').innerHTML?

What is the easiest way to remove the first character from a string?

Ruby 2.5+

As of Ruby 2.5 you can use delete_prefix or delete_prefix! to achieve this in a readable manner.

In this case "[12,23,987,43".delete_prefix("[").

More info here:

'invisible'.delete_prefix('in') #=> "visible"
'pink'.delete_prefix('in') #=> "pink"

N.B. you can also use this to remove items from the end of a string with delete_suffix and delete_suffix!

'worked'.delete_suffix('ed') #=> "work"
'medical'.delete_suffix('ed') #=> "medical"

Edit:

Using the Tin Man's benchmark setup, it looks pretty quick too (under the last two entries delete_p and delete_p!). Doesn't quite pip the previous faves for speed, though is very readable.

2.5.0
              user     system      total        real
[0]       0.174766   0.000489   0.175255 (  0.180207)
[/^./]    0.318038   0.000510   0.318548 (  0.323679)
[/^\[/]   0.372645   0.001134   0.373779 (  0.379029)
sub+      0.460295   0.001510   0.461805 (  0.467279)
sub       0.498351   0.001534   0.499885 (  0.505729)
gsub      1.669837   0.005141   1.674978 (  1.682853)
[1..-1]   0.199840   0.000976   0.200816 (  0.205889)
slice     0.279661   0.000859   0.280520 (  0.285661)
length    0.268362   0.000310   0.268672 (  0.273829)
eat!      0.341715   0.000524   0.342239 (  0.347097)
reverse   0.335301   0.000588   0.335889 (  0.340965)
delete_p  0.222297   0.000832   0.223129 (  0.228455)
delete_p!  0.225798   0.000747   0.226545 (  0.231745)

Ping with timestamp on Windows CLI

WindowsPowershell:

option 1

ping.exe -t COMPUTERNAME|Foreach{"{0} - {1}" -f (Get-Date),$_}

option 2

Test-Connection -Count 9999 -ComputerName COMPUTERNAME | Format-Table @{Name='TimeStamp';Expression={Get-Date}},Address,ProtocolAddress,ResponseTime

Pass data to layout that are common to all pages

I used RenderAction html helper for razor in layout.

@{
   Html.RenderAction("Action", "Controller");
 }

I needed it for simple string. So my action returns string and writes it down easy in view. But if you need complex data you can return PartialViewResult and model.

 public PartialViewResult Action()
    {
        var model = someList;
        return PartialView("~/Views/Shared/_maPartialView.cshtml", model);
    }

You just need to put your model begining of the partial view '_maPartialView.cshtml' that you created

@model List<WhatEverYourObjeIs>

Then you can use data in the model in that partial view with html.

How to change onClick handler dynamically?

If you want to pass variables from the current function, another way to do this is, for example:

document.getElementById("space1").onclick = new Function("lrgWithInfo('"+myVar+"')");

If you don't need to pass information from this function, it's just:

document.getElementById("space1").onclick = new Function("lrgWithInfo('13')");

Check if $_POST exists

Everyone is saying to use isset() - which will probably work for you.

However, it's important that you understand the difference between

$_POST['x'] = NULL; and $_POST['x'] = '';

isset($_POST['x']) will return false on the first example, but will return true on the second one even though if you tried to print either one, both would return a blank value.

If your $_POST is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.

Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.

How can I install packages using pip according to the requirements.txt file from a local directory?

Installing requirements.txt file inside virtual env with Python 3:

I had the same issue. I was trying to install the requirements.txt file inside a virtual environment. I found the solution.

Initially, I created my virtualenv in this way:

virtualenv -p python3 myenv

Activate the environment using:

source myenv/bin/activate

Now I installed the requirements.txt file using:

pip3 install -r requirements.txt

Installation was successful and I was able to import the modules.

SQL LIKE condition to check for integer?

Which one of those is indexable?

This one is definitely btree-indexable:

WHERE title >= '0' AND title < ':'

Note that ':' comes after '9' in ASCII.

WHERE clause on SQL Server "Text" data type

This works in MSSQL and MySQL:

SELECT *
FROM   Village
WHERE  CastleType LIKE '%foo%'; 

Getting the ID of the element that fired an event

this.element.attr("id") works fine in IE8.

What is the difference between MVC and MVVM?

Model–View–Controller (usually known as MVC) is a software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted by the user. Following the MVC architectural pattern decouples these major components allowing for code reuse and parallel development.

Traditionally used for desktop graphical user interfaces (GUIs), this pattern has become popular for designing web applications. Popular programming languages like JavaScript, Python, Ruby, PHP, Java, and C# have MVC frameworks that are used in web application development straight out of the box.

Model

The central component of the pattern. It is the application's dynamic data structure, independent of the user interface. It directly manages the data, logic, and rules of the application.

View

Any representation of information such as a chart, diagram or table. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.

Controller

Accepts input and converts it to commands for the model or view.

In addition to dividing the application into these components, the model–view–controller design defines the interactions between them.

The model is responsible for managing the data of the application. It receives user input from the controller.

The view means a presentation of the model in a particular format.

The controller responds to the user input and performs interactions on the data model objects. The controller receives the input, optionally validates it and then passes the input to the model. enter image description here

Model–View–ViewModel (MVVM) is a software architectural pattern.

MVVM facilitates a separation of development of the graphical user interface – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the data model). The view model of MVVM is a value converter, meaning the view model is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented. In this respect, the view model is more model than a view and handles most if not all of the view's display logic. The view model may implement a mediator pattern, organizing access to the back-end logic around the set of use cases supported by the view.

MVVM is a variation of Martin Fowler's Presentation Model design pattern. MVVM abstracts a view's state and behavior in the same way, but a Presentation Model abstracts a view (creates a view model) in a manner not dependent on a specific user-interface platform.

MVVM was invented by Microsoft architects Ken Cooper and Ted Peters specifically to simplify event-driven programming of user interfaces. The pattern was incorporated into Windows Presentation Foundation (WPF) (Microsoft's .NET graphics system) and Silverlight (WPF's Internet application derivative). John Gossman, one of Microsoft's WPF and Silverlight architects, announced MVVM on his blog in 2005.

Model–View–ViewModel is also referred to as model–view–binder, especially in implementations not involving the .NET platform. ZK (a web application framework written in Java) and KnockoutJS (a JavaScript library) use model–view–binder. enter image description here

How do I split an int into its digits?

Reversed order digit extractor (eg. for 23 will be 3 and 2):

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    //print digit
}

Normal order digit extractor (eg. for 23 will be 2 and 3):

std::stack<int> sd;

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    sd.push(digit);
}

while (!sd.empty())
{
    int digit = sd.top();
    sd.pop();
    //print digit
}

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

I had similar issue. I was not able to use value="something" to display and edit. I had to use the below command inside my <input>along withe ng model being declared.

[(ngModel)]=userDataToPass.pinCode

Where I have the list of data in the object userDataToPass and the item that I need to display and edit is pinCode.

For the same , I referred to this YouTube video

"for loop" with two variables?

There's two possible questions here: how can you iterate over those variables simultaneously, or how can you loop over their combination.

Fortunately, there's simple answers to both. First case, you want to use zip.

x = [1, 2, 3]
y = [4, 5, 6]

for i, j in zip(x, y):
   print(str(i) + " / " + str(j))

will output

1 / 4
2 / 5
3 / 6

Remember that you can put any iterable in zip, so you could just as easily write your exmple like:

for i, j in zip(range(x), range(y)):
    # do work here.

Actually, just realised that won't work. It would only iterate until the smaller range ran out. In which case, it sounds like you want to iterate over the combination of loops.

In the other case, you just want a nested loop.

for i in x:
    for j in y:
        print(str(i) + " / " + str(j))

gives you

1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...

You can also do this as a list comprehension.

[str(i) + " / " + str(j) for i in range(x) for j in range(y)]

Hope that helps.

Javascript replace with reference to matched group?

You can use replace instead of gsub.

"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

This was good enough for me

sudo /etc/init.d/mysql restart

Convert pandas DataFrame into list of lists

you can do it like this:

map(list, df.values)

How to append multiple items in one line in Python

use for loop. like this:

for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
    new_list.append(my_list[i + x])

HTML input file selection event not firing upon selecting the same file

In this article, under the title "Using form input for selecting"

http://www.html5rocks.com/en/tutorials/file/dndfiles/

<input type="file" id="files" name="files[]" multiple />

<script>
function handleFileSelect(evt) {

    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
     // Code to execute for every file selected
    }
    // Code to execute after that

}

document.getElementById('files').addEventListener('change', 
                                                  handleFileSelect, 
                                                  false);
</script>

It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.

How do you attach and detach from Docker's process?

For anyone who ran into the same problem I did (can't detach without killing the container, even when setting the detach key)......

When starting your containers with docker-compose up -d

instead of using docker attach {container name} to view the tailing log ....

try docker-compose logs -f {service name} ctrl-c kills the log tail without killing your container

{service name} being the service listed in side of your docker-compose.yml file.. (e.g. while container name=elk_logstash_1 -> service name=logstash

HTH

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

From my testing Write-Output and [Console]::WriteLine() perform much better than Write-Host.

Depending on how much text you need to write out this may be important.

Below if the result of 5 tests each for Write-Host, Write-Output and [Console]::WriteLine().

In my limited experience, I've found when working with any sort of real world data I need to abandon the cmdlets and go straight for the lower level commands to get any decent performance out of my scripts.

measure-command {$count = 0; while ($count -lt 1000) { Write-Host "hello"; $count++ }}

1312ms
1651ms
1909ms
1685ms
1788ms


measure-command { $count = 0; while ($count -lt 1000) { Write-Output "hello"; $count++ }}

97ms
105ms
94ms
105ms
98ms


measure-command { $count = 0; while ($count -lt 1000) { [console]::WriteLine("hello"); $count++ }}

158ms
105ms
124ms
99ms
95ms

How to fluently build JSON in Java?

I recently created a library for creating Gson objects fluently:

http://jglue.org/fluent-json/

It works like this:

  JsonObject jsonObject = JsonBuilderFactory.buildObject() //Create a new builder for an object
  .addNull("nullKey")                            //1. Add a null to the object

  .add("stringKey", "Hello")                     //2. Add a string to the object
  .add("stringNullKey", (String) null)           //3. Add a null string to the object

  .add("numberKey", 2)                           //4. Add a number to the object
  .add("numberNullKey", (Float) null)            //5. Add a null number to the object

  .add("booleanKey", true)                       //6. Add a boolean to the object
  .add("booleanNullKey", (Boolean) null)         //7. Add a null boolean to the object

  .add("characterKey", 'c')                      //8. Add a character to the object
  .add("characterNullKey", (Character) null)     //9. Add a null character to the object

  .addObject("objKey")                           //10. Add a nested object
    .add("nestedPropertyKey", 4)                 //11. Add a nested property to the nested object
    .end()                                       //12. End nested object and return to the parent builder

  .addArray("arrayKey")                          //13. Add an array to the object
    .addObject()                                 //14. Add a nested object to the array
      .end()                                     //15. End the nested object
    .add("arrayElement")                         //16. Add a string to the array
    .end()                                       //17. End the array

    .getJson();                                  //Get the JsonObject

String json = jsonObject.toString();

And through the magic of generics it generates compile errors if you try to add an element to an array with a property key or an element to an object without a property name:

JsonObject jsonArray = JsonBuilderFactory.buildArray().addObject().end().add("foo", "bar").getJson(); //Error: tried to add a string with property key to array.
JsonObject jsonObject = JsonBuilderFactory.buildObject().addArray().end().add("foo").getJson(); //Error: tried to add a string without property key to an object.
JsonArray jsonArray = JsonBuilderFactory.buildObject().addArray("foo").getJson(); //Error: tried to assign an object to an array.
JsonObject jsonObject = JsonBuilderFactory.buildArray().addObject().getJson(); //Error: tried to assign an object to an array.

Lastly there is mapping support in the API which allows you to map your domain objects to JSON. The goal being when Java8 is released you'll be able to do something like this:

Collection<User> users = ...;
JsonArray jsonArray = JsonBuilderFactory.buildArray(users, { u-> buildObject()
                                                                 .add("userName", u.getName())
                                                                 .add("ageInYears", u.getAge()) })
                                                                 .getJson();

Get Application Directory

If you're trying to get access to a file, try the openFileOutput() and openFileInput() methods as described here. They automatically open input/output streams to the specified file in internal memory. This allows you to bypass the directory and File objects altogether which is a pretty clean solution.

@property retain, assign, copy, nonatomic in Objective-C

Atomic property can be accessed by only one thread at a time. It is thread safe. Default is atomic .Please note that there is no keyword atomic

Nonatomic means multiple thread can access the item .It is thread unsafe

So one should be very careful while using atomic .As it affect the performance of your code

Looping through all the properties of object php

Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)

How to get package name from anywhere?

If you use the gradle-android-plugin to build your app, then you can use

BuildConfig.APPLICATION_ID

to retrieve the package name from any scope, incl. a static one.

CSS text-align not working

You have to make the UL inside the div behave like a block. Try adding

.navigation ul {
     display: inline-block;
}

Making a cURL call in C#

Well if you are new to C# with cmd-line exp. you can use online sites like "https://curl.olsh.me/" or search curl to C# converter will returns site that could do that for you.

or if you are using postman you can use Generate Code Snippet only problem with Postman code generator is the dependency on RestSharp library.

How to bring back "Browser mode" in IE11?

In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good

How to remove element from ArrayList by checking its value?

Try below code :

 public static void main(String[] args) throws Exception{
     List<String> l = new ArrayList<String>();
     l.add("abc");
     l.add("xyz");
     l.add("test");
     l.add("test123");
     System.out.println(l);
     List<String> dl = new ArrayList<String>();
    for (int i = 0; i < l.size(); i++) {
         String a = l.get(i);
         System.out.println(a); 
         if(a.equals("test")){
             dl.add(a);
         }
    }
    l.removeAll(dl);
     System.out.println(l); 
}

your output :

 [abc, xyz, test, test123]
abc
xyz
test
test123
[abc, xyz, test123]

SQL Call Stored Procedure for each Row without using a cursor

Marc's answer is good (I'd comment on it if I could work out how to!)
Just thought I'd point out that it may be better to change the loop so the SELECT only exists once (in a real case where I needed to do this, the SELECT was quite complex, and writing it twice was a risky maintenance issue).

-- define the last customer ID handled
DECLARE @LastCustomerID INT
SET @LastCustomerID = 0
-- define the customer ID to be handled now
DECLARE @CustomerIDToHandle INT
SET @CustomerIDToHandle = 1

-- as long as we have customers......    
WHILE @LastCustomerID <> @CustomerIDToHandle
BEGIN  
  SET @LastCustomerId = @CustomerIDToHandle
  -- select the next customer to handle    
  SELECT TOP 1 @CustomerIDToHandle = CustomerID
  FROM Sales.Customer
  WHERE CustomerID > @LastCustomerId 
  ORDER BY CustomerID

  IF @CustomerIDToHandle <> @LastCustomerID
  BEGIN
      -- call your sproc
  END

END

Onclick on bootstrap button

Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:

$('#myButton').on('click', function(event) {
  event.preventDefault(); // To prevent following the link (optional)
  ...
});

You can also use inline javascript in the onclick attribute:

<a ... onclick="myFunc();">..</a>

How can I change the remote/target repository URL on Windows?

The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.

On my machine in a repo I regularly use it looks like this:

KidA% cat .git/config 
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    autocflg = true
[remote "origin"]
    url = ssh://localhost:8888/opt/local/var/git/project.git
    #url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git
    fetch = +refs/heads/*:refs/remotes/origin/*

The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.

This is the file that is getting manipulated under-the-hood when you run something like git remote rm or git remote add but in this case since its only a typo you made it might make sense to correct it this way.

Wait .5 seconds before continuing code VB.net

This question is old but here is another answer because it is useful fo others:

thread.sleep is not a good method for waiting, because usually it freezes the software until finishing its time, this function is better:

   Imports VB = Microsoft.VisualBasic

   Public Sub wait(ByVal seconds As Single)
     Static start As Single
     start = VB.Timer()
     Do While VB.Timer() < start + seconds
       System.Windows.Forms.Application.DoEvents()
     Loop
   End Sub

The above function waits for a specific time without freezing the software, however increases the CPU usage.

This function not only doesn't freeze the software, but also doesn't increase the CPU usage:

   Private Sub wait(ByVal seconds As Integer)
     For i As Integer = 0 To seconds * 100
       System.Threading.Thread.Sleep(10)
       Application.DoEvents()
     Next
   End Sub

Get remote registry value

another option ... needs remoting ...

(invoke-command -ComputerName mymachine -ScriptBlock {Get-ItemProperty HKLM:\SOFTWARE\VanDyke\VShell\License -Name Version }).version

PHP mkdir: Permission denied problem

If you'r using LINUX, first let's check apache's user, since in some distros it can be different:

egrep -i '^user|^group' /etc/httpd/conf/httpd.conf 

Let's say the result is "http". Do the folowwing, just remember change path_to_folder to folders path:

chown -R http:http path_to_folder
chmod -R g+rw path_to_folder

Visualizing branch topology in Git

Gitg is a great tool for Linux, similar to Gitx for OS X. Just run 'gitg' on the command line from somewhere inside your repository's tree structure (same with gitx).

Practical uses for AtomicInteger

Simple example for compareAndSet() function:

import java.util.concurrent.atomic.AtomicInteger; 

public class GFG { 
    public static void main(String args[]) 
    { 

        // Initially value as 0 
        AtomicInteger val = new AtomicInteger(0); 

        // Prints the updated value 
        System.out.println("Previous value: "
                           + val); 

        // Checks if previous value was 0 
        // and then updates it 
        boolean res = val.compareAndSet(0, 6); 

        // Checks if the value was updated. 
        if (res) 
            System.out.println("The value was"
                               + " updated and it is "
                           + val); 
        else
            System.out.println("The value was "
                               + "not updated"); 
      } 
  } 

The printed is: previous value: 0 The value was updated and it is 6 Another simple example:

    import java.util.concurrent.atomic.AtomicInteger; 

public class GFG { 
    public static void main(String args[]) 
    { 

        // Initially value as 0 
        AtomicInteger val 
            = new AtomicInteger(0); 

        // Prints the updated value 
        System.out.println("Previous value: "
                           + val); 

         // Checks if previous value was 0 
        // and then updates it 
        boolean res = val.compareAndSet(10, 6); 

          // Checks if the value was updated. 
          if (res) 
            System.out.println("The value was"
                               + " updated and it is "
                               + val); 
        else
            System.out.println("The value was "
                               + "not updated"); 
    } 
} 

The printed is: Previous value: 0 The value was not updated

How to add a class to a given element?

In YUI, if you include yuidom, you can use

YAHOO.util.Dom.addClass('div1','className');

HTH

How to scroll to the bottom of a UITableView on the iPhone before the view appears

On iOS 12 the accepted answer seems to be broken. I had it working with the following extension



import UIKit

extension UITableView {
    public func scrollToBottom(animated: Bool = true) {
        guard let dataSource = dataSource else {
            return
        }

        let sections = dataSource.numberOfSections?(in: self) ?? 1
        let rows = dataSource.tableView(self, numberOfRowsInSection: sections-1)
        let bottomIndex = IndexPath(item: rows - 1, section: sections - 1)

        scrollToRow(at: bottomIndex,
                    at: .bottom,
                    animated: animated)
    }
}

Pointers in JavaScript?

I'm thinking that in contrary to C or any language with pointers :

/** Javascript **/
var o = {x:10,y:20};
var o2 = {z:50,w:200};
  • obviously in javascript you cannot access to objects o and o2 addresses in memory
  • but you can't compare their address neither : (no trivial possibility to sort them, and then access by dichotomy)

.

o == o2 // obviously false : not the same address in memory
o <= o2 // true !
o >= o2 // also true !!

that's a huge problem :

  • it means that you can list/manage every objects created (allocated) by your application,

  • from that huge list of objects, compute some information about these (how they are linked together for example)

  • but when you want to retrieve the information you created about a specific object, you cannot find it in your huge list by dichotomy : there is no unique identifier per object that could be used as a replacement of the real memory address

this finally means that this is a huge problem, if you want to write in javascript :

  • a javascript debugger / IDE
  • or a specially optimized garbage collector
  • a data structure drawer / analyzer

Programmatically shut down Spring Boot application

This will make sure that the SpringBoot application is closed properly and the resources are released back to the operating system,

@Autowired
private ApplicationContext context;

@GetMapping("/shutdown-app")
public void shutdownApp() {

    int exitCode = SpringApplication.exit(context, (ExitCodeGenerator) () -> 0);
    System.exit(exitCode);
}

Set android shape color programmatically

A simpler solution nowadays would be to use your shape as a background and then programmatically change its color via:

view.background.setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_ATOP)

See PorterDuff.Mode for the available options.

UPDATE (API 29):

The above method is deprecated since API 29 and replaced by the following:

view.background.colorFilter = BlendModeColorFilter(Color.parseColor("#343434"), BlendMode.SRC_ATOP)

See BlendMode for the available options.

Best way to get application folder path

Note that not all of these methods will return the same value. In some cases, they can return the same value, but be careful, their purposes are different:

Application.StartupPath

returns the StartupPath parameter (can be set when run the application)

System.IO.Directory.GetCurrentDirectory()

returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).

How to check if a scope variable is undefined in AngularJS template?

As @impulsgraw wrote. You need to check for undefined after the pipes:

<div ng-show="foo || undefined">
    Show this if foo is defined!
</div>
<div ng-show="boo || !undefined">
    Show this if boo is undefined!
</div>

https://jsfiddle.net/mjfz2q9h/11/

PHP DOMDocument loadHTML not encoding UTF-8 correctly

You must feed the DOMDocument a version of your HTML with a header that make sense. Just like HTML5.

$profile ='<?xml version="1.0" encoding="'.$_encoding.'"?>'. $html;

maybe is a good idea to keep your html as valid as you can, so you don't get into issues when you'll start query... around :-) and stay away from htmlentities!!!! That's an an necessary back and forth wasting resources. keep your code insane!!!!

How to render html with AngularJS templates

In angular 4+ we can use innerHTML property instead of ng-bind-html.

In my case, it's working and I am using angular 5.

<div class="chart-body" [innerHTML]="htmlContent"></div>

In.ts file

let htmlContent = 'This is the `<b>Bold</b>` text.';

How do I reformat HTML code using Sublime Text 2?

For me, the HTML Prettify solution was extremely simple. I went to the HTML Prettify page.

  1. Needed the Sublime Package Manager
  2. Followed the Instructions for installing the package manager here
  3. typed cmd + shift + p to bring up the menu
  4. Typed prettify
  5. Chose the HTML prettify selection in the menu

Boom. Done. Looks great

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

Jonathon gave you an approach using dict comprehensions in his answer. Here is an approach that deals with your do something part.

If you want to do something with the values of the dictionary, you don't need a dictionary comprehension at all:

I'm using iteritems() since you tagged your question with

results = map(some_function, [(k,v) for k,v in a_dict.iteritems() if 'foo' in k])

Now the result will be in a list with some_function applied to each key/value pair of the dictionary, that has foo in its key.

If you just want to deal with the values and ignore the keys, just change the list comprehension:

results = map(some_function, [v for k,v in a_dict.iteritems() if 'foo' in k])

some_function can be any callable, so a lambda would work as well:

results = map(lambda x: x*2, [v for k,v in a_dict.iteritems() if 'foo' in k])

The inner list is actually not required, as you can pass a generator expression to map as well:

>>> map(lambda a: a[0]*a[1], ((k,v) for k,v in {2:2, 3:2}.iteritems() if k == 2))
[4]

How to install gem from GitHub source?

Bundler allows you to use gems directly from git repositories. In your Gemfile:

# Use the http(s), ssh, or git protocol
gem 'foo', git: 'https://github.com/dideler/foo.git'
gem 'foo', git: '[email protected]:dideler/foo.git'
gem 'foo', git: 'git://github.com/dideler/foo.git'

# Specify a tag, ref, or branch to use
gem 'foo', git: '[email protected]:dideler/foo.git', tag: 'v2.1.0'
gem 'foo', git: '[email protected]:dideler/foo.git', ref: '4aded'
gem 'foo', git: '[email protected]:dideler/foo.git', branch: 'development'

# Shorthand for public repos on GitHub (supports all the :git options)
gem 'foo', github: 'dideler/foo'

For more info, see https://bundler.io/v2.0/guides/git.html

java.net.SocketTimeoutException: Read timed out under Tomcat

Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.

Correct.

Client has a read timeout set, and server is taking longer than that to respond.

No. That would cause a timeout at the client.

One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.

That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.

It just means the client isn't sending. You don't need to worry about it. Browser clients come and go in all sorts of strange ways.

data.frame rows to a list

An alternative way is to convert the df to a matrix then applying the list apply lappy function over it: ldf <- lapply(as.matrix(myDF), function(x)x)

How to find out line-endings in a text file?

I dump my output to a text file. I then open it in notepad ++ then click the show all characters button. Not very elegant but it works.

Tomcat view catalina.out log file

 cd /usr/local/tomcat/logs
 tail -f catalina.out

What is the use of style="clear:both"?

When you use float without width, there remains some space in that row. To block this space you can use clear:both; in next element.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

Making a Simple Ajax call to controller in asp.net mvc

Remove the data attribute as you are not POSTING anything to the server (Your controller does not expect any parameters).

And in your AJAX Method you can use Razor and use @Url.Action rather than a static string:

$.ajax({
    url: '@Url.Action("FirstAjax", "AjaxTest")',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: successFunc,
    error: errorFunc
});

From your update:

$.ajax({
    type: "POST",
    url: '@Url.Action("FirstAjax", "AjaxTest")',
    contentType: "application/json; charset=utf-8",
    data: { a: "testing" },
    dataType: "json",
    success: function() { alert('Success'); },
    error: errorFunc
});

href around input type submit

Place the link location in the action="" of a wrapping form tag.

Your first link would be:

<form action="1.html">
    <input type="submit" class="button_active" value="1">
</form>

Cannot connect to MySQL 4.1+ using old authentication

If you do not have control of the server

I just had this issue, and was able to work around it.

First, connect to the MySQL database with an older client that doesn't mind old_passwords. Connect using the user that your script will be using.

Run these queries:

SET SESSION old_passwords=FALSE;
SET PASSWORD = PASSWORD('[your password]');

In your PHP script, change your mysql_connect function to include the client flag 1:

define('CLIENT_LONG_PASSWORD', 1);
mysql_connect('[your server]', '[your username]', '[your password]', false, CLIENT_LONG_PASSWORD);

This allowed me to connect successfully.

Edit: as per Garland Pope's comment, it may not be necessary to set CLIENT_LONG_PASSWORD manually any more in your PHP code as of PHP 5.4!

Edit: courtesy of Antonio Bonifati, a PHP script to run the queries for you:

<?php const DB = [ 'host' => '...', # localhost may not work on some hosting 
    'user' => '...',
    'pwd' => '...', ]; 

if (!mysql_connect(DB['host'], DB['user'], DB['pwd'])) {
    die(mysql_error());
} if (!mysql_query($query = 'SET SESSION old_passwords=FALSE')) {
    die($query);
} if (!mysql_query($query = "SET PASSWORD = PASSWORD('" . DB['pwd'] . "')")) {
    die($query);
}

echo "Excellent, mysqli will now work"; 
?>

Why is vertical-align: middle not working on my span or div?

In case you cannot rely on flexbox... Place .child into .parent's center. Works when pixel sizes are unknown (in other words, always) and no problems with IE9+ too.

_x000D_
_x000D_
.parent { position: relative; }_x000D_
_x000D_
.child {_x000D_
    position: absolute;_x000D_
    top : 50%;_x000D_
    left: 50%;_x000D_
    -ms-transform: translate(-50%, -50%);_x000D_
    transform    : translate(-50%, -50%);    _x000D_
}
_x000D_
<div class="parent" style="background:lightyellow; padding:6em"> _x000D_
  <div class="child" style="background:gold; padding:1em">&mdash;</div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Java AES and using my own Key

Edit:

As written in the comments the old code is not "best practice". You should use a keygeneration algorithm like PBKDF2 with a high iteration count. You also should use at least partly a non static (meaning for each "identity" exclusive) salt. If possible randomly generated and stored together with the ciphertext.

    SecureRandom sr = SecureRandom.getInstanceStrong();
    byte[] salt = new byte[16];
    sr.nextBytes(salt);

    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1000, 128 * 8);
    SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
    Cipher aes = Cipher.getInstance("AES");
    aes.init(Cipher.ENCRYPT_MODE, key);

===========

Old Answer

You should use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).

Additionally don't generate byte arrays from Strings through getBytes() it uses the platform default Charset. So the password "blaöä" results in different byte array on different platforms.

byte[] key = (SALT2 + username + password).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit

SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");

Edit: If you need 256 bit as key sizes you need to download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" Oracle download link, use SHA-256 as hash and remove the Arrays.copyOf line. "ECB" is the default Cipher Mode and "PKCS5Padding" the default padding. You could use different Cipher Modes and Padding Modes through the Cipher.getInstance string using following format: "Cipher/Mode/Padding"

For AES using CTS and PKCS5Padding the string is: "AES/CTS/PKCS5Padding"

Render basic HTML view?


1) The best way is to set static folder. In your main file (app.js | server.js | ???):

app.use(express.static(path.join(__dirname, 'public')));

public/css/form.html
public/css/style.css

Then you got static file from "public" folder:

http://YOUR_DOMAIN/form.html
http://YOUR_DOMAIN/css/style.css

2)

You can create your file cache.
Use method fs.readFileSync

var cache = {};
cache["index.html"] = fs.readFileSync( __dirname + '/public/form.html');

app.get('/', function(req, res){    
    res.setHeader('Content-Type', 'text/html');
    res.send( cache["index.html"] );                                
};);

How to remove a variable from a PHP session array

If you want to remove or unset all $_SESSION 's then try this

session_destroy();

If you want to remove specific $_SESSION['name'] then try this

session_unset('name');

How to use timeit module

The way timeit works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn't affect the next pass with already sorted data (that, of course, would make the Timsort really shine because it performs best when the data already partially ordered).

Here is an example of how to set up a test for sorting:

>>> import timeit

>>> setup = '''
import random

random.seed('slartibartfast')
s = [random.random() for i in range(1000)]
timsort = list.sort
'''

>>> print min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000))
0.334147930145

Note that the series of statements makes a fresh copy of the unsorted data on every pass.

Also, note the timing technique of running the measurement suite seven times and keeping only the best time -- this can really help reduce measurement distortions due to other processes running on your system.

Those are my tips for using timeit correctly. Hope this helps :-)

How to generate XML from an Excel VBA macro?

Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)

Script:

Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
    Dim Q As String
    Q = Chr$(34)

    Dim sXML As String

    sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
    sXML = sXML & "<rows>"


    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1
    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend

    Dim iRow As Integer
    iRow = iDataStartRow

    While Cells(iRow, 1) > ""
        sXML = sXML & "<row id=" & Q & iRow & Q & ">"

        For icol = 1 To iColCount - 1
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
           sXML = sXML & Trim$(Cells(iRow, icol))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
        Next

        sXML = sXML & "</row>"
        iRow = iRow + 1
    Wend
    sXML = sXML & "</rows>"

    Dim nDestFile As Integer, sText As String

    ''Close any open text files
    Close

    ''Get the number of the next free text file
    nDestFile = FreeFile

    ''Write the entire file to sText
    Open sOutputFileName For Output As #nDestFile
    Print #nDestFile, sXML
    Close
End Sub

Sub test()
    MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub

Removing cordova plugins from the project

This is the commandline for removing plugins in Cordova

cordova plugin remove <pluginid>

For example I ran cordova plugin and got a list of plugins then I used the id for the plugin to uninstall

cordova plugin remove com.monday.contact-chooser

You can get help in the commandline by typing

cordova help <command>

sql primary key and index

NOTE: This answer addresses enterprise-class development in-the-large.

This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed.

In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index.

Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows.

The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table.

I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.

Changing the background color of a drop down list transparent in html

You can actualy fake the transparency of option DOMElements with the following CSS:

CSS

option { 
    /* Whatever color  you want */
    background-color: #82caff;
}

See Demo

The option tag does not support rgba colors yet.

How do I get currency exchange rates via an API such as Google Finance?

If you're looking for a ruby based solution for this problem, I recommend using the Google Calculator method a solution similar to the following: http://j.mp/QIC564

require 'faraday'
require 'faraday_middleware'
require 'json'

# Debug: 
# require "pry"


country_code_src = "USD"
country_code_dst = "INR"
connection = Faraday.get("http://www.google.com/ig/calculator?hl=en&q=1#{country_code_src}=?#{country_code_dst}")

currency_comparison_hash = eval connection.body #Google's output is not JSON, it's a hash

dst_currency_value, *dst_currency_text = *currency_comparison_hash[:rhs].split(' ')
dst_currency_value = dst_currency_value.to_f
dst_currency_text = dst_currency_text.join(' ')

puts "#{country_code_dst} -> #{dst_currency_value} (#{dst_currency_text} to 1 #{country_code_src})"

Use LIKE %..% with field values in MySQL

Use:

SELECT t1.Notes, 
       t2.Name
  FROM Table1 t1
  JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')

Count number of rows by group using dplyr

I think what you are looking for is as follows.

cars_by_cylinders_gears <- mtcars %>%
  group_by(cyl, gear) %>%
  summarise(count = n())

This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.

Recursively look for files with a specific extension

find $directory -type f -name "*.in"

is a bit shorter than that whole thing (and safer - deals with whitespace in filenames and directory names).

Your script is probably failing for entries that don't have a . in their name, making $extension empty.

Change Color of Fonts in DIV (CSS)

To do links, you can do

.social h2 a:link {
  color: pink;
  font-size: 14px;   
}

You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.

How to parse XML using jQuery?

First thing that pop-up in google results http://think2loud.com/224-reading-xml-with-jquery/ There's no simple way to access xml structure (like you described Pages->pagename->controls->test) in jQuery without any plugins.

How to set JAVA_HOME for multiple Tomcat instances?

If you are a Windows user, put the content below in a setenv.bat file that you must create in Tomcat bin directory.

set JAVA_HOME=C:\Program Files\Java\jdk1.6.x

If you are a Linux user, put the content below in a setenv.sh file that you must create in Tomcat bin directory.

JAVA_HOME=/usr/java/jdk1.6.x

Save PHP variables to a text file

Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).

Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.

$file = '/tmp/file';
$content = serialize($my_variable);
file_put_contents($file, $content);
$content = unserialize(file_get_contents($file));

How do I put a border around an Android textview?

With the Material Components Library you can use the MaterialShapeDrawable.

    <TextView
        android:id="@+id/textview"
        .../>

Then you can programmatically apply a MaterialShapeDrawable:

    TextView textView = findViewById(R.id.textview);
    MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable();
    shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,android.R.color.transparent));
    shapeDrawable.setStroke(1.0f, ContextCompat.getColor(this,R.color....));
    ViewCompat.setBackground(textView,shapeDrawable);

enter image description here

How to write :hover condition for a:before and a:after?

You can also restrict your action to just one class using the right pointed bracket (">"), as I have done in this code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    span {
    font-size:12px;
    }
    a {
        color:green;
    }
    .test1>a:hover span {
        display:none;
    }
    .test1>a:hover:before {
        color:red;
        content:"Apple";
    }
  </style>
</head>

<body>
  <div class="test1">
    <a href="#"><span>Google</span></a>
  </div>
  <div class="test2">
    <a href="#"><span>Apple</span></a>
  </div>
</body>

</html>

Note: The hover:before switch works only on the .test1 class

Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

We tried Set instead of List and it is a nightmare: when you add two new objects, equals() and hashCode() fail to distinguish both of them ! Because they don't have any id.

typical tools like Eclipse generate that kind of code from Database tables:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

You may also read this article that explains properly how messed up JPA/Hibernate is. After reading this, I think this is the last time I use any ORM in my life.

I've also encounter Domain Driven Design guys that basically say ORM are a terrible thing.

Convert base64 string to ArrayBuffer

Using TypedArray.from:

Uint8Array.from(atob(base64_string), c => c.charCodeAt(0))

Performance to be compared with the for loop version of Goran.it answer.

Gray out image with CSS?

Your here:

<a href="#"><img src="img.jpg" /></a>

Css Gray:

img{
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 10+, Firefox on Android */
    filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: gray; /* IE6-9 */
    -webkit-filter: grayscale(100%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */}

Ungray:

a:hover img{
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
    filter: grayscale(0%);
    -moz-filter: grayscale(0%);
    -ms-filter: grayscale(0%);
    -o-filter: grayscale(0%);
    filter: none ; /* IE6-9 */
    zoom:1; /* needed to trigger "hasLayout" in IE if no width or height is set */
    -webkit-filter: grayscale(0%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */
    }

I found it at: http://zkiwi.com/topic/chuyen-hinh-mau-thanh-trang-den-bang-css-nhu-the-nao

Edit: IE10+ does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter. You can fix it, use one in two solutions below:

  1. Set IE10+ to render using IE9 standards mode using the following meta element in the head: <meta http-equiv="X-UA-Compatible" content="IE=9">
  2. Use an SVG overlay in IE10 to accomplish the greyscaling internet explorer 10 - howto apply grayscale filter?

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

download rpm packages and run the following command:

rpm -Uvh glibc-2.15-60.el6.x86_64.rpm \
glibc-common-2.15-60.el6.x86_64.rpm \
glibc-devel-2.15-60.el6.x86_64.rpm \
glibc-headers-2.15-60.el6.x86_64.rpm

How to right-align and justify-align in Markdown?

If you want to use justify align in Jupyter Notebook use the following syntax:

<p style='text-align: justify;'> Your Text </p>

For right alignment:

<p style='text-align: right;'> Your Text </p>

How can I change default dialog button text color in android 5

For me it was different, I used a button theme

<style name="ButtonLight_pink" parent="android:Widget.Button">
    <item name="android:background">@drawable/light_pink_btn_default_holo_light</item>
    <item name="android:minHeight">48dip</item>
    <item name="android:minWidth">64dip</item>
    <item name="android:textColor">@color/tab_background_light_pink</item>
</style>

and because android:textColor was white there… I didn't see any button text (Dialog buttons are basically buttons too). There we go, changed it, fixed it.

Allow access permission to write in Program Files of Windows 7

I am working on a program that saves its data properly to %APPDATA%, but sometimes, there are system-wide settings that affect all users. So in these situations, it HAS to write to the programs installation directory.

And as far as I have read now, it's impossible to temporarily get write access to one directory. You can only run the whole application as administrator (which should be out of the question) or not be able to save that file. (all or nothing)

I guess, I will just write the file to %APPDATA% and launch an external program that copies the file into the installation folder and have THAT program demand admin privileges... dumb idea, but seems to be the only practical solution...

getting "No column was specified for column 2 of 'd'" in sql server cte?

You just need to provide an alias for your aggregate columns in the CTE

d as (SELECT 
   duration, 
   sum(totalitems) as sumtotalitems
FROM 
   [DrySoftBranch].[dbo].[mnthItemWiseTotalQty] ('1') AS BkdQty
group by duration
)

How do you write multiline strings in Go?

You have to be very careful on formatting and line spacing in go, everything counts and here is a working sample, try it https://play.golang.org/p/c0zeXKYlmF

package main

import "fmt"

func main() {
    testLine := `This is a test line 1
This is a test line 2`
    fmt.Println(testLine)
}

How can I turn a List of Lists into a List in Java 8?

List<List> list = map.values().stream().collect(Collectors.toList());

    List<Employee> employees2 = new ArrayList<>();
    
     list.stream().forEach(
             
             n-> employees2.addAll(n));

What does DIM stand for in Visual Basic and BASIC?

Short for Dimension. It's a type of variable. You declare (or "tell" Visual Basic) that you are setting up a variable with this word.

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

Correct me if I'm mistaken, but the previous example, I believe, is just slightly out of sync with the latest version of James Newton's Json.NET library.

var o = JObject.Parse(stringFullOfJson);
var page = (int)o["page"];
var totalPages = (int)o["total_pages"];

How to install Python MySQLdb module using pip?

My environment are:

  • Windows 10 Pro,
  • Python 3.7 (python-3.7.1-amd64.exe),
  • MySQL 8.0 (mysql-installer-web-community-8.0.13.0.msi)

pip install mysqlclient-1.3.13-cp37-cp37m-win_amd64.whl

works for me.

import MySQLdb, sys


# --------------------------------------------------
# Connect to MySQL
# --------------------------------------------------
try:
    db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="database", charset='cp1251')
except MySQLdb.Error as e:
    print ("Error %d: %s" % (e.args[0], e.args[1]))
    sys.exit()

# Creating cursor 
cursor = db.cursor()

How to change a css class style through Javascript?

There are two ways in which this can be accomplished using vanilla javascript. The first is className and the second is classList. className works in all browsers but can be unwieldy to work with when modifying an element's class attribute. classList is an easier way to modify an element's class(es).

To outright set an element's class attribute, className is the way to go, otherwise to modify an element's class(es), it's easier to use classList.

Initial Html

<div id="ID"></div>

Setting the class attribute

var div = document.getElementById('ID');
div.className = "foo bar car";

Result:

<div id="ID" class="foo bar car"></div>

Adding a class

div.classList.add("car");// Class already exists, nothing happens
div.classList.add("tar");

Note: There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.
Result:

<div id="ID" class="foo bar car tar"></div>

Removing a class

div.classList.remove("car");
div.classList.remove("tar");
div.classList.remove("car");// No class of this name exists, nothing happens

Note: Just like add, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.
Result:

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

Checking if a class attribute contains a specific class

if (div.classList.contains("foo")) {
  // Do stuff
}

Toggling a class

var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed

classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added

.toggle has a second boolean parameter that, in my opinion, is redundant and isn't worth going over.

For more information on classList, check out MDN. It also covers browser compatibility if that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.

Is it possible to capture the stdout from the sh DSL command in the pipeline

Note: The linked Jenkins issue has since been solved.

As mention in JENKINS-26133 it was not possible to get shell output as a variable. As a workaround suggested using of writ-read from temporary file. So, your example would have looked like:

sh "echo foo > result";
def output=readFile('result').trim()
echo "output=$output";

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

maxReceivedMessageSize and maxBufferSize in app.config

Open app.config on client side and add maxBufferSize and maxReceivedMessageSize attributes if it is not available

Original

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="Service1Soap"/>
      </basicHttpBinding>
    </bindings>

After Edit/Update

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="Service1Soap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
      </basicHttpBinding>
    </bindings>

How do I create a new user in a SQL Azure database?

I found this link very helpful:
https://azure.microsoft.com/en-gb/documentation/articles/sql-database-manage-logins/

It details things like:
- Azure SQL Database subscriber account
- Using Azure Active Directory users to access the database
- Server-level principal accounts (unrestricted access)
- Adding users to the dbmanager database role

I used this and Stuart's answer to do the following:
On the master database (see link as to who has permissions on this):

CREATE LOGIN [MyAdmin] with password='ReallySecurePassword'

And then on the database in question:

CREATE USER [MyAdmin] FROM LOGIN [MyAdmin]
ALTER ROLE db_owner ADD MEMBER [MyAdmin]

You can also create users like this, according to the link:

CREATE USER [[email protected]] FROM EXTERNAL PROVIDER;

ASP.NET Web API application gives 404 when deployed at IIS 7

I have been battling this problem for a couple of days trying all kinds of things suggested. My dev machine was working fine, but the new machine I was deploying to was giving me the 404 error.

In IIS manager, I compared the handler mappings on both machines to realize that a lot of handlers were missing. Turns out that ASP.Net 5 was not installed on the machine.

How to print number with commas as thousands separators?

from Python version 2.6 you can do this:

def format_builtin(n):
    return format(n, ',')

For Python versions < 2.6 and just for your information, here are 2 manual solutions, they turn floats to ints but negative numbers work correctly:

def format_number_using_lists(number):
    string = '%d' % number
    result_list = list(string)
    indexes = range(len(string))
    for index in indexes[::-3][1:]:
        if result_list[index] != '-':
            result_list.insert(index+1, ',')
    return ''.join(result_list)

few things to notice here:

  • this line: string = '%d' % number beautifully converts a number to a string, it supports negatives and it drops fractions from floats, making them ints;
  • this slice indexes[::-3] returns each third item starting from the end, so I used another slice [1:] to remove the very last item cuz I don't need a comma after the last number;
  • this conditional if l[index] != '-' is being used to support negative numbers, do not insert a comma after the minus sign.

And a more hardcore version:

def format_number_using_generators_and_list_comprehensions(number):
    string = '%d' % number
    generator = reversed( 
        [
            value+',' if (index!=0 and value!='-' and index%3==0) else value
            for index,value in enumerate(reversed(string))
        ]
    )
    return ''.join(generator)

how to use font awesome in own css?

Instructions for Drupal 8 / FontAwesome 5

Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)

Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
}
?>

Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.

Make sure you import FontAwesome, add this at the top of the CSS file

@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

then add this in the CSS

input#edit-submit {
    font-family: 'Font Awesome\ 5 Free';
    background-color: transparent;
    border: 0;  
}

FLUSH ALL CACHES AND IT SHOULD WORK FINE

Add Google Font Effects

If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>

How do I limit the number of results returned from grep?

For 2 use cases:

  1. I only want n overall results, not n results per file, the grep -m 2 is per file max occurrence.
  2. I often use git grep which doesn't take -m

A good alternative in these scenarios is grep | sed 2q to grep first 2 occurrences across all files. sed documentation: https://www.gnu.org/software/sed/manual/sed.html

Environment variable in Jenkins Pipeline

You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).

From the documentation:

Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):

env.MYTOOL_VERSION = '1.33'
node {
  sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}

These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.

For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job enter image description here

How to initialize std::vector from C-style array?

You can 'learn' the size of the array automatically:

template<typename T, size_t N>
void set_data(const T (&w)[N]){
    w_.assign(w, w+N);
}

Hopefully, you can change the interface to set_data as above. It still accepts a C-style array as its first argument. It just happens to take it by reference.


How it works

[ Update: See here for a more comprehensive discussion on learning the size ]

Here is a more general solution:

template<typename T, size_t N>
void copy_from_array(vector<T> &target_vector, const T (&source_array)[N]) {
    target_vector.assign(source_array, source_array+N);
}

This works because the array is being passed as a reference-to-an-array. In C/C++, you cannot pass an array as a function, instead it will decay to a pointer and you lose the size. But in C++, you can pass a reference to the array.

Passing an array by reference requires the types to match up exactly. The size of an array is part of its type. This means we can use the template parameter N to learn the size for us.

It might be even simpler to have this function which returns a vector. With appropriate compiler optimizations in effect, this should be faster than it looks.

template<typename T, size_t N>
vector<T> convert_array_to_vector(const T (&source_array)[N]) {
    return vector<T>(source_array, source_array+N);
}

Best way to simulate "group by" from bash?

The canonical solution is the one mentioned by another respondent:

sort | uniq -c

It is shorter and more concise than what can be written in Perl or awk.

You write that you don't want to use sort, because the data's size is larger than the machine's main memory size. Don't underestimate the implementation quality of the Unix sort command. Sort was used to handle very large volumes of data (think the original AT&T's billing data) on machines with 128k (that's 131,072 bytes) of memory (PDP-11). When sort encounters more data than a preset limit (often tuned close to the size of the machine's main memory) it sorts the data it has read in main memory and writes it into a temporary file. It then repeats the action with the next chunks of data. Finally, it performs a merge sort on those intermediate files. This allows sort to work on data many times larger than the machine's main memory.

Set margins in a LinearLayout programmatically

Try this

 LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT
    );
    params.setMargins(left, top, right, bottom);
    yourbutton.setLayoutParams(params);

Image UriSource and Data Binding

This article by Atul Gupta has sample code that covers several scenarios:

  1. Regular resource image binding to Source property in XAML
  2. Binding resource image, but from code behind
  3. Binding resource image in code behind by using Application.GetResourceStream
  4. Loading image from file path via memory stream (same is applicable when loading blog image data from database)
  5. Loading image from file path, but by using binding to a file path Property
  6. Binding image data to a user control which internally has image control via dependency property
  7. Same as point 5, but also ensuring that the file doesn't get's locked on hard-disk

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

I get this every time I want to create an application in VC++.

Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.

Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.

Make Adobe fonts work with CSS3 @font-face in IE9

As Knu said, you can use this tool, however it's compiled only for MS-DOS. I compiled it for Win64. Download.

Usage:

  1. Place the .exe in the same folder as the font you need to modify

  2. Navigate to that directory in the command line

  3. type embed fontname.fonttype, replacing fontname with the filename and fonttype with the extension i.e. embed brokenFont.ttf

  4. All done! Your font should now work.

get string value from HashMap depending on key name

Suppose you declared HashMap as :-

HashMap<Character,Integer> hs = new HashMap<>();

Then,key in map is of type Character data type and value of int type.Now,to get value corresponding to key irrespective of type of key,value type, syntax is :-

    char temp = 'a';
    if(hs.containsKey(temp)){
`       int val = hs.get(temp); //val is the value corresponding to key temp
    }

So, according to your question you want to get string value corresponding to a key.For this, just declare HashMap as HashMap<"datatype of key","datatype of value" hs = new HashMap<>(); Using this will make your code cleaner and also you don't have to convert the result of hs.get("my_code") to string as by default it returns value of string if at entry time one has kept value as a string.

jQuery Change event on an <input> element - any way to retain previous value?

You could have the value of the input field copied to a hidden field whenever focus leaves the input field (which should do what you want). See code below:

<script>
    $(document).ready(function(){
        $('#myInputElement').bind('change', function(){
            var newvalue = $(this).val();
        });
        $('#myInputElement').blur(function(){
            $('#myHiddenInput').val($(this).val());
        });
    });
</script>
<input id="myInputElement" type="text">

(untested, but it should work).

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

It is a security issue, so to fix it simply do the following:

  1. Go to the Oracle Client folder.
  2. Right Click on the folder.
  3. On security Tab, Add "Authenticated Users" and give this account Read & Execute permission.
  4. Apply this security for all folders, Subfolders and Files (IMPORTANT).
  5. Don't Forget to REBOOT your Machine; if you forgot to do this you will still face the same problem unless you restart your machine.

http://blogs.msdn.com/b/fabdulwahab/archive/2011/11/13/system-data-oracleclient-requires-oracle-client-software-version-8-1-7-or-greater.aspx

Margin while printing html page

If you know the target paper size, you can place your content in a DIV with that specific size and add a margin to that DIV to simulate the print margin. Unfortunately, I don't believe you have extra control over the print functionality apart from just show the print dialog box.

Add column to SQL Server

Use this query:

ALTER TABLE tablename ADD columname DATATYPE(size);

And here is an example:

ALTER TABLE Customer ADD LastName VARCHAR(50);

Time stamp in the C programming language

Standard C99:

#include <time.h>

time_t t0 = time(0);
// ...
time_t t1 = time(0);
double datetime_diff_ms = difftime(t1, t0) * 1000.;

clock_t c0 = clock();
// ...
clock_t c1 = clock();
double runtime_diff_ms = (c1 - c0) * 1000. / CLOCKS_PER_SEC;

The precision of the types is implementation-defined, ie the datetime difference might only return full seconds.

Calling class staticmethod within the class body?

What about this solution? It does not rely on knowledge of @staticmethod decorator implementation. Inner class StaticMethod plays as a container of static initialization functions.

class Klass(object):

    class StaticMethod:
        @staticmethod  # use as decorator
        def _stat_func():
            return 42

    _ANS = StaticMethod._stat_func()  # call the staticmethod

    def method(self):
        ret = self.StaticMethod._stat_func() + Klass._ANS
        return ret

How to pass a vector to a function?

You're passing in a pointer *random but you're using it like a reference &random

The pointer (what you have) says "This is the address in memory that contains the address of random"

The reference says "This is the address of random"

Capitalize words in string

My solution:

String.prototype.toCapital = function () {
    return this.toLowerCase().split(' ').map(function (i) {
        if (i.length > 2) {
            return i.charAt(0).toUpperCase() + i.substr(1);
        }

        return i;
    }).join(' ');
};

Example:

'álL riGht'.toCapital();
// Returns 'Áll Right'

Testing pointers for validity (C/C++)

I've got a lot of sympathy with your question, as I'm in an almost identical position myself. I appreciate what a lot of the replies are saying, and they are correct - the routine supplying the pointer should be providing a valid pointer. In my case, it is almost inconceivable that they could have corrupted the pointer - but if they had managed, it would be MY software that crashes, and ME that would get the blame :-(

My requirement isn't that I continue after a segmentation fault - that would be dangerous - I just want to report what happened to the customer before terminating so that they can fix their code rather than blaming me!

This is how I've found to do it (on Windows): http://www.cplusplus.com/reference/clibrary/csignal/signal/

To give a synopsis:

#include <signal.h>

using namespace std;

void terminate(int param)
/// Function executed if a segmentation fault is encountered during the cast to an instance.
{
  cerr << "\nThe function received a corrupted reference - please check the user-supplied  dll.\n";
  cerr << "Terminating program...\n";
  exit(1);
}

...
void MyFunction()
{
    void (*previous_sigsegv_function)(int);
    previous_sigsegv_function = signal(SIGSEGV, terminate);

    <-- insert risky stuff here -->

    signal(SIGSEGV, previous_sigsegv_function);
}

Now this appears to behave as I would hope (it prints the error message, then terminates the program) - but if someone can spot a flaw, please let me know!

How do I use T-SQL's Case/When?

As soon as a WHEN statement is true the break is implicit.

You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.

More information here: break in case statement in T-SQL

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

Fill background color left to right CSS

If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.

Steps to create:

  1. Have two text, one is static colored in color on hover, and the other one in default state color which you will be moving on hover
  2. On hover move wrapper of the not static one text while in the same time move inner text of that wrapper to the opposite direction.
  3. Make sure to add overflow hidden where needed

Good thing about this solution:

  • Support IE9, uses only transform
  • Button (or element you are applying animation) is fluid in width, so no fixed values are being used here

Not so good thing about this solution:

  • A really messy markup, could be solved by using pseudo elements and att(data)?
  • There is some small glitch in animation when having more then one button next to each other, maybe it could be easily solved but I didn't take much time to investigate yet.

Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq

<button class="btn btn--animation-from-right">
  <span class="btn__text-static">Cover left</span>
  <div class="btn__text-dynamic">
    <span class="btn__text-dynamic-inner">Cover left</span>
  </div>
</button>

.btn {
  padding: 10px 20px;
  position: relative;

  border: 2px solid #222;
  color: #fff;
  background-color: #222;
  position: relative;

  overflow: hidden;
  cursor: pointer;

  text-transform: uppercase;
  font-family: monospace;
  letter-spacing: -1px;

  [class^="btn__text"] {
    font-size: 24px;
  }

  .btn__text-dynamic,
  .btn__text-dynamic-inner {    
    display: flex;
    justify-content: center;
    align-items: center;

    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index: 2;

    transition: all ease 0.5s;
  }

  .btn__text-dynamic {
    background-color: #fff;
    color: #222;

    overflow: hidden;
  }

  &:hover {
    .btn__text-dynamic {
      transform: translateX(-100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(100%);
    }
  }
}

.btn--animation-from-right {
    &:hover {
    .btn__text-dynamic {
      transform: translateX(100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(-100%);
    }
  }
}

You can remove .btn--animation-from-right modifier if you want to animate to the left.

Animation CSS3: display + opacity

I had the same problem. I tried using animations instead of transitions - as suggested by @MichaelMullany and @Chris - but it only worked for webkit browsers even if I copy-pasted with "-moz" and "-o" prefixes.

I was able to get around the problem by using visibility instead of display. This works for me because my child element is position: absolute, so document flow isn't being affected. It might work for others too.

This is what the original code would look like using my solution:

.child {
    position: absolute;
    opacity: 0;
    visibility: hidden;

    -webkit-transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    transition: opacity 0.5s ease-in-out;
}

.parent:hover .child {
    position: relative;
    opacity: 0.9;
    visibility: visible;
}

How do you check "if not null" with Eloquent?

If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->

 $searchResultQuery = Users::query(); 
 $searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
 $searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null 

Or with scope in model :

public function scopeNotNullOnly($query){

    return $query->where('status_message', '<>', '');
}

Radio buttons and label to display in same line

** Used table to align the radio and text in one line

_x000D_
_x000D_
<div >_x000D_
  <table>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td><strong>Do you want to add new server ?</strong></td>_x000D_
        <td><input type="radio" name="addServer" id="serverYes" value="1"></td>_x000D_
        <td>Yes</td>_x000D_
        <td><input type="radio" name="addServer" id="serverNo" value="1"></td>_x000D_
        <td>No</td>_x000D_
_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

**

How to import and use image in a Vue single file component?

These both work for me in JavaScript and TypeScript

<img src="@/assets/images/logo.png" alt=""> 

or

 <img src="./assets/images/logo.png" alt="">

How to export a mysql database using Command Prompt?

mysqldump -h [host] -p -u [user] [database name] > filename.sql

Example in localhost

mysqldump -h localhost -p -u root cookbook > cookbook.sql

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

Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:

Select Insert imports on paste value to All

Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*

Site does not exist error for a2ensite

Worked after I added .conf to the configuration file

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

What happens if I promote the column to be a/the PK, too (a.k.a. identifying relationship)? As the column is now the PK, I must tag it with @Id (...).

This enhanced support of derived identifiers is actually part of the new stuff in JPA 2.0 (see the section 2.4.1 Primary Keys Corresponding to Derived Identities in the JPA 2.0 specification), JPA 1.0 doesn't allow Id on a OneToOne or ManyToOne. With JPA 1.0, you'd have to use PrimaryKeyJoinColumn and also define a Basic Id mapping for the foreign key column.

Now the question is: are @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?

You can obtain a similar result but using an Id on OneToOne or ManyToOne is much simpler and is the preferred way to map derived identifiers with JPA 2.0. PrimaryKeyJoinColumn might still be used in a JOINED inheritance strategy. Below the relevant section from the JPA 2.0 specification:

11.1.40 PrimaryKeyJoinColumn Annotation

The PrimaryKeyJoinColumn annotation specifies a primary key column that is used as a foreign key to join to another table.

The PrimaryKeyJoinColumn annotation is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108].

...

If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.

...

Example: Customer and ValuedCustomer subclass

@Entity
@Table(name="CUST")
@Inheritance(strategy=JOINED)
@DiscriminatorValue("CUST")
public class Customer { ... }

@Entity
@Table(name="VCUST")
@DiscriminatorValue("VCUST")
@PrimaryKeyJoinColumn(name="CUST_ID")
public class ValuedCustomer extends Customer { ... }

[108] The derived id mechanisms described in section 2.4.1.1 are now to be preferred over PrimaryKeyJoinColumn for the OneToOne mapping case.

See also


This source http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state states that using @ManyToOne and @Id works with JPA 1.x. Who's correct now?

The author is using a pre release JPA 2.0 compliant version of EclipseLink (version 2.0.0-M7 at the time of the article) to write an article about JPA 1.0(!). This article is misleading, the author is using something that is NOT part of JPA 1.0.

For the record, support of Id on OneToOne and ManyToOne has been added in EclipseLink 1.1 (see this message from James Sutherland, EclipseLink comitter and main contributor of the Java Persistence wiki book). But let me insist, this is NOT part of JPA 1.0.

How to install package from github repo in Yarn

For ssh style urls just add ssh before the url:

yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>