Programs & Examples On #Pclxl

How to search multiple columns in MySQL?

If it is just for searching then you may be able to use CONCATENATE_WS. This would allow wild card searching. There may be performance issues depending on the size of the table.

SELECT * 
FROM pages 
WHERE CONCAT_WS('', column1, column2, column3) LIKE '%keyword%'

useState set method not reflecting change immediately

You can solve it by using the useRef hook but then it's will not re-render when it' updated. I have created a hooks called useStateRef, that give you the good from both worlds. It's like a state that when it's updated the Component re-render, and it's like a "ref" that always have the latest value.

See this example:

var [state,setState,ref]=useStateRef(0)

It works exactly like useState but in addition, it gives you the current state under ref.current

Learn more:

Angular 1 - get current URL parameters

You could inject $routeParams to your controller and access all the params that where used when the route was resolved.

E.g.:

// route was: app.dev/backend/:type/:id

function MyCtrl($scope, $routeParams, $log) {
    // use the params
    $log.info($routeParams.type, $routeParams.id);
};

See angular $routeParams documentation for further information.

How do I change select2 box height

edit select2.css file. Go to the height option and change:

.select2-container .select2-choice {
    display: block;
    height: 36px;
    padding: 0 0 0 8px;
    overflow: hidden;
    position: relative;

    border: 1px solid #aaa;
    white-space: nowrap;
    line-height: 26px;
    color: #444;
    text-decoration: none;

    border-radius: 4px;

    background-clip: padding-box;

    -webkit-touch-callout: none;
      -webkit-user-select: none;
       -khtml-user-select: none;
         -moz-user-select: none;
          -ms-user-select: none;
              user-select: none;

    background-color: #fff;
    background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #eee), color-stop(0.5, #fff));
    background-image: -webkit-linear-gradient(center bottom, #eee 0%, #fff 50%);
    background-image: -moz-linear-gradient(center bottom, #eee 0%, #fff 50%);
    background-image: -o-linear-gradient(bottom, #eee 0%, #fff 50%);
    background-image: -ms-linear-gradient(top, #fff 0%, #eee 50%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr = '#ffffff', endColorstr = '#eeeeee', GradientType = 0);
    background-image: linear-gradient(top, #fff 0%, #eee 50%);
}

Parse HTML table to Python list?

Sven Marnach excellent solution is directly translatable into ElementTree which is part of recent Python distributions:

from xml.etree import ElementTree as ET

s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""

table = ET.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print(dict(zip(headers, values)))

same output as Sven Marnach's answer...

Get and Set a Single Cookie with Node.js HTTP Server

You can use the "cookies" npm module, which has a comprehensive set of features.

Documentation and examples at:
https://github.com/jed/cookies

How to add url parameters to Django template url tag?

I found the answer here: Is it possible to pass query parameters via Django's {% url %} template tag?

Simply add them to the end:

<a href="{% url myview %}?office=foobar">
For Django 1.5+

<a href="{% url 'myview' %}?office=foobar">

[there is nothing else to improve but I'm getting a stupid error when I fix the code ticks]

The value violated the integrity constraints for the column

As a slight alternative to @FazianMubasher's answer, instead of allowing NULL for the specified column (which may for many reasons not be possible), you could also add a Conditional Split Task to branch NULL values to an error file, or just to ignore them:

enter image description here

enter image description here

adb shell su works but adb root does not

I use for enter su mode in abd shell

adb shell "su"

What are .a and .so files?

Wikipedia is a decent source for this info.

To learn about static library files like .a read Static libarary

To learn about shared library files like .so read Library_(computing)#Shared_libraries On this page, there is also useful info in the File naming section.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

The easiest way is to execute the following command from the command line (see Upgrading the Gradle Wrapper in documentation):

./gradlew wrapper --gradle-version 5.5

Moreover, you can use --distribution-type parameter with either bin or all value to choose a distribution type. Use all distribution type to avoid a hint from IntelliJ IDEA or Android Studio that will offer you to download Gradle with sources:

./gradlew wrapper --gradle-version 5.5 --distribution-type all

Or you can create a custom wrapper task

task wrapper(type: Wrapper) {
    gradleVersion = '5.5'
}

and run ./gradlew wrapper.

send Content-Type: application/json post with node.js

Since the request module that other answers use has been deprecated, may I suggest switching to node-fetch:

const fetch = require("node-fetch")

const url = "https://www.googleapis.com/urlshortener/v1/url"
const payload = { longUrl: "http://www.google.com/" }

const res = await fetch(url, {
  method: "post",
  body: JSON.stringify(payload),
  headers: { "Content-Type": "application/json" },
})

const { id } = await res.json()

Tomcat is web server or application server?

Application Server:

Application server maintains the application logic and
serves the web pages in response to user request.

That means application server can do both application logic maintanence and web page serving.

Web Server:

Web server just serves the web pages and it cannot enforce any application logic.

Final conclusion is: Application server also contains the web server.

For further Reference : http://www.javaworld.com/javaqa/2002-08/01-qa-0823-appvswebserver.html

Read the package name of an Android APK

On Mac:

Way 1:

zgong$ /Users/zgong/Library/Android/sdk/build-tools/29.0.3/aapt dump badging ~/Downloads/NonSIMCC-151-app-release-signed.apk
package: name='com.A.B' versionCode='2020111801' versionName='1.0.40' compileSdkVersion='29' compileSdkVersionCodename='10'
sdkVersion:'24'
targetSdkVersion:'29'
......

Way 2:

/Users/zgong/Library/Android/sdk/build-tools/29.0.3/aapt2 dump packagename ~/Downloads/NonSIMCC-151-app-release-signed.apk
com.A.B

Unable to load script from assets index.android.bundle on windows

first of all check your assets folder exist in this location \android\app\src\main\assets

if no then run this command in terminal

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

then run your project on your android device using

react-native run-android

What does '&' do in a C++ declaration?

One way to look at the & (reference) operator in c++ is that is merely a syntactic sugar to a pointer. For example, the following are roughly equivalent:

void foo(int &x)
{
    x = x + 1;
}

void foo(int *x)
{
    *x = *x + 1;
}

The more useful is when you're dealing with a class, so that your methods turn from x->bar() to x.bar().

The reason I said roughly is that using references imposes additional compile-time restrictions on what you can do with the reference, in order to protect you from some of the problems caused when dealing with pointers. For instance, you can't accidentally change the pointer, or use the pointer in any way other than to reference the singular object you've been passed.

Make Axios send cookies in its requests automatically

So I had this exact same issue and lost about 6 hours of my life searching, I had the

withCredentials: true

But the browser still didn't save the cookie until for some weird reason I had the idea to shuffle the configuration setting:

Axios.post(GlobalVariables.API_URL + 'api/login', {
        email,
        password,
        honeyPot
    }, {
        withCredentials: true,
        headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
    }});

Seems like you should always send the 'withCredentials' Key first.

MISCONF Redis is configured to save RDB snapshots

As pointed out by @Chris the problem is likely to to low memory. We started experiencing it when we allocated too much RAM to MySQL (innodb_buffer_pool_size).

To ensure there's enough RAM for Redis and other services we reduced innodb_buffer_pool_size on MySQL.

How do I get into a Docker container's shell?

GOINSIDE SOLUTION

install goinside command line tool with:

sudo npm install -g goinside

and go inside a docker container with a proper terminal size with:

goinside docker_container_name

old answer

We've put this snippet in ~/.profile:

goinside(){
    docker exec -it $1 bash -c "stty cols $COLUMNS rows $LINES && bash";
}
export -f goinside

Not only does this make everyone able to get inside a running container with:

goinside containername

It also solves a long lived problem about fixed Docker container terminal sizes. Which is very annoying if you face it.

Also if you follow the link you'll have command completion for your docker container names too.

Pandas DataFrame: replace all values in a column, based on condition

df["First season"] = df["First season"].apply(lambda x : 1 if x > 1990 else x)

Run a shell script with an html button

This is really just an expansion of BBB's answer which lead to to get my experiment working.

This script will simply create a file /tmp/testfile when you click on the button that says "Open Script".

This requires 3 files.

  1. The actual HTML Website with a button.
  2. A php script which executes the script
  3. A Script

The File Tree:

root@test:/var/www/html# tree testscript/
testscript/
+-- index.html
+-- testexec.php
+-- test.sh

1. The main WebPage:

root@test:/var/www/html# cat testscript/index.html
<form action="/testscript/testexec.php">
    <input type="submit" value="Open Script">
</form>

2. The PHP Page that runs the script and redirects back to the main page:

root@test:/var/www/html# cat testscript/testexec.php
<?php
shell_exec("/var/www/html/testscript/test.sh");
header('Location: http://192.168.1.222/testscript/index.html?success=true');
?>

3. The Script :

root@test:/var/www/html# cat testscript/test.sh

#!/bin/bash

touch /tmp/testfile

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

How do I instantiate a JAXBElement<String> object?

ObjectFactory fact = new ObjectFactory();   
JAXBElement<String> str = fact.createCompositeTypeStringValue("vik");    
comp.setStringValue(str);
CompositeType retcomp = service.getDataUsingDataContract(comp);
System.out.println(retcomp.getStringValue().getValue());

Placeholder in UITextView

You can just set a label on the textview.

MyUITextView.h

@interface MyUITextView : UITextView {
    UILabel* _placeholderLabel;
}

@property(nonatomic, assign)NSString *placeholder;

MyUITextView.m

@implementation MyUITextView

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Create placeholder
        viewFrame = CGRectMake(0, 0, frame.size.width, 15);
        _placeholderLabel = [[UILabel alloc] initWithFrame:viewFrame];
        _placeholderLabel.textColor = [UIColor lightGrayColor];
        [self addSubview:_placeholderLabel];

        // Add text changed notification 
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)setPlaceholder:(NSString *)placeholder {
    _placeholderLabel.text = placeholder;
}

- (NSString*)placeholder {
    return _placeholderLabel.text;
}

#pragma mark UITextViewTextDidChangeNotification

- (void)textChanged:(NSNotification *)notification {
    _placeholderLabel.hidden = ([self.text lenght] == 0);
}

@end

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.

In other words, List<? extends Serializable> means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).

Format numbers in JavaScript similar to C#

To further jfriend00's answer (I dont't have enough points to comment) I have extended his/her answer to the following:

_x000D_
_x000D_
function log(args) {_x000D_
    var str = "";_x000D_
    for (var i = 0; i < arguments.length; i++) {_x000D_
        if (typeof arguments[i] === "object") {_x000D_
            str += JSON.stringify(arguments[i]);_x000D_
        } else {_x000D_
            str += arguments[i];_x000D_
        }_x000D_
    }_x000D_
    var div = document.createElement("div");_x000D_
    div.innerHTML = str;_x000D_
    document.body.appendChild(div);_x000D_
}_x000D_
_x000D_
Number.prototype.addCommas = function (str) {_x000D_
    if (str === undefined) {_x000D_
     str = this;_x000D_
    }_x000D_
    _x000D_
    var parts = (str + "").split("."),_x000D_
        main = parts[0],_x000D_
        len = main.length,_x000D_
        output = "",_x000D_
        first = main.charAt(0),_x000D_
        i;_x000D_
    _x000D_
    if (first === '-') {_x000D_
        main = main.slice(1);_x000D_
        len = main.length;    _x000D_
    } else {_x000D_
       first = "";_x000D_
    }_x000D_
    i = len - 1;_x000D_
    while(i >= 0) {_x000D_
        output = main.charAt(i) + output;_x000D_
        if ((len - i) % 3 === 0 && i > 0) {_x000D_
            output = "," + output;_x000D_
        }_x000D_
        --i;_x000D_
    }_x000D_
    // put sign back_x000D_
    output = first + output;_x000D_
    // put decimal part back_x000D_
    if (parts.length > 1) {_x000D_
        output += "." + parts[1];_x000D_
    }_x000D_
    return output;_x000D_
}_x000D_
_x000D_
var testCases = [_x000D_
    1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,_x000D_
    -1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1_x000D_
];_x000D_
 _x000D_
for (var i = 0; i < testCases.length; i++) {_x000D_
 log(testCases[i].addCommas());_x000D_
}_x000D_
 _x000D_
/*for (var i = 0; i < testCases.length; i++) {_x000D_
    log(Number.addCommas(testCases[i]));_x000D_
}*/
_x000D_
_x000D_
_x000D_

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Populate nested array in mongoose

I found this very helpful creating a feathersjs before hook to populate a 2 ref level deep relation. The mongoose models simply have

tables = new Schema({
  ..
  tableTypesB: { type: Schema.Types.ObjectId, ref: 'tableTypesB' },
  ..
}
tableTypesB = new Schema({
  ..
  tableType: { type: Schema.Types.ObjectId, ref: 'tableTypes' },
  ..
}

then in feathersjs before hook:

module.exports = function(options = {}) {
  return function populateTables(hook) {
    hook.params.query.$populate = {
      path: 'tableTypesB',
      populate: { path: 'tableType' }
    }

    return Promise.resolve(hook)
  }
}

So simple compared to some other methods I was trying to achieve this.

What's the difference between ng-model and ng-bind

ng-model

ng-model directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.

ng-bind

ng-bind works much different than ng-model. ng-bind is one way data binding used for displaying the value inside html component as inner HTML. This directive can not be used for binding with the variable but only with the HTML elements content. Infact this can be used along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.

This example would help you to understand.

High Quality Image Scaling Library

You can try dotImage, one of my company's products, which includes an object for resampling images that has 18 filter types for various levels of quality.

Typical usage is:

// BiCubic is one technique available in PhotoShop
ResampleCommand resampler = new ResampleCommand(newSize, ResampleMethod.BiCubic);
AtalaImage newImage = resampler.Apply(oldImage).Image;

in addition, dotImage includes 140 some odd image processing commands including many filters similar to those in PhotoShop, if that's what you're looking for.

How to open a page in a new window or tab from code-behind

You can use scriptmanager.registerstartupscript to call a JavaScript function.

Inside that function, you can open a new window.

Remove last item from array

Using the spread operator:

_x000D_
_x000D_
const a = [1,2,3]
const [, ...rest] = a.reverse();
const withoutLast = rest.reverse();
console.log(withoutLast)
_x000D_
_x000D_
_x000D_

Is it possible to print a variable's type in standard C++?

Copying from this answer: https://stackoverflow.com/a/56766138/11502722

I was able to get this somewhat working for C++ static_assert(). The wrinkle here is that static_assert() only accepts string literals; constexpr string_view will not work. You will need to accept extra text around the typename, but it works:

template<typename T>
constexpr void assertIfTestFailed()
{
#ifdef __clang__
    static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(__GNUC__)
    static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(_MSC_VER)
    static_assert(testFn<T>(), "Test failed on this used type: " __FUNCSIG__);
#else
    static_assert(testFn<T>(), "Test failed on this used type (see surrounding logged error for details).");
#endif
    }
}

MSVC Output:

error C2338: Test failed on this used type: void __cdecl assertIfTestFailed<class BadType>(void)
... continued trace of where the erroring code came from ...

How to make exe files from a node.js app?

There are a lot of good answers here, but they're not all as straightforward as JXcore.

Once you have JXcore installed on windows, all you have to do is run:

jx package app.js "myAppName" -native

This will produce a .exe file that you can distribute and can be executed without any external dependencies whatsoever (you don't even need JXcore nor Node.js on the system).

Here's the documentation on that functionality: http://jxcore.com/packaging-code-protection/#cat-74

Edit 2018

That project is now dead but it is still hosted here: https://github.com/jxcore/jxcore-release (thanks @Elmue)

How to add background image for input type="button"?

background-image takes an url as a value. Use either

background-image: url ('/image/btn.png');

or

background: url ('/image/btn.png') no-repeat;

which is a shorthand for

background-image: url ('/image/btn.png');
background-repeat: no-repeat;

Also, you might want to look at the button HTML element for fancy submit buttons.

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

Then number of columns must match between both parts of the union.

In order to build the full path, you need to "aggregate" all values of the Location column. You still need to select the id and other columns inside the CTE in order to be able to join properly. You get "rid" of them by simply not selecting them in the outer select:

with q as 
(
   select ID, PartOf_LOC_id, Location, ' > ' + Location as path
   from tblLocation 
   where ID = 1 

   union all

   select child.ID, child.PartOf_LOC_id, Location, parent.path + ' > ' + child.Location 
   from tblLocation child
     join q parent on parent.ID = t.LOC_PartOf_ID
)
select path
from q;

How to move files from one git repo to another (not a clone), preserving history

If the paths for the files in question are the same in the two repos and you're wanting to bring over just one file or a small set of related files, one easy way to do this is to use git cherry-pick.

The first step is to bring the commits from the other repo into your own local repo using git fetch <remote-url>. This will leave FETCH_HEAD pointing to the head commit from the other repo; if you want to preserve a reference to that commit after you've done other fetches you may want to tag it with git tag other-head FETCH_HEAD.

You will then need to create an initial commit for that file (if it doesn't exist) or a commit to bring the file to a state that can be patched with the first commit from the other repo you want to bring in. You may be able to do this with a git cherry-pick <commit-0> if commit-0 introduced the files you want, or you may need to construct the commit 'by hand'. Add -n to the cherry-pick options if you need to modify the initial commit to, e.g., drop files from that commit you don't want to bring in.

After that, you can continue to git cherry-pick subsequent commits, again using -n where necessary. In the simplest case (all commits are exactly what you want and apply cleanly) you can give the full list of commits on the cherry-pick command line: git cherry-pick <commit-1> <commit-2> <commit-3> ....

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

The download from java.com which installs in /Library/Internet Plug-Ins is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home which you can then add to Eclipse via Preferences -> Java -> Installed JREs.

Git: can't undo local changes (error: path ... is unmerged)

This worked perfectly for me:

$ git reset -- foo/bar.txt
$ git checkout foo/bar.txt

Running two projects at once in Visual Studio

Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.

This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).

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

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

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

For example, considering the following markup:

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

You'll get the following result:

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

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

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

See MDN for more details:

php resize image on upload

If you want to use Imagick out of the box (included with most PHP distributions), it's as easy as...

$image = new Imagick();
$image_filehandle = fopen('some/file.jpg', 'a+');
$image->readImageFile($image_filehandle);

$image->scaleImage(100,200,FALSE);

$image_icon_filehandle = fopen('some/file-icon.jpg', 'a+');
$image->writeImageFile($image_icon_filehandle);

You will probably want to calculate width and height more dynamically based on the original image. You can get an image's current width and height, using the above example, with $image->getImageHeight(); and $image->getImageWidth();

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I confirm some methods proposed here that also worked for me : you have to put your local .json file in your public directory where fetch() is looking for (looking in http://localhost:3000/) for example : I use this fetch() in my src/App.js file:

componentDidMount(){
  fetch('./data/json-data.json')
  .then ( resp1 => resp1.json() )
  .then ( users1 => this.setState( {cards : users1} ) )
}

so I created public/data/json-data.json

and everything was fine then :)

What is the use of ObservableCollection in .net?

From Pro C# 5.0 and the .NET 4.5 Framework

The ObservableCollection<T> class is very useful in that it has the ability to inform external objects when its contents have changed in some way (as you might guess, working with ReadOnlyObservableCollection<T> is very similar, but read-only in nature). In many ways, working with the ObservableCollection<T> is identical to working with List<T>, given that both of these classes implement the same core interfaces. What makes the ObservableCollection<T> class unique is that this class supports an event named CollectionChanged. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified. Like any event, CollectionChanged is defined in terms of a delegate, which in this case is NotifyCollectionChangedEventHandler. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs as the second. Consider the following Main() method, which populates an observable collection containing Person objects and wires up the CollectionChanged event:

class Program
{
   static void Main(string[] args)
   {
     // Make a collection to observe and add a few Person objects.
     ObservableCollection<Person> people = new ObservableCollection<Person>()
     {
        new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
        new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
     };
     // Wire up the CollectionChanged event.
     people.CollectionChanged += people_CollectionChanged;
     // Now add a new item.
     people.Add(new Person("Fred", "Smith", 32));

     // Remove an item.
     people.RemoveAt(0);

     Console.ReadLine();
   }
   static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
   {
       // What was the action that caused the event?
        Console.WriteLine("Action for this event: {0}", e.Action);

        // They removed something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
        {
            Console.WriteLine("Here are the OLD items:");
            foreach (Person p in e.OldItems)
            {
                Console.WriteLine(p.ToString());
            }
            Console.WriteLine();
        }

        // They added something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            // Now show the NEW items that were inserted.
            Console.WriteLine("Here are the NEW items:");
            foreach (Person p in e.NewItems)
            {
                Console.WriteLine(p.ToString());
            }
        }
   }
}

The incoming NotifyCollectionChangedEventArgs parameter defines two important properties, OldItems and NewItems, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when items are added, removed, relocated, or reset. To discover which of these actions triggered the event, you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be tested against any of the following members of the NotifyCollectionChangedAction enumeration:

public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}

Members of System.Collections.ObjectModel

Getting Current time to display in Label. VB.net

Use Date.Now instead of DateTime.Now

How to get JSON response from http.Get

Your Problem were the slice declarations in your data structs (except for Track, they shouldn't be slices...). This was compounded by some rather goofy fieldnames in the fetched json file, which can be fixed via structtags, see godoc.

The code below parsed the json successfully. If you've further questions, let me know.

package main

import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type Tracks struct {
    Toptracks Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  Attr_info `json: "@attr"`
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable Streamable_info
    Artist     Artist_info   
    Attr       Track_attr_info `json: "@attr"`
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string `json: "#text"`
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func perror(err error) {
    if err != nil {
        panic(err)
    }
}

func get_content() {
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)
    perror(err)
    defer res.Body.Close()

    decoder := json.NewDecoder(res.Body)
    var data Tracks
    err = decoder.Decode(&data)
    if err != nil {
        fmt.Printf("%T\n%s\n%#v\n",err, err, err)
        switch v := err.(type){
            case *json.SyntaxError:
                fmt.Println(string(body[v.Offset-40:v.Offset]))
        }
    }
    for i, track := range data.Toptracks.Track{
        fmt.Printf("%d: %s %s\n", i, track.Artist.Name, track.Name)
    }
}

func main() {
    get_content()
}

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

Does GPS require Internet?

GPS does not need any kind of internet or wireless connection, but there are technologies like A-GPS that use the mobile network to shorten the time to first fix, or the initial positioning or increase the precision in situations when there is a low satellite visibility.

Android phones tend to use A-GPS. If there is no connectivity, they use pure GPS. They do not override the data network mode. If you deactivated it, the phone won't use any data connection (which is handy if you are abroad, and do not want to pay expensive data roaming).

How to convert std::string to LPCWSTR in C++ (Unicode)

Thanks for the link to the MSDN article. This is exactly what I was looking for.

std::wstring s2ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

std::wstring stemp = s2ws(myString);
LPCWSTR result = stemp.c_str();

Convert ascii char[] to hexadecimal char[] in C

Use the %02X format parameter:

printf("%02X",word[i]);

More info can be found here: http://www.cplusplus.com/reference/cstdio/printf/

NoClassDefFoundError in Java: com/google/common/base/Function

I wanted to try a simple class outside IDE and stuff. So downloaded selenium zip from website and run the class like this:

java -cp selenium-2.50.1/*:selenium-2.50.1/libs/*:. my/package/MyClass <params>

I had the issue that I initially used lib instead of libs. I didn't need to add selenium standalone jar. This is Java 8 that understands wildcards in classpath. I think java 7 would also do.

ES6 Class Multiple inheritance

use extent with custom function to handle multiple inheritance with es6

_x000D_
_x000D_
var aggregation = (baseClass, ...mixins) => {_x000D_
    let base = class _Combined extends baseClass {_x000D_
        constructor (...args) {_x000D_
            super(...args)_x000D_
            mixins.forEach((mixin) => {_x000D_
                mixin.prototype.initializer.call(this)_x000D_
            })_x000D_
        }_x000D_
    }_x000D_
    let copyProps = (target, source) => {_x000D_
        Object.getOwnPropertyNames(source)_x000D_
            .concat(Object.getOwnPropertySymbols(source))_x000D_
            .forEach((prop) => {_x000D_
            if (prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/))_x000D_
                return_x000D_
            Object.defineProperty(target, prop, Object.getOwnPropertyDescriptor(source, prop))_x000D_
        })_x000D_
    }_x000D_
    mixins.forEach((mixin) => {_x000D_
        copyProps(base.prototype, mixin.prototype)_x000D_
        copyProps(base, mixin)_x000D_
    })_x000D_
    return base_x000D_
}_x000D_
_x000D_
class Colored {_x000D_
    initializer ()     { this._color = "white" }_x000D_
    get color ()       { return this._color }_x000D_
    set color (v)      { this._color = v }_x000D_
}_x000D_
_x000D_
class ZCoord {_x000D_
    initializer ()     { this._z = 0 }_x000D_
    get z ()           { return this._z }_x000D_
    set z (v)          { this._z = v }_x000D_
}_x000D_
_x000D_
class Shape {_x000D_
    constructor (x, y) { this._x = x; this._y = y }_x000D_
    get x ()           { return this._x }_x000D_
    set x (v)          { this._x = v }_x000D_
    get y ()           { return this._y }_x000D_
    set y (v)          { this._y = v }_x000D_
}_x000D_
_x000D_
class Rectangle extends aggregation(Shape, Colored, ZCoord) {}_x000D_
_x000D_
var rect = new Rectangle(7, 42)_x000D_
rect.z     = 1000_x000D_
rect.color = "red"_x000D_
console.log(rect.x, rect.y, rect.z, rect.color)
_x000D_
_x000D_
_x000D_

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

I had this problem when i was trying to query by passing a Set and i didn't used In

example

problem : repository.findBySomeSetOfData(setOfData);

solution : repository.findBySomeSetOfDataIn(setOfData);

How to add element into ArrayList in HashMap

Typical code is to create an explicit method to add to the list, and create the ArrayList on the fly when adding. Note the synchronization so the list only gets created once!

@Override
public synchronized boolean addToList(String key, Item item) {
   Collection<Item> list = theMap.get(key);
   if (list == null)  {
      list = new ArrayList<Item>();  // or, if you prefer, some other List, a Set, etc...
      theMap.put(key, list );
   }

   return list.add(item);
}

How do you find the row count for all your tables in Postgres

Not sure if an answer in bash is acceptable to you, but FWIW...

PGCOMMAND=" psql -h localhost -U fred -d mydb -At -c \"
            SELECT   table_name
            FROM     information_schema.tables
            WHERE    table_type='BASE TABLE'
            AND      table_schema='public'
            \""
TABLENAMES=$(export PGPASSWORD=test; eval "$PGCOMMAND")

for TABLENAME in $TABLENAMES; do
    PGCOMMAND=" psql -h localhost -U fred -d mydb -At -c \"
                SELECT   '$TABLENAME',
                         count(*) 
                FROM     $TABLENAME
                \""
    eval "$PGCOMMAND"
done

Combine :after with :hover

 #alertlist li:hover:after,#alertlist li.selected:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}?

jsFiddle Link

How to set HTML Auto Indent format on Sublime Text 3?

One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.

Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:

p [tab][enter] Hello world!

When you type p [tab] Emmet expands it to:

<p></p>

Pressing [enter] then further expands it to:

<p>

</p>

With the cursor indented and on the line between the tags. Meaning that typing text results in:

<p>
    Hello, world!
</p>

C# removing items from listbox

Sorry guys i had to adjust the string

sqldatapull = dr[0].ToString();
                if (sqldatapull.StartsWith("OBJECT"))
                {
                    sqldatapull = "";
                }
                listBox1.Items.Add(sqldatapull);
                for (int i = listBox1.Items.Count - 1; i >= 0; i--)
                {
                    if (String.IsNullOrEmpty(listBox1.Items[i] as String))
                        listBox1.Items.RemoveAt(i);
                }
            }

Add "Are you sure?" to my excel button, how can I?

Just make a custom userform that is shown when the "delete" button is pressed, then link the continue button to the actual code that does the deleting. Make the cancel button hide the userform.

Turning off hibernate logging console output

Try to set more reasonable logging level. Setting logging level to info means that only log event at info or higher level (warn, error and fatal) are logged, that is debug logging events are ignored.

log4j.logger.org.hibernate=info

or in XML version of log4j config file:

<logger name="org.hibernate">
  <level value="info"/> 
</logger>

See also log4j manual.

Can't push to GitHub because of large file which I already deleted

I had a similar issue and used the step above to remove the file. It worked perfectly.

I then got an error on a second file that I needed to remove: remote: error: File <path/filename> is 109.99 MB; this exceeds GitHub's file size limit of 100.00 MB

I tried the same step, got an error: "A previous backup already exists in <path/filename>"

From research on this website I used the command: git filter-branch --force --index-filter "git rm --cached --ignore-unmatch <path/filename>" --prune-empty --tag-name-filter cat -- --all

Worked great, and the large files were removed.

Unbelievably, the push still failed with another error: error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 104 fatal: The remote end hung up unexpectedly

This I fixed by directly modifying the .git config file - postBuffer = 999999999

After that the push went through!

How do I search within an array of hashes by hash values in ruby?

You're looking for Enumerable#select (also called find_all):

@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
#      { "age" => 50, "father" => "Batman" } ]

Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers] for which block is not false."

how to specify local modules as npm package dependencies

If it's acceptible to simply publish your modules preinstalled in node_modules alongside your other files, you can do it like this:

// ./node_modules/foo/package.json
{ 
  "name":"foo",
  "version":"0.0.1",
  "main":"index.js"
}

// ./package.json
...
"dependencies": {
  "foo":"0.0.1",
  "bar":"*"
}

// ./app.js
var foo = require('foo');

You may also want to store your module on git and tell your parent package.json to install the dependency from git: https://npmjs.org/doc/json.html#Git-URLs-as-Dependencies

How to compare only date components from DateTime in EF?

Here's a different way to do it, but it's only useful if SecondDate is a variable you're passing in:

DateTime startDate = SecondDate.Date;
DateTime endDate = startDate.AddDays(1).AddTicks(-1);
...
e => e.FirstDate.Value >= startDate && e.FirstDate.Value <= endDate

I think that should work

Set HTTP header for one request

Try this, perhaps it works ;)

.factory('authInterceptor', function($location, $q, $window) {


return {
    request: function(config) {
      config.headers = config.headers || {};

      config.headers.Authorization = 'xxxx-xxxx';

      return config;
    }
  };
})

.config(function($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
})

And make sure your back end works too, try this. I'm using RESTful CodeIgniter.

class App extends REST_Controller {
    var $authorization = null;

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
            die();
        }

        if(!$this->input->get_request_header('Authorization')){
            $this->response(null, 400);    
        }

        $this->authorization = $this->input->get_request_header('Authorization');
    }

}

How to manually force a commit in a @Transactional method?

Why don't you use spring's TransactionTemplate to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional method, but given that it's a test I would opt for programmatic control of your transactions.

Also note that the @Transactional annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!

@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {

@Autowired
PlatformTransactionManager platformTransactionManager;

TransactionTemplate transactionTemplate;

@Before
public void setUp() throws Exception {
    transactionTemplate = new TransactionTemplate(platformTransactionManager);
}

@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {

    final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
        @Override
        public Contract doInTransaction(TransactionStatus status) {
            Contract c = contractDOD.getNewTransientContract(15);
            contractRepository.save(c);
            return c;
        }
    });

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 5; ++i) {
        executorService.execute(new Runnable() {
            @Override  //note that there is no @Transactional configured for the method
            public void run() {
                transactionTemplate.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {
                        // do whatever you want to do with c1
                        return null;
                    }
                });
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            // validate test results in transaction
            return null;
        }
    });
}

}

Toolbar overlapping below status bar

None of the answers worked for me, but this is what finally worked after i set android:fitSystemWindows on the root view(I set these in styles v21):

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

Make sure you don't have the following line as AS puts it by default:

<item name="android:statusBarColor">@android:color/transparent</item>

Can I install Python 3.x and 2.x on the same Windows computer?

When you add both to environment variables there will a be a conflict because the two executable have the same name: python.exe.

Just rename one of them. In my case I renamed it to python3.exe.

So when I run python it will execute python.exe which is 2.7 and when I run python3 it will execute python3.exe which is 3.6

enter image description here

How can I make a time delay in Python?

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

How to call a REST web service API from JavaScript?

Without a doubt, the simplest method uses an invisible FORM element in HTML specifying the desired REST method. Then the arguments can be inserted into input type=hidden value fields using JavaScript and the form can be submitted from the button click event listener or onclick event using one line of JavaScript. Here is an example that assumes the REST API is in file REST.php:

<body>
<h2>REST-test</h2>
<input type=button onclick="document.getElementById('a').submit();"
    value="Do It">
<form id=a action="REST.php" method=post>
<input type=hidden name="arg" value="val">
</form>
</body>

Note that this example will replace the page with the output from page REST.php. I'm not sure how to modify this if you wish the API to be called with no visible effect on the current page. But it's certainly simple.

check if a std::vector contains a certain object?

See question: How to find an item in a std::vector?

You'll also need to ensure you've implemented a suitable operator==() for your object, if the default one isn't sufficient for a "deep" equality test.

How do I make a "div" button submit the form its sitting in?

To keep the scripting in one place rather than using onClick in the HTML tag, add the following code to your script block:

$('#id-of-the-button').click(function() {document.forms[0].submit()});

Which assumes you just have the one form on the page.

Converting byte array to String (Java)

You can try this.

String s = new String(bytearray);

JBoss vs Tomcat again

I have also read that for some servers one for example needs only annotate persistence contexts, but in some servers, the injection should be done manually.

How can I do factory reset using adb in android?

Warning

From @sidharth: "caused my lava iris alfa to go into a bootloop :("


For my Motorola Nexus 6 running Android Marshmallow 6.0.1 I did:

adb devices       # Check the phone is running
adb reboot bootloader
# Wait a few seconds
fastboot devices  # Check the phone is in bootloader
fastboot -w       # Wipe user data

How to extract closed caption transcript from YouTube video?

I just got this easily done manually by opening the transcript at the beginning of the video and left-clicking and dragging at the time 00:00 marker with the shift key pressed over a few lines at the beginning.

I then advanced the video to near the end. When the video stopped, I clicked the end of the last sentence whilst holding down the shift key once more. With CTRL-C I copied the text to the clipboard and pasted it into an editor.

Done!

Caveat: Be sure to have no RDP-Windows sharing the clipboard or Software such as Teamviewer is running at the same time as this procedure will overflow their buffers where a large amount of text is copied.

Python Image Library fails with message "decoder JPEG not available" - PIL

The followed works on ubuntu 12.04:

pip uninstall PIL
apt-get install libjpeg-dev
apt-get install libfreetype6-dev
apt-get install zlib1g-dev
apt-get install libpng12-dev
pip install PIL --upgrade

when your see "-- JPEG support avaliable" that means it works.

But, if it still doesn't work when your edit your jpeg image, check the python path !! my python path missed /usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/, so I edit the ~/.bashrc add the following code to this file:

Edit: export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/

then, finally, it works!!

Split string with JavaScript

var wrapper = $(document.body);

strings = [
    "19 51 2.108997",
    "20 47 2.1089"
];

$.each(strings, function(key, value) {
    var tmp = value.split(" ");
    $.each([
        tmp[0] + " " + tmp[1],
        tmp[2]
    ], function(key, value) {
        $("<span>" + value + "</span>").appendTo(wrapper);
    }); 
});

How to test if a file is a directory in a batch script?

A variation of @batchman61's approach (checking the Directory attribute).

This time I use an external 'find' command.

(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)

@ECHO OFF
SETLOCAL EnableExtensions
ECHO.%~a1 | find "d" >NUL 2>NUL && (
    ECHO %1 is a directory
)

Outputs yes on:

  • Directories.
  • Directory symbolic links or junctions.
  • Broken directory symbolic links or junctions. (Doesn't try to resolve links.)
  • Directories which you have no read permission on (e.g. "C:\System Volume Information")

How to change UIButton image in Swift

in swift 3.0:

@IBOutlet weak var selectionButton: UIButton!

selectionButton.setImage(UIImage.addBlueIcon, for: .selected)

PHP array: count or sizeof?

Both are used to count elements in a array. sizeof() function is an alias of count() function used in PHP. However, count() function is faster and butter than sizeof().

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));  //copy

In this case, list1 is of type ArrayList.

List<Integer> list2 = Arrays.asList(ia);

Here, the list is returned as a List view, meaning it has only the methods attached to that interface. Hence why some methods are not allowed on list2.

ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));

Here, you ARE creating a new ArrayList. You're simply passing it a value in the constructor. This is not an example of casting. In casting, it might look more like this:

ArrayList list1 = (ArrayList)Arrays.asList(ia);

How to ignore HTML element from tabindex?

Such hack like "tabIndex=-1" not work for me with Chrome v53.

This is which works for chrome, and most browsers:

_x000D_
_x000D_
function removeTabIndex(element) {_x000D_
    element.removeAttribute('tabindex');_x000D_
}
_x000D_
<input tabIndex="1" />_x000D_
<input tabIndex="2" id="notabindex" />_x000D_
<input tabIndex="3" />_x000D_
<button tabIndex="4" onclick="removeTabIndex(document.getElementById('notabindex'))">Remove tabindex</button>
_x000D_
_x000D_
_x000D_

Creating a ZIP archive in memory using System.IO.Compression

Just in case, if anyone wants to save a dynamic zip file through SaveFileDialog.

        var logFileName = "zip_filename.zip";
        appLogSaver.FileName = logFileName;
        appLogSaver.Filter = "LogFiles|*.zip";
        appLogSaver.DefaultExt = "zip";
        DialogResult resDialog = appLogSaver.ShowDialog();

        if (resDialog.ToString() == "OK")
        {
            System.IO.FileStream fs = (System.IO.FileStream)appLogSaver.OpenFile();

            using (var memoryStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    var demoFile = archive.CreateEntry("foo.txt");
                    using (var entryStream = demoFile.Open())
                    {
                        using (var streamWriter = new StreamWriter(entryStream))
                        {
                            //read your existing file and put the content here 
                            streamWriter.Write("Bar!");
                        }
                    }

                    var demoFile2 = archive.CreateEntry("foo2.txt");
                    using (var entryStream = demoFile2.Open())
                    {
                        using (var streamWriter = new StreamWriter(entryStream))
                        {
                            streamWriter.Write("Bar2!");
                        }
                    }
                }

                memoryStream.Seek(0, SeekOrigin.Begin);
                memoryStream.CopyTo(fs);
            }
            fs.Close();
        }

Does Android keep the .apk files? if so where?

To find an apk, download and Install the Bluetooth App Sender from Play store. Once installation completes open the Bluetooth App Sender. It will show all the apps (.apk) installed in your device, then you can easily transfer the app to your PC through Bluetooth.

Changing the highlight color when selecting text in an HTML text input

I guess this can help :

selection styles

It's possible to define color and background for text the user selects.

Try it below. If you select something and it looks like this, your browser supports selection styles.

This is the paragraph with normal ::selection.

This is the paragraph with ::-moz-selection.

This is the paragraph with ::-webkit-selection.

Testsheet:

p.normal::selection {
  background:#cc0000;
  color:#fff;
}

p.moz::-moz-selection {
  background:#cc0000;
  color:#fff;
}

p.webkit::-webkit-selection {
  background:#cc0000;
  color:#fff;
}

Quoted from Quirksmode

How to stop a JavaScript for loop?

To stop a for loop early in JavaScript, you use break:

var remSize = [], 
    szString,
    remData,
    remIndex,
    i;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {      
     // I'm looking for the index i, when the condition is true
     if (remSize[i].size === remData.size) {
          remIndex = i;
          break;       // <=== breaks out of the loop early
     }
}

If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex (to find the entry's index) or Array#find (to find the entry itself), both of which can be shimmed/polyfilled:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = remSize.findIndex(function(entry) {
     return entry.size === remData.size;
});

Array#find:

var remSize = [], 
    szString,
    remData,
    remEntry;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remEntry = remSize.find(function(entry) {
     return entry.size === remData.size;
});

Array#findIndex stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1 if the callback never returns a truthy value. Array#find also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined if the callback never returns a truthy value).

If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some function on arrays, which calls a callback until the callback returns a truthy value:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
    if (entry.size === remData.size) {
        remIndex = index;
        return true; // <== Equivalent of break for `Array#some`
    }
});

If you're using jQuery, you can use jQuery.each to loop through an array; that would look like this:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
    if (entry.size === remData.size) {
        remIndex = index;
        return false; // <== Equivalent of break for jQuery.each
    }
});

How do I lowercase a string in Python?

Use .lower() - For example:

s = "Kilometer"
print(s.lower())

The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()

What is the best way to use a HashMap in C++?

The standard library includes the ordered and the unordered map (std::map and std::unordered_map) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.

An example with (ordered) std::map:

#include <map>
#include <iostream>
#include <cassert>

int main(int argc, char **argv)
{
  std::map<std::string, int> m;
  m["hello"] = 23;
  // check if key is present
  if (m.find("world") != m.end())
    std::cout << "map contains key world!\n";
  // retrieve
  std::cout << m["hello"] << '\n';
  std::map<std::string, int>::iterator i = m.find("hello");
  assert(i != m.end());
  std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
  return 0;
}

Output:

23
Key: hello Value: 23

If you need ordering in your container and are fine with the O(log n) runtime then just use std::map.

Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map, which has a similar to std::map API (e.g. in the above example you just have to search and replace map with unordered_map).

The unordered_map container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11 to the CXXFLAGS).

Even before the C++11 release GCC supported unordered_map - in the namespace std::tr1. Thus, for old GCC compilers you can try to use it like this:

#include <tr1/unordered_map>

std::tr1::unordered_map<std::string, int> m;

It is also part of boost, i.e. you can use the corresponding boost-header for better portability.

Automatically scroll down chat div

I prefer to use Vanilla JS

let chatWrapper = document.querySelector('#chat-messages');
chatWrapper.scrollTo(0, chatWrapper.offsetHeight );

where element.scrollTo(x-coord, y-coord)

Use a LIKE statement on SQL Server XML Datatype

Another option is to search the XML as a string by converting it to a string and then using LIKE. However as a computed column can't be part of a WHERE clause you need to wrap it in another SELECT like this:

SELECT * FROM
    (SELECT *, CONVERT(varchar(MAX), [COLUMNA]) as [XMLDataString] FROM TABLE) x
WHERE [XMLDataString] like '%Test%'

What's the difference between OpenID and OAuth?

OpenId - Used only for Authentication.

OAuth - Used for both Authentication and Authorization. Authorization depends on the access_token which comes as part of JWT token. It can have details of user permissions or any useful information.

Both can rely on 3rd party auth provider which maintains their accounts. For example OKTA identity provider, User provides the credentials on OKTA login page and on successful login the user is redirected on the consumer application with the JWT token in the header.

Merge / convert multiple PDF files into one PDF

I'm sorry, I managed to find the answer myself using google and a bit of luck : )

For those interested;

I installed the pdftk (pdf toolkit) on our debian server, and using the following command I achieved desired output:

pdftk file1.pdf file2.pdf cat output output.pdf

OR

gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf file1.pdf file2.pdf file3.pdf ...

This in turn can be piped directly into pdf2ps.

What is null in Java?

Is null an instance of anything?

No, there is no type which null is an instanceof.

15.20.2 Type Comparison Operator instanceof

RelationalExpression:
    RelationalExpression instanceof ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

This means that for any type E and R, for any E o, where o == null, o instanceof R is always false.


What set does 'null' belong to?

JLS 4.1 The Kinds of Types and Values

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.


What is null?

As the JLS quote above says, in practice you can simply pretend that it's "merely a special literal that can be of any reference type".

In Java, null == null (this isn't always the case in other languages). Note also that by contract, it also has this special property (from java.lang.Object):

public boolean equals(Object obj)

For any non-null reference value x, x.equals(null) should return false.

It is also the default value (for variables that have them) for all reference types:

JLS 4.12.5 Initial Values of Variables

  • Each class variable, instance variable, or array component is initialized with a default value when it is created:
    • For all reference types, the default value is null.

How this is used varies. You can use it to enable what is called lazy initialization of fields, where a field would have its initial value of null until it's actually used, where it's replaced by the "real" value (which may be expensive to compute).

There are also other uses. Let's take a real example from java.lang.System:

public static Console console()

Returns: The system console, if any, otherwise null.

This is a very common use pattern: null is used to denote non-existence of an object.

Here's another usage example, this time from java.io.BufferedReader:

public String readLine() throws IOException

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.

So here, readLine() would return instanceof String for each line, until it finally returns a null to signify the end. This allows you to process each line as follows:

String line;
while ((line = reader.readLine()) != null) {
   process(line);
}

One can design the API so that the termination condition doesn't depend on readLine() returning null, but one can see that this design has the benefit of making things concise. Note that there is no problem with empty lines, because an empty line "" != null.

Let's take another example, this time from java.util.Map<K,V>:

V get(Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

Here we start to see how using null can complicate things. The first statement says that if the key isn't mapped, null is returned. The second statement says that even if the key is mapped, null can also be returned.

In contrast, java.util.Hashtable keeps things simpler by not permitting null keys and values; its V get(Object key), if returns null, unambiguously means that the key isn't mapped.

You can read through the rest of the APIs and find where and how null is used. Do keep in mind that they aren't always the best practice examples.

Generally speaking, null are used as a special value to signify:

  • Uninitialized state
  • Termination condition
  • Non-existing object
  • An unknown value

How is it represented in the memory?

In Java? None of your concern. And it's best kept that way.


Is null a good thing?

This is now borderline subjective. Some people say that null causes many programmer errors that could've been avoided. Some say that in a language that catches NullPointerException like Java, it's good to use it because you will fail-fast on programmer errors. Some people avoid null by using Null object pattern, etc.

This is a huge topic on its own, so it's best discussed as answer to another question.

I will end this with a quote from the inventor of null himself, C.A.R Hoare (of quicksort fame):

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

The video of this presentation goes deeper; it's a recommended watch.

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

Can I get div's background-image url?

I'm using this one

  function getBackgroundImageUrl($element) {
    if (!($element instanceof jQuery)) {
      $element = $($element);
    }

    var imageUrl = $element.css('background-image');
    return imageUrl.replace(/(url\(|\)|'|")/gi, ''); // Strip everything but the url itself
  }

Can we define min-margin and max-margin, max-padding and min-padding in css?

I was faced with the same problem today. Apparently the solution is as simple as using :

padding: calc(*put fixed pixels here*px + *put your required %age here*%) 

Note that you do have to decrement the required %age a little to account for fixed pixels.

php check if array contains all array values from another array

I think you're looking for the intersect function

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )

array_intersect() returns an array containing all values of array1 that are present in all the arguments. Note that keys are preserved.

http://www.php.net/manual/en/function.array-intersect.php

Socket.io + Node.js Cross-Origin Request Blocked

I tried above and nothing worked for me. Following code is from socket.io documentation and it worked.

io.origins((origin, callback) => {
  if (origin !== 'https://foo.example.com') {
      return callback('origin not allowed', false);
  }
  callback(null, true);
});

biggest integer that can be stored in a double

It is true that, for 64-bit IEEE754 double, all integers up to 9007199254740992 == 2^53 can be exactly represented.

However, it is also worth mentioning that all representable numbers beyond 4503599627370496 == 2^52 are integers. Beyond 2^52 it becomes meaningless to test whether or not they are integers, because they are all implicitly rounded to a nearby representable value.

In the range 2^51 to 2^52, the only non-integer values are the midpoints ending with ".5", meaning any integer test after a calculation must be expected to yield at least 50% false answers.

Below 2^51 we also have ".25" and ".75", so comparing a number with its rounded counterpart in order to determine if it may be integer or not starts making some sense.

TLDR: If you want to test whether a calculated result may be integer, avoid numbers larger than 2251799813685248 == 2^51

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

Does Ruby have a string.startswith("abc") built in method?

Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.

You could always use a regular expression though:

if SomeString.match(/^abc/) 
   # SomeString starts with abc

^ means "start of string" in regular expressions

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Disable sorting on last column when using jQuery DataTables

Try to use minus sign for count from backside

<script>
    $(document).ready(function () {
        $('#example-2').DataTable({               
            'order':[],
            'columnDefs': [{
                "targets": [-1],
                "orderable": false
            }]
        });
    });
</script>

SQL Server: IF EXISTS ; ELSE

Try this:

Update TableB Set
  Code = Coalesce(
    (Select Max(Value)
    From TableA 
    Where Id = b.Id), 123)
From TableB b

How to use BigInteger?

sum = sum.add(BigInteger.valueOf(i))

The BigInteger class is immutable, hence you can't change its state. So calling "add" creates a new BigInteger, rather than modifying the current.

How do format a phone number as a String in Java?

If you really need the right way then you can use Google's recently open sourced libphonenumber

jquery, selector for class within id

You can use the class selector along with descendant selector

$("#my_id .my_class")

Using Chrome, how to find to which events are bound to an element

Give it a try to the jQuery Audit extension (https://chrome.google.com/webstore/detail/jquery-audit/dhhnpbajdcgdmbbcoakfhmfgmemlncjg), after installing follow these steps:

  1. Inspect the element
  2. On the new 'jQuery Audit' tab expand the Events property
  3. Choose for the Event you need
  4. From the handler property, right click over function and select 'Show function definition'
  5. You will now see the Event binding code
  6. Click on the 'Pretty print' button for a more readable view of the code

Getting one value from a tuple

General

Single elements of a tuple a can be accessed -in an indexed array-like fashion-

via a[0], a[1], ... depending on the number of elements in the tuple.

Example

If your tuple is a=(3,"a")

  • a[0] yields 3,
  • a[1] yields "a"

Concrete answer to question

def tup():
  return (3, "hello")

tup() returns a 2-tuple.

In order to "solve"

i = 5 + tup()  # I want to add just the three

you select the 3 by

tup()[0|    #first element

so in total

i = 5 + tup()[0]

Alternatives

Go with namedtuple that allows you to access tuple elements by name (and by index). Details at https://docs.python.org/3/library/collections.html#collections.namedtuple

>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

Definition of int64_t

int64_t is guaranteed by the C99 standard to be exactly 64 bits wide on platforms that implement it, there's no such guarantee for a long which is at least 32 bits so it could be more.

§7.18.1.3 Exact-width integer types 1 The typedef name intN_t designates a signed integer type with width N , no padding bits, and a two’s complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits.

determine DB2 text string length

This will grab records with strings (in the fieldName column) that are 10 characters long:

 select * from table where length(fieldName)=10

Open new Terminal Tab from command line (Mac OS X)

If you use oh-my-zsh (which every trendy geek should use), after activating the "osx" plugin in .zshrc, simply enter the tab command; it will open a new tab and cd in the directory your were on.

How can I check if PostgreSQL is installed or not via Linux script?

And if everything else fails from these great choice of answers, you can always use "find" like this. Or you may need to use sudo

If you are root, just type $$> find / -name 'postgres'

If you are a user, you will need sudo priv's to run it through all the directories

I run it this way, from the / base to find the whole path that the element is found in. This will return any files or directories with the "postgres" in it.

You could do the same thing looking for the pg_hba.conf or postgresql.conf files also.

ParseError: not well-formed (invalid token) using cElementTree

What helped me with that error was Juan's answer - https://stackoverflow.com/a/20204635/4433222 But wasn't enough - after struggling I found out that an XML file needs to be saved with UTF-8 without BOM encoding.

The solution wasn't working for "normal" UTF-8.

Python, print all floats to 2 decimal places in output

Well I would atleast clean it up as follows:

print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4)

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

Component based game engine design

I am currently researching this exact topic in the many (MANY) threads at GameDev.net and found the following two solutions to be good candidates on what I will develop for my game:

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

stop all instances of node.js server

Use the following command to kill and restart node server from batch file

    @echo off
cd "D:\sam\Projects\Node"
taskkill /IM node.exe -F
start /min cmd /C "node index.js"
goto :EOF

Sequel Pro Alternative for Windows

Toad for MySQL by Quest is free for non-commercial use. I really like the interface and it's quite powerful if you have several databases to work with (for example development, test and production servers).

From the website:

Toad® for MySQL is a freeware development tool that enables you to rapidly create and execute queries, automate database object management, and develop SQL code more efficiently. It provides utilities to compare, extract, and search for objects; manage projects; import/export data; and administer the database. Toad for MySQL dramatically increases productivity and provides access to an active user community.

Set inputType for an EditText Programmatically?

This may be of help to others like me who wanted to toggle between password and free-text mode. I tried using the input methods suggested but it only worked in one direction. I could go from password to text but then I could not revert. For those trying to handle a toggle (eg a show Password check box) use

       @Override
        public void onClick(View v)
        {
            if(check.isChecked())
            {
                edit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                Log.i(TAG, "Show password");
            }
            else
            {
                edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                Log.i(TAG, "Hide password");
            }
        }

I have to credit this for the solution. Wish I had found that a few hours ago!

UTF-8: General? Bin? Unicode?

In general, utf8_general_ci is faster than utf8_unicode_ci, but less correct.

Here is the difference:

For any Unicode character set, operations performed using the _general_ci collation are faster than those for the _unicode_ci collation. For example, comparisons for the utf8_general_ci collation are faster, but slightly less correct, than comparisons for utf8_unicode_ci. The reason for this is that utf8_unicode_ci supports mappings such as expansions; that is, when one character compares as equal to combinations of other characters. For example, in German and some other languages “ß” is equal to “ss”. utf8_unicode_ci also supports contractions and ignorable characters. utf8_general_ci is a legacy collation that does not support expansions, contractions, or ignorable characters. It can make only one-to-one comparisons between characters.

Quoted from: http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html

For more detailed explanation, please read the following post from MySQL forums: http://forums.mysql.com/read.php?103,187048,188748

As for utf8_bin: Both utf8_general_ci and utf8_unicode_ci perform case-insensitive comparison. In constrast, utf8_bin is case-sensitive (among other differences), because it compares the binary values of the characters.

Oracle - Insert New Row with Auto Incremental ID

ELXAN@DB1> create table cedvel(id integer,ad varchar2(15));

Table created.

ELXAN@DB1> alter table cedvel add constraint pk_ad primary key(id);

Table altered.

ELXAN@DB1> create sequence test_seq start with 1 increment by 1;

Sequence created.

ELXAN@DB1> create or replace trigger ad_insert
before insert on cedvel
REFERENCING NEW AS NEW OLD AS OLD
for each row
begin
    select test_seq.nextval into :new.id from dual;
end;
/  2    3    4    5    6    7    8 

Trigger created.

ELXAN@DB1> insert into cedvel (ad) values ('nese');

1 row created.

php date validation

You could use checkdate. For example, something like this:

$test_date = '03/22/2010';
$test_arr  = explode('/', $test_date);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
    // valid date ...
}

A more paranoid approach, that doesn't blindly believe the input:

$test_date = '03/22/2010';
$test_arr  = explode('/', $test_date);
if (count($test_arr) == 3) {
    if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
        // valid date ...
    } else {
        // problem with dates ...
    }
} else {
    // problem with input ...
}

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

This is solved for me when I update maven and check the option "Force update of Snapshots/Releases" in Eclipse. this clears all errors. So right click on project -> Maven -> update project, then check the above option -> Ok. Hope this helps you.

How to add image that is on my computer to a site in css or html?

If you just want to see how your picture will look on the website without uploading it to the server or without running your website on a local server, I think a very simple solution will be to convert your picture into a Base64 and add the contents into an IMG tag or as a background-image with CSS.

Reading json files in C++

Example (with complete source code) to read a json configuration file:

https://github.com/sksodhi/CodeNuggets/tree/master/json/config_read

 > pwd
/root/CodeNuggets/json/config_read
 > ls
Makefile  README.md  ReadJsonCfg.cpp  cfg.json
 > cat cfg.json 
{
   "Note" : "This is a cofiguration file",
   "Config" : { 
       "server-ip"     : "10.10.10.20",
       "server-port"   : "5555",
       "buffer-length" : 5000
   }   
}
 > cat ReadJsonCfg.cpp 
#include <iostream>
#include <json/value.h>
#include <jsoncpp/json/json.h>
#include <fstream>

void 
displayCfg(const Json::Value &cfg_root);

int
main()
{
    Json::Reader reader;
    Json::Value cfg_root;
    std::ifstream cfgfile("cfg.json");
    cfgfile >> cfg_root;

    std::cout << "______ cfg_root : start ______" << std::endl;
    std::cout << cfg_root << std::endl;
    std::cout << "______ cfg_root : end ________" << std::endl;

    displayCfg(cfg_root);
}       

void 
displayCfg(const Json::Value &cfg_root)
{
    std::string serverIP = cfg_root["Config"]["server-ip"].asString();
    std::string serverPort = cfg_root["Config"]["server-port"].asString();
    unsigned int bufferLen = cfg_root["Config"]["buffer-length"].asUInt();

    std::cout << "______ Configuration ______" << std::endl;
    std::cout << "server-ip     :" << serverIP << std::endl;
    std::cout << "server-port   :" << serverPort << std::endl;
    std::cout << "buffer-length :" << bufferLen<< std::endl;
}
 > cat Makefile 
CXX = g++
PROG = readjsoncfg

CXXFLAGS += -g -O0 -std=c++11

CPPFLAGS += \
        -I. \
        -I/usr/include/jsoncpp

LDLIBS = \
                 -ljsoncpp

LDFLAGS += -L/usr/local/lib $(LDLIBS)

all: $(PROG)
        @echo $(PROG) compilation success!

SRCS = \
        ReadJsonCfg.cpp
OBJS=$(subst .cc,.o, $(subst .cpp,.o, $(SRCS)))

$(PROG): $(OBJS)
        $(CXX) $^ $(LDFLAGS) -o $@

clean:
        rm -f $(OBJS) $(PROG) ./.depend

depend: .depend

.depend: $(SRCS)
        rm -f ./.depend
        $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM $^ >  ./.depend;

include .depend
 > make
Makefile:43: .depend: No such file or directory
rm -f ./.depend
g++ -g -O0 -std=c++11 -I. -I/usr/include/jsoncpp -MM ReadJsonCfg.cpp >  ./.depend;
g++ -g -O0 -std=c++11 -I. -I/usr/include/jsoncpp  -c -o ReadJsonCfg.o ReadJsonCfg.cpp
g++ ReadJsonCfg.o -L/usr/local/lib -ljsoncpp -o readjsoncfg
readjsoncfg compilation success!
 > ./readjsoncfg 
______ cfg_root : start ______
{
        "Config" : 
        {
                "buffer-length" : 5000,
                "server-ip" : "10.10.10.20",
                "server-port" : "5555"
        },
        "Note" : "This is a cofiguration file"
}
______ cfg_root : end ________
______ Configuration ______
server-ip     :10.10.10.20
server-port   :5555
buffer-length :5000
 > 

How to grep Git commit diffs or contents for a certain word?

You can try the following command:

git log --patch --color=always | less +/searching_string

or using grep in the following way:

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

Run this command in the parent directory where you would like to search.

JavaScript Nested function

Function-instantiation is allowed inside and outside of functions. Inside those functions, just like variables, the nested functions are local and therefore cannot be obtained from the outside scope.

function foo() {
    function bar() {
        return 1;
    }
    return bar();
}

foo manipulates bar within itself. bar cannot be touched from the outer scope unless it is defined in the outer scope.

So this will not work:

function foo() {
    function bar() {
        return 1;
    }
}

bar(); // throws error: bar is not defined

How do you simulate Mouse Click in C#?

I use the InvokeOnClick() method. It takes two arguments: Control and EventArgs. If you need the EventArgs, then create an instance of it and pass it in, else use InvokeOnClick(controlToClick, null);. You can use a variety of Mouse event related arguments that derive from EventArgs such as MouseEventArgs.

Listen for key press in .NET console app

The shortest way:

Console.WriteLine("Press ESC to stop");

while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
{
    // do something
}

Console.ReadKey() is a blocking function, it stops the execution of the program and waits for a key press, but thanks to checking Console.KeyAvailable first, the while loop is not blocked, but running until the Esc is pressed.

How to calculate an age based on a birthday?

Another clever way from that ancient thread:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

Provide an image for WhatsApp link sharing

I had the same problem, here is to solve.

It should be show up if you add meta og:image

The problem is whatsapp would not show image if you type without http:// and end with / For example, it show up image and description if you type http://google.com/ but not with google.com

Hope it helps someone.

Getting the parent div of element

If you are looking for a particular type of element that is further away than the immediate parent, you can use a function that goes up the DOM until it finds one, or doesn't:

// Find first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
  tagName = tagName.toLowerCase();

  while (el && el.parentNode) {
    el = el.parentNode;
    if (el.tagName && el.tagName.toLowerCase() == tagName) {
      return el;
    }
  }

  // Many DOM methods return null if they don't 
  // find the element they are searching for
  // It would be OK to omit the following and just
  // return undefined
  return null;
}

ssh : Permission denied (publickey,gssapi-with-mic)

Maybe you should assign the public key to the authorized_keys, the simple way to do this is using ssh-copy-id -i your-pub-key-file user@dest.

How to run .sql file in Oracle SQL developer tool to import database?

You can use Load function

Load TableName fullfilepath; 

How to modify list entries during for loop?

It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:

my_strings = ['a','b','c','d','e']
undesirable_strings = ['b','d']
for undesirable_string in undesirable_strings:
    for i in range(my_strings.count(undesirable_string)):
        my_strings.remove(undesirable_string)

which changes my_strings to ['a', 'c', 'e']

no suitable HttpMessageConverter found for response type

Or you can use

public void setSupportedMediaTypes(List supportedMediaTypes)

method which belongs to AbstractHttpMessageConverter<T>, to add some ContentTypes you like. This way can let the MappingJackson2HttpMessageConverter canRead() your response, and transform it to your desired Class, which on this case,is ProductList Class.

and I think this step should hooked up with the Spring Context initializing. for example, by using

implements ApplicationListener { ... }

Running Python on Windows for Node.js dependencies

Example : pg_config not executable / error node-gyp

Solution : On windows just try to add PATH Env -> C:\Program Files\PostgreSQL\12\bin

Work for me, Now i can use npm i pg-promise for example or other dependencies.

ASP.NET MVC3 - textarea with @Html.EditorFor

Someone asked about adding attributes (specifically, 'rows' and 'cols'). If you're using Razor, you could just do this:

@Html.TextAreaFor(model => model.Text, new { cols = 35, @rows = 3 })

That works for me. The '@' is used to escape keywords so they are treated as variables/properties.

Typescript Type 'string' is not assignable to type

You'll need to cast it:

export type Fruit = "Orange" | "Apple" | "Banana";
let myString: string = "Banana";

let myFruit: Fruit = myString as Fruit;

Also notice that when using string literals you need to use only one |

Edit

As mentioned in the other answer by @Simon_Weaver, it's now possible to assert it to const:

let fruit = "Banana" as const;

How does data binding work in AngularJS?

Angular.js creates a watcher for every model we create in view. Whenever a model is changed, an "ng-dirty" class is appeneded to the model, so the watcher will observe all models which have the class "ng-dirty" & update their values in the controller & vice versa.

Hash string in c#

using System.Security.Cryptography;

public static byte[] GetHash(string inputString)
{
    using (HashAlgorithm algorithm = SHA256.Create())
        return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}

public static string GetHashString(string inputString)
{
    StringBuilder sb = new StringBuilder();
    foreach (byte b in GetHash(inputString))
        sb.Append(b.ToString("X2"));

    return sb.ToString();
}

Additional Notes

  • Since MD5 and SHA1 are obsolete and insecure algorithms, this solution uses SHA256. Alternatively, you can use BCrypt or Scrypt as pointed out in comments.
  • Also, consider "salting" your hashes and use proven cryptographic algorithms, as pointed out in comments.

Proper way to renew distribution certificate for iOS

This was a really a helpful thread, I followed the same steps as @junjie mentioned but for me something weird happened, the below are the steps I did.

  1. Went to developer portal and revoked the certificate which was about to expire.
  2. Went to XCode6.4 and in the Account settings, the certificate still showed valid, I went crazy.
  3. Then I opened XCode7, there the certificate was shown with "Reset" button instead of create and I hit the reset button and later in the portal I was able to see an extended certificate present. This is what Apple says about Reset button

If Xcode detects an issue with a signing identity, it displays an appropriate action in Accounts preferences. If Xcode displays a Create button, the signing identity doesn’t exist in Member Center or on your Mac. If Xcode displays a Reset button, the signing identity is not usable on your Mac—for example, it is missing the private key. If you click the Reset button, Xcode revokes and requests the corresponding certificate.

  1. I tried creating an Appstore ipa with that, just to test and it worked fine so I am saved, but still not sure what has happened. May be I had multiple accounts configured in my Mac, dont know.

HTML 5: Is it <br>, <br/>, or <br />?

Both <br> and <br/> will do fine but I prefer <br/> because it's slightly more logical. It is logical to expect a closing tag whenever there is an opening tag. Therefore your code is slightly easier to read if you don't use an opening tag when there isn't going to be a closing tag.

All browser (except possibly some very old ones that don't matter) will display both exactly the same. However, <br> is not xHTML complient.

How to attach a file using mail command on Linux?

mailx might help as well. From the mailx man page:

-a file
     Attach the given file to the message.

Pretty easy, right?

How to print a query string with parameter values when using Hibernate

The solution is correct but logs also all bindings for the result objects. To prevent this it's possibile to create a separate appender and enable filtering, for example:

<!-- A time/date based rolling appender -->
<appender name="FILE_HIBERNATE" class="org.jboss.logging.appender.DailyRollingFileAppender">
    <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
    <param name="File" value="${jboss.server.log.dir}/hiber.log"/>
    <param name="Append" value="false"/>
    <param name="Threshold" value="TRACE"/>
    <!-- Rollover at midnight each day -->
    <param name="DatePattern" value="'.'yyyy-MM-dd"/>

    <layout class="org.apache.log4j.PatternLayout">
        <!-- The default pattern: Date Priority [Category] Message\n -->
        <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
    </layout>

    <filter class="org.apache.log4j.varia.StringMatchFilter">
        <param name="StringToMatch" value="bind" />
        <param name="AcceptOnMatch" value="true" />
    </filter>
    <filter class="org.apache.log4j.varia.StringMatchFilter">
        <param name="StringToMatch" value="select" />
        <param name="AcceptOnMatch" value="true" />
    </filter>  
    <filter class="org.apache.log4j.varia.DenyAllFilter"/>
</appender> 

<category name="org.hibernate.type">
  <priority value="TRACE"/>
</category>

<logger name="org.hibernate.type">
   <level value="TRACE"/> 
   <appender-ref ref="FILE_HIBERNATE"/>
</logger>

<logger name="org.hibernate.SQL">
   <level value="TRACE"/> 
   <appender-ref ref="FILE_HIBERNATE"/>
</logger>

Output (echo/print) everything from a PHP Array

 //@parram $data-array,$d-if true then die by default it is false
 //@author Your name

 function p($data,$d = false){

     echo "<pre>"; 
         print_r($data);
     echo "</pre>"; 

     if($d == TRUE){
        die();
     } 
} // END OF FUNCTION

Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function

In your case you can use in this way....

while($row = mysql_fetch_array($result)){
    p($row); // Use this function if you use above function in your page.
}

Prevent textbox autofill with previously entered values

This works for me

   <script type="text/javascript">
        var c = document.getElementById("<%=TextBox1.ClientID %>");
        c.select =
        function (event, ui) 
        { this.value = ""; return false; }
    </script>

Do not want scientific notation on plot axis

You could try lattice:

require(lattice)
x <- 1:100000
y <- 1:100000
xyplot(y~x, scales=list(x = list(log = 10)), type="l")

enter image description here

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

For me the problem was that an other process was using the same port. (In my case it was outlook that was using the same port as my site and thus my site couldn't start)

Yes you can change the local port, but if you are running an API or something that other applications need, you don't always want to do this.

To get a list of what applications are using what port open CMD and type "netstat -aon" You will get a list of ports. Find the port that your site should use, or that you want to use and write down / remember the PID.

Now open task manager and click on the tab 'details'. Find the process with your PID and end it. Now you should be able to start IIS Express with that port.

Is there a simple way to use button to navigate page as a link does in angularjs

For me, best solution is to use Angular router native directives with ui-sref like:

<button ui-sref="state.name">Go!!</button>

To understand that directive and get more options visit ui-router docs at:

https://ui-router.github.io/docs/0.3.1/#/api/ui.router.state.directive:ui-sref

: )

What is the difference between Amazon SNS and Amazon SQS?

In simple terms,

  • SNS - sends messages to the subscriber using push mechanism and no need of pull.

  • SQS - it is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components.

A common pattern is to use SNS to publish messages to Amazon SQS queues to reliably send messages to one or many system components asynchronously.

Reference from Amazon SNS FAQs.

Git commit with no commit message

The commit message is a best practice that should be followed at all times. Unless you're the only developer and that isn't going to change any time soon.

git commit -a -m 'asdfasdfadsfsdf'

Load data from txt with pandas

I usually take a look at the data first or just try to import it and do data.head(), if you see that the columns are separated with \t then you should specify sep="\t" otherwise, sep = " ".

import pandas as pd     
data = pd.read_csv('data.txt', sep=" ", header=None)

Overlaying histograms with ggplot2 in R

Your current code:

ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)

is telling ggplot to construct one histogram using all the values in f0 and then color the bars of this single histogram according to the variable utt.

What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram, where each one gets it's own data frame and fill:

ggplot(histogram, aes(f0)) + 
    geom_histogram(data = lowf0, fill = "red", alpha = 0.2) + 
    geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
    geom_histogram(data = highf0, fill = "green", alpha = 0.2) +

Here's a concrete example with some output:

dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))

ggplot(dat,aes(x=xx)) + 
    geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
    geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)

which produces something like this:

enter image description here

Edited to fix typos; you wanted fill, not colour.

How to use not contains() in xpath?

Should be xpath with not contains() method, //production[not(contains(category,'business'))]

Writing a Python list of lists to a csv file

Ambers's solution also works well for numpy arrays:

from pylab import *
import csv

array_=arange(0,10,1)
list_=[array_,array_*2,array_*3]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(list_)

Options for initializing a string array

Basic:

string[] myString = new string[]{"string1", "string2"};

or

string[] myString = new string[4];
myString[0] = "string1"; // etc.

Advanced: From a List

list<string> = new list<string>(); 
//... read this in from somewhere
string[] myString = list.ToArray();

From StringCollection

StringCollection sc = new StringCollection();
/// read in from file or something
string[] myString = sc.ToArray();

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

GLYPHICONS - bootstrap icon font hex value

If you want to use glyph icons with bootstrap 2.3.2, Add the font files from bootstrap 3 to your project folder then copy this to your css file

 @font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

use grep -n -i null myfile.txt to output the line number in front of each match.

I dont think grep has a switch to print the count of total lines matched, but you can just pipe grep's output into wc to accomplish that:

grep -n -i null myfile.txt | wc -l

Creating an instance of class

   /* 1 */ Foo* foo1 = new Foo ();

Creates an object of type Foo in dynamic memory. foo1 points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo was a POD-type, this would perform value-initialization (it doesn't apply here).

   /* 2 */ Foo* foo2 = new Foo;

Identical to before, because Foo is not a POD type.

   /* 3 */ Foo foo3;

Creates a Foo object called foo3 in automatic storage.

   /* 4 */ Foo foo4 = Foo::Foo();

Uses copy-initialization to create a Foo object called foo4 in automatic storage.

   /* 5 */ Bar* bar1 = new Bar ( *new Foo() );

Uses Bar's conversion constructor to create an object of type Bar in dynamic storage. bar1 is a pointer to it.

   /* 6 */ Bar* bar2 = new Bar ( *new Foo );

Same as before.

   /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );

This is just invalid syntax. You can't declare a variable there.

   /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );

Would work and work by the same principle to 5 and 6 if bar3 wasn't declared on in 7.

5 & 6 contain memory leaks.

Syntax like new Bar ( Foo::Foo() ); is not usual. It's usually new Bar ( (Foo()) ); - extra parenthesis account for most-vexing parse. (corrected)

Converting a Pandas GroupBy output from Series to DataFrame

These solutions only partially worked for me because I was doing multiple aggregations. Here is a sample output of my grouped by that I wanted to convert to a dataframe:

Groupby Output

Because I wanted more than the count provided by reset_index(), I wrote a manual method for converting the image above into a dataframe. I understand this is not the most pythonic/pandas way of doing this as it is quite verbose and explicit, but it was all I needed. Basically, use the reset_index() method explained above to start a "scaffolding" dataframe, then loop through the group pairings in the grouped dataframe, retrieve the indices, perform your calculations against the ungrouped dataframe, and set the value in your new aggregated dataframe.

df_grouped = df[['Salary Basis', 'Job Title', 'Hourly Rate', 'Male Count', 'Female Count']]
df_grouped = df_grouped.groupby(['Salary Basis', 'Job Title'], as_index=False)

# Grouped gives us the indices we want for each grouping
# We cannot convert a groupedby object back to a dataframe, so we need to do it manually
# Create a new dataframe to work against
df_aggregated = df_grouped.size().to_frame('Total Count').reset_index()
df_aggregated['Male Count'] = 0
df_aggregated['Female Count'] = 0
df_aggregated['Job Rate'] = 0

def manualAggregations(indices_array):
    temp_df = df.iloc[indices_array]
    return {
        'Male Count': temp_df['Male Count'].sum(),
        'Female Count': temp_df['Female Count'].sum(),
        'Job Rate': temp_df['Hourly Rate'].max()
    }

for name, group in df_grouped:
    ix = df_grouped.indices[name]
    calcDict = manualAggregations(ix)

    for key in calcDict:
        #Salary Basis, Job Title
        columns = list(name)
        df_aggregated.loc[(df_aggregated['Salary Basis'] == columns[0]) & 
                          (df_aggregated['Job Title'] == columns[1]), key] = calcDict[key]

If a dictionary isn't your thing, the calculations could be applied inline in the for loop:

    df_aggregated['Male Count'].loc[(df_aggregated['Salary Basis'] == columns[0]) & 
                                (df_aggregated['Job Title'] == columns[1])] = df['Male Count'].iloc[ix].sum()

What is the best open source help ticket system?

TRAC. Open source, Python-based

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

you seem to have not created an main method, which should probably look something like this (i am not sure)

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

    Calculate answer = new Calculate();
    answer.getNumber1();
    answer.getNumber2();
    answer.setNumber(answer.getNumber1() , answer.getNumber2());
    answer.getOper();
    answer.setOper(answer.getOper());
    answer.getAnswer();
    }
}

the point is you should have created a main method under some class and after compiling you should run the .class file containing main method. In this case the main method is under RunThis i.e RunThis.class.

I am new to java this may or may not be the right answer, correct me if i am wrong

CORS with spring-boot and angularjs not working

Extending WebSecurityConfigurerAdapter class and overriding configure() method in your @EnableWebSecurity class would work : Below is sample class

@Override
protected void configure(final HttpSecurity http) throws Exception {

         http
        .csrf().disable()
        .exceptionHandling();
         http.headers().cacheControl();

        @Override
        public CorsConfiguration getCorsConfiguration(final HttpServletRequest request) {
            return new CorsConfiguration().applyPermitDefaultValues();
        }
    });
   }
}

Skip a submodule during a Maven build

there is now (from 1.1.1 version) a 'skip' flag in pit.

So you can do things like :

    <profile>
        <id>pit</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.pitest</groupId>
                    <artifactId>pitest-maven</artifactId>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

in your module, and pit will skip

[INFO] --- pitest-maven:1.1.3:mutationCoverage (default-cli) @ module-selenium --- [INFO] Skipping project

How to use the start command in a batch file?

An extra pair of rabbits' ears should do the trick.

start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

Where can I find error log files?

I am using Cent OS 6.6 with Apache and for me error log files are in

/usr/local/apache/log

Getting value from a cell from a gridview on RowDataBound event

why not pull the data directly out of the data source.

DataBinder.Eval(e.Row.DataItem, "ColumnName")

Change a Django form field to a hidden field

If you have a custom template and view you may exclude the field and use {{ modelform.instance.field }} to get the value.

also you may prefer to use in the view:

form.fields['field_name'].widget = forms.HiddenInput()

but I'm not sure it will protect save method on post.

Hope it helps.

How to create full compressed tar file using Python?

import tarfile
tar = tarfile.open("sample.tar.gz", "w:gz")
for name in ["file1", "file2", "file3"]:
    tar.add(name)
tar.close()

If you want to create a tar.bz2 compressed file, just replace file extension name with ".tar.bz2" and "w:gz" with "w:bz2".

How to pass data to view in Laravel?

For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way

In the controller, you define the variables you want to pass as global and you attribute the values to these variables.

Example global $variable; $variable = 1;

And now in the view, at the top, simply do

<?php global $variable;?>

Then you can now call your variable from any where in the view for example

{{$variable}}

hope this helps someone.

convert from Color to brush

Brush brush = new SolidColorBrush(color);

The other way around:

if (brush is SolidColorBrush colorBrush)
    Color color = colorBrush.Color;

Or something like that.

Point being not all brushes are colors but you could turn all colors into a (SolidColor)Brush.

How can you detect the version of a browser?

I use this piece of javascript code based on what I could find in another posts.

_x000D_
_x000D_
var browserHelper = function () {
    var self = {};

    /// IE 6+
    self.isIEBrowser = function () {
        return /*@cc_on!@*/false || !!document.documentMode;
    };

    /// Opera 8.0+
    self.isOperaBrowser = function () {
        return (!!window.opr && !!opr.addons)
            || !!window.opera
            || navigator.userAgent.indexOf(' OPR/') >= 0;
    };

    /// Firefox 1.0+
    self.isFirefoxBrowser = function () {
        return typeof InstallTrigger !== 'undefined';
    };

    /// Safari 3.0+
    self.isSafariBrowser = function () {
        return /constructor/i.test(window.HTMLElement)
            || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));
    };

    /// Edge 20+
    self.isEdgeBrowser = function () {
        return !self.isIEBrowser() && !!window.StyleMedia;
    };

    /// Chrome 1 - 87
    self.isChromeBrowser = function () {
        return (!!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime))
            || (navigator.userAgent.indexOf("Chrome") > -1) && !self.isOperaBrowser();
    };

    /// Edge (based on chromium)
    self.isEdgeChromiumBrowser = function () {
        return self.isChromeBrowser() && (navigator.userAgent.indexOf("Edg") != -1);
    };

    /// Blink
    self.isBlinkBasedOnBrowser = function () {
        return (self.isChromeBrowser() || self.isOperaBrowser()) && !!window.CSS;
    };

    /// Returns the name of the navigator
    self.browserName = function () {

        if (self.isOperaBrowser()) return "Opera";

        if (self.isEdgeBrowser()) return "Edge";

        if (self.isEdgeChromiumBrowser()) return "Edge (based on chromium)";

        if (self.isFirefoxBrowser()) return "Firefox";

        if (self.isIEBrowser()) return "Internet Explorer";

        if (self.isSafariBrowser()) return "Safari";

        if (self.isChromeBrowser()) return "Chrome";

        return "Unknown";
    };
    
    return self;
};

var bName = document.getElementById('browserName');
bName.innerText = browserHelper().browserName();
_x000D_
#browserName {
  font-family: Arial, Verdana;
  font-size: 1.2rem;
  color: #ff8000;
  text-align: center;
  border: 2px solid #ff8000;
  border-radius: .5rem;
  padding: .5rem;
  max-width: 25%;
  margin: auto;
}
_x000D_
<div id="browserName"></div>
_x000D_
_x000D_
_x000D_

HTML - how to make an entire DIV a hyperlink?

alternative would be javascript and forwarding via the onclick event

<div onclick="window.location.href='somewhere...';">...</div>

Spring Boot Adding Http Request Interceptors

I had the same issue of WebMvcConfigurerAdapter being deprecated. When I searched for examples, I hardly found any implemented code. Here is a piece of working code.

create a class that extends HandlerInterceptorAdapter

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import me.rajnarayanan.datatest.DataTestApplication;
@Component
public class EmployeeInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(DataTestApplication.class);
    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler) throws Exception {

            String x = request.getMethod();
            logger.info(x + "intercepted");
        return true;
    }

}

then Implement WebMvcConfigurer interface

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import me.rajnarayanan.datatest.interceptor.EmployeeInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    EmployeeInterceptor employeeInterceptor ;

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(employeeInterceptor).addPathPatterns("/employee");
    }
}

TensorFlow not found using pip

For pyCharm users:

  1. Check pip version: pip3 -V
  2. If pip is older than 9.0.1: py -3 -m pip install --upgrade pip
  3. Then: py -3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl

What do two question marks together mean in C#?

Nothing dangerous about this. In fact, it is beautiful. You can add default value if that is desirable, for example:

CODE

int x = x1 ?? x2 ?? x3 ?? x4 ?? 0;

How can I get argv[] as int?

You can use the function int atoi (const char * str);.
You need to include #include <stdlib.h> and use the function in this way:
int x = atoi(argv[1]);
Here more information if needed: atoi - C++ Reference

Handle Button click inside a row in RecyclerView

this is how I handle multiple onClick events inside a recyclerView:

Edit : Updated to include callbacks (as mentioned in other comments). I have used a WeakReference in the ViewHolder to eliminate a potential memory leak.

Define interface :

public interface ClickListener {

    void onPositionClicked(int position);
    
    void onLongClicked(int position);
}

Then the Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    
    private final ClickListener listener;
    private final List<MyItems> itemsList;

    public MyAdapter(List<MyItems> itemsList, ClickListener listener) {
        this.listener = listener;
        this.itemsList = itemsList;
    }

    @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row_layout), parent, false), listener);
    }

    @Override public void onBindViewHolder(MyViewHolder holder, int position) {
        // bind layout and data etc..
    }

    @Override public int getItemCount() {
        return itemsList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        private ImageView iconImageView;
        private TextView iconTextView;
        private WeakReference<ClickListener> listenerRef;

        public MyViewHolder(final View itemView, ClickListener listener) {
            super(itemView);

            listenerRef = new WeakReference<>(listener);
            iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
            iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);

            itemView.setOnClickListener(this);
            iconTextView.setOnClickListener(this);
            iconImageView.setOnLongClickListener(this);
        }

        // onClick Listener for view
        @Override
        public void onClick(View v) {

            if (v.getId() == iconTextView.getId()) {
                Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
            
            listenerRef.get().onPositionClicked(getAdapterPosition());
        }


        //onLongClickListener for view
        @Override
        public boolean onLongClick(View v) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Hello Dialog")
                    .setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            builder.create().show();
            listenerRef.get().onLongClicked(getAdapterPosition());
            return true;
        }
    }
}

Then in your activity/fragment - whatever you can implement : Clicklistener - or anonymous class if you wish like so :

MyAdapter adapter = new MyAdapter(myItems, new ClickListener() {
            @Override public void onPositionClicked(int position) {
                // callback performed on click
            }

            @Override public void onLongClicked(int position) {
                // callback performed on click
            }
        });

To get which item was clicked you match the view id i.e. v.getId() == whateverItem.getId()

Hope this approach helps!

How do I expire a PHP session after 30 minutes?

It's actually easy with a function like the following. It uses database table name 'sessions' with fields 'id' and 'time'.

Every time when the user visits your site or service again you should invoke this function to check if its return value is TRUE. If it's FALSE the user has expired and the session will be destroyed (Note: This function uses a database class to connect and query the database, of course you could also do it inside your function or something like that):

function session_timeout_ok() {
    global $db;
    $timeout = SESSION_TIMEOUT; //const, e.g. 6 * 60 for 6 minutes
    $ok = false;
    $session_id = session_id();
    $sql = "SELECT time FROM sessions WHERE session_id = '".$session_id."'";
    $rows = $db->query($sql);
    if ($rows === false) {
        //Timestamp could not be read
        $ok = FALSE;
    }
    else {
        //Timestamp was read succesfully
        if (count($rows) > 0) {
            $zeile = $rows[0];
            $time_past = $zeile['time'];
            if ( $timeout + $time_past < time() ) {
                //Time has expired
                session_destroy();
                $sql = "DELETE FROM sessions WHERE session_id = '" . $session_id . "'";
                $affected = $db -> query($sql);
                $ok = FALSE;
            }
            else {
                //Time is okay
                $ok = TRUE;
                $sql = "UPDATE sessions SET time='" . time() . "' WHERE session_id = '" . $session_id . "'";
                $erg = $db -> query($sql);
                if ($erg == false) {
                    //DB error
                }
            }
        }
        else {
            //Session is new, write it to database table sessions
            $sql = "INSERT INTO sessions(session_id,time) VALUES ('".$session_id."','".time()."')";
            $res = $db->query($sql);
            if ($res === FALSE) {
                //Database error
                $ok = false;
            }
            $ok = true;
        }
        return $ok;
    }
    return $ok;
}

Python Regex - How to Get Positions and Values of Matches

import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
    print(m.start(), m.group())

Scheduling Python Script to run every hour accurately

To run something every 10 minutes past the hour.

from datetime import datetime, timedelta

while 1:
    print 'Run something..'

    dt = datetime.now() + timedelta(hours=1)
    dt = dt.replace(minute=10)

    while datetime.now() < dt:
        time.sleep(1)

ssh connection refused on Raspberry Pi

I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.

Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.

c# Best Method to create a log file

I would not use third party libraries, I would log to an xml file.

This is a code sample that do logging to a xml file from different threads:

private static readonly object Locker = new object();
private static XmlDocument _doc = new XmlDocument();

static void Main(string[] args)
{
    if (File.Exists("logs.txt"))
        _doc.Load("logs.txt");
    else
    {
        var root = _doc.CreateElement("hosts");
        _doc.AppendChild(root);
    }

    for (int i = 0; i < 100; i++)
    {
        new Thread(new ThreadStart(DoSomeWork)).Start();
    }
}

static void DoSomeWork()
{
    /*
     * Here you will build log messages
     */
    Log("192.168.1.15", "alive");
}

static void Log(string hostname, string state)
{
    lock (Locker)
    {
        var el = (XmlElement)_doc.DocumentElement.AppendChild(_doc.CreateElement("host"));
        el.SetAttribute("Hostname", hostname);
        el.AppendChild(_doc.CreateElement("State")).InnerText = state;
        _doc.Save("logs.txt");
    }
}

Sending Multipart File as POST parameters with RestTemplate requests

You have to add the FormHttpMessageConverter to your applicationContext.xml to be able to post multipart files.

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
            <bean class="org.springframework.http.converter.FormHttpMessageConverter" />
        </list>
    </property>
</bean>

See http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/FormHttpMessageConverter.html for examples.

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

Late reaction, but I've struggled with this for a while so maybe I can save somebody some time by showing my solution.

My problem showed a bit different, but the cause might be the same.

In my situation, TortoiseSVN kept on trying to connect via a proxy server. I could access SVN via chrome, firefox and IE fine.

Turns out that there is a configuration file that has a different configuration than the GUI in TortoiseSVN shows.

Mine was located here: C:\Documents and Settings\[username]\Application Data\Subversion\, but you can also open the file via the TortoiseSVN gui.

TortoiseSVN

In my file, http-proxy-exceptions was empty. After I specified it, everything worked fine.

[global]
http-proxy-exceptions = 10.1.1.11
http-proxy-host = 197.132.0.223
http-proxy-port = 8080
http-proxy-username = defaultusername
http-proxy-password = defaultpassword
http-compression = no

How to emulate a do-while loop in Python?

do {
  stuff()
} while (condition())

->

while True:
  stuff()
  if not condition():
    break

You can do a function:

def do_while(stuff, condition):
  while condition(stuff()):
    pass

But 1) It's ugly. 2) Condition should be a function with one parameter, supposed to be filled by stuff (it's the only reason not to use the classic while loop.)

Change column type in pandas

pandas >= 1.0

Here's a chart that summarises some of the most important conversions in pandas.

enter image description here

Conversions to string are trivial .astype(str) and are not shown in the figure.

"Hard" versus "Soft" conversions

Note that "conversions" in this context could either refer to converting text data into their actual data type (hard conversion), or inferring more appropriate data types for data in object columns (soft conversion). To illustrate the difference, take a look at

df = pd.DataFrame({'a': ['1', '2', '3'], 'b': [4, 5, 6]}, dtype=object)
df.dtypes                                                                  

a    object
b    object
dtype: object

# Actually converts string to numeric - hard conversion
df.apply(pd.to_numeric).dtypes                                             

a    int64
b    int64
dtype: object

# Infers better data types for object data - soft conversion
df.infer_objects().dtypes                                                  

a    object  # no change
b     int64
dtype: object

# Same as infer_objects, but converts to equivalent ExtensionType
df.convert_dtypes().dtypes                                                     

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

maybe

string = document.location.href;
arrayOfStrings = string.toString().split('/');

assuming you want the current url

How to grep and replace

Be very careful when using find and sed in a git repo! If you don't exclude the binary files you can end up with this error:

error: bad index file sha1 signature 
fatal: index file corrupt

To solve this error you need to revert the sed by replacing your new_string with your old_string. This will revert your replaced strings, so you will be back to the beginning of the problem.

The correct way to search for a string and replace it is to skip find and use grep instead in order to ignore the binary files:

sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")

Credits for @hobs