Programs & Examples On #Culerity

what's the default value of char?

Default value for char is \u0000

public class DefaultValues {
char varChar;
public static void main(String...l)
 {
    DefaultValues ob =new DefaultValues();
    System.out.println(ob.varChar=='\u0000');
 }  
}

This will return true

Circle button css

use this css.

_x000D_
_x000D_
.roundbutton{_x000D_
          display:block;_x000D_
          height: 300px;_x000D_
          width: 300px;_x000D_
          border-radius: 50%;_x000D_
          border: 1px solid red;_x000D_
          _x000D_
        }
_x000D_
<a class="roundbutton" href="#"><i class="ion-ios-arrow-down"></i></a>
_x000D_
_x000D_
_x000D_

How to convert any Object to String?

I've written a few methods for convert by Gson library and java 1.8 .
thay are daynamic model for convert.

string to object

object to string

List to string

string to List

HashMap to String

String to JsonObj

//saeedmpt 
public static String convertMapToString(Map<String, String> data) {
    //convert Map  to String
    return new GsonBuilder().setPrettyPrinting().create().toJson(data);
}
public static <T> List<T> convertStringToList(String strListObj) {
    //convert string json to object List
    return new Gson().fromJson(strListObj, new TypeToken<List<Object>>() {
    }.getType());
}
public static <T> T convertStringToObj(String strObj, Class<T> classOfT) {
    //convert string json to object
    return new Gson().fromJson(strObj, (Type) classOfT);
}

public static JsonObject convertStringToJsonObj(String strObj) {
    //convert string json to object
    return new Gson().fromJson(strObj, JsonObject.class);
}

public static <T> String convertListObjToString(List<T> listObj) {
    //convert object list to string json for
    return new Gson().toJson(listObj, new TypeToken<List<T>>() {
    }.getType());
}

public static String convertObjToString(Object clsObj) {
    //convert object  to string json
    String jsonSender = new Gson().toJson(clsObj, new TypeToken<Object>() {
    }.getType());
    return jsonSender;
}

how do I loop through a line from a csv file in powershell

Import-Csv $path | Foreach-Object { 

    foreach ($property in $_.PSObject.Properties)
    {
        doSomething $property.Name, $property.Value
    } 

}

Java output formatting for Strings

If you want a minimum of 4 characters, for instance,

System.out.println(String.format("%4d", 5));
// Results in "   5", minimum of 4 characters

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

C++ auto keyword. Why is it magic?

It's not going anywhere ... it's a new standard C++ feature in the implementation of C++11. That being said, while it's a wonderful tool for simplifying object declarations as well as cleaning up the syntax for certain call-paradigms (i.e., range-based for-loops), don't over-use/abuse it :-)

Angular 5 Service to read local .json file

Assumes, you have a data.json file in the src/app folder of your project with the following values:

[
    {
        "id": 1,
        "name": "Licensed Frozen Hat",
        "description": "Incidunt et magni est ut.",
        "price": "170.00",
        "imageUrl": "https://source.unsplash.com/1600x900/?product",
        "quantity": 56840
    },
    ...
]

3 Methods for Reading Local JSON Files

Method 1: Reading Local JSON Files Using TypeScript 2.9+ import Statement

import { Component, OnInit } from '@angular/core';
import * as data from './data.json';

@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular Example';

  products: any = (data as any).default;

  constructor(){}
  ngOnInit(){
    console.log(data);
  }
}

Method 2: Reading Local JSON Files Using Angular HttpClient

import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";


@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular Example';
  products: any = [];

  constructor(private httpClient: HttpClient){}
  ngOnInit(){
    this.httpClient.get("assets/data.json").subscribe(data =>{
      console.log(data);
      this.products = data;
    })
  }
}

Method 3: Reading Local JSON Files in Offline Angular Apps Using ES6+ import Statement

If your Angular application goes offline, reading the JSON file with HttpClient will fail. In this case, we have one more method to import local JSON files using the ES6+ import statement which supports importing JSON files.

But first we need to add a typing file as follows:

declare module "*.json" {
  const value: any;
  export default value;
}

Add this inside a new file json-typings.d.ts file in the src/app folder.

Now, you can import JSON files just like TypeScript 2.9+.

import * as data from "data.json";

Can you create nested WITH clauses for Common Table Expressions?

Nested 'With' is not supported, but you can always use the second With as a subquery, for example:

WITH A AS (
                --WITH B AS ( SELECT COUNT(1) AS _CT FROM C ) SELECT CASE _CT WHEN 1 THEN 1 ELSE 0 END FROM B --doesn't work
                SELECT CASE WHEN count = 1 THEN 1 ELSE 0 END AS CT FROM (SELECT COUNT(1) AS count FROM dual)
                union all
                select 100 AS CT from dual
           )
              select CT FROM A

Finding the direction of scrolling in a UIScrollView?

Short & Easy would be, just check the velocity value, if its greater than zero then its scrolling left else right:

func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    var targetOffset = Float(targetContentOffset.memory.x)
    println("TargetOffset: \(targetOffset)")
    println(velocity)

    if velocity.x < 0 {
        scrollDirection = -1 //scrolling left
    } else {
        scrollDirection = 1 //scrolling right
    }
}

What is the correct value for the disabled attribute?

In HTML5, there is no correct value, all the major browsers do not really care what the attribute is, they are just checking if the attribute exists so the element is disabled.

Where to install Android SDK on Mac OS X?

You can install android-sdk in different ways

  1. homebrew
    Install brew using command from brew.sh

    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"  
    

    Install android-sdk using

    brew install android-sdk
    

    Now android-sdk will be installed in /usr/local/opt/android-sdk

    export ANDROID_HOME=/usr/local/opt/android-sdk
    
  2. If you installed android studio following the website,
    android-sdk will be installed in ~/Library/Android/sdk

    export ANDROID_HOME=~/Library/Android/sdk
    

I think these defaults make sense and its better to stick to it

I need an unordered list without any bullets

If you're unable to make it work at the <ul> level, you might need to place the list-style-type: none; at the <li> level:

<ul>
    <li style="list-style-type: none;">Item 1</li>
    <li style="list-style-type: none;">Item 2</li>
</ul>

You can create a CSS class to avoid this repetition:

<style>
ul.no-bullets li
{
    list-style-type: none;
}
</style>

<ul class="no-bullets">
    <li>Item 1</li>
    <li>Item 2</li>
</ul>

When necessary, use !important:

<style>
ul.no-bullets li
{
    list-style-type: none !important;
}
</style>

How to properly make a http web GET request

Servers sometimes compress their responses to save on bandwidth, when this happens, you need to decompress the response before attempting to read it. Fortunately, the .NET framework can do this automatically, however, we have to turn the setting on.

Here's an example of how you could achieve that.

string html = string.Empty;
string url = @"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    html = reader.ReadToEnd();
}

Console.WriteLine(html);

GET

public string Get(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

GET async

public async Task<string> GetAsync(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

POST
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public string Post(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        requestBody.Write(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

    

POST async
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

Any way to exit bash script, but not quitting the terminal

This is just like you put a run function inside your script run2.sh. You use exit code inside run while source your run2.sh file in the bash tty. If the give the run function its power to exit your script and give the run2.sh its power to exit the terminator. Then of cuz the run function has power to exit your teminator.

    #! /bin/sh
    # use . run2.sh

    run()
    {
        echo "this is run"
        #return 0
        exit 0
    }

    echo "this is begin"
    run
    echo "this is end"

Anyway, I approve with Kaz it's a design problem.

how to delete the content of text file without deleting itself

FileOutputStream fos = openFileOutput("/*file name like --> one.txt*/", MODE_PRIVATE);
FileWriter fw = new FileWriter(fos.getFD());
fw.write("");

How to cancel a pull request on github?

I wanted to comment, but since my reputation won't qualify for commenting, it had to be an answer. Github will actually let you not only cancel a pull request, but also delete it by simply deleting the fork you are trying to push. Hope this may help some others googling this.

what are the .map files used for in Bootstrap 3.x?

These are source maps. Provide these alongside compressed source files; developer tools such as those in Firefox and Chrome will use them to allow debugging as if the code was not compressed.

Accessing members of items in a JSONArray with Java

In case it helps someone else, I was able to convert to an array by doing something like this,

JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()

...or you should be able to get the length

((JSONArray) myJsonArray).toArray().length

Unable to compile simple Java 10 / Java 11 project with Maven

Alright so for me nothing worked.
I was using spring boot with hibernate. The spring boot version was ~2.0.1 and I would keep get this error and null pointer exception upon compilation. The issue was with hibernate that needed a version bump. But after that I had some other issues that seemed like the annotation processor was not recognised so I decided to just bump spring from 2.0.1 to 2.1.7-release and everything worked as expected.

You still need to add the above plugin tough
Hope it helps!

Using the Web.Config to set up my SQL database connection string?

Web.config file

<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;    Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>

.cs file

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

SQLite - UPSERT *not* INSERT or REPLACE

Eric B’s answer is OK if you want to preserve just one or maybe two columns from the existing row. If you want to preserve a lot of columns, it gets too cumbersome fast.

Here’s an approach that will scale well to any amount of columns on either side. To illustrate it I will assume the following schema:

 CREATE TABLE page (
     id      INTEGER PRIMARY KEY,
     name    TEXT UNIQUE,
     title   TEXT,
     content TEXT,
     author  INTEGER NOT NULL REFERENCES user (id),
     ts      TIMESTAMP DEFAULT CURRENT_TIMESTAMP
 );

Note in particular that name is the natural key of the row – id is used only for foreign keys, so the point is for SQLite to pick the ID value itself when inserting a new row. But when updating an existing row based on its name, I want it to continue to have the old ID value (obviously!).

I achieve a true UPSERT with the following construct:

 WITH new (name, title, author) AS ( VALUES('about', 'About this site', 42) )
 INSERT OR REPLACE INTO page (id, name, title, content, author)
 SELECT old.id, new.name, new.title, old.content, new.author
 FROM new LEFT JOIN page AS old ON new.name = old.name;

The exact form of this query can vary a bit. The key is the use of INSERT SELECT with a left outer join, to join an existing row to the new values.

Here, if a row did not previously exist, old.id will be NULL and SQLite will then assign an ID automatically, but if there already was such a row, old.id will have an actual value and this will be reused. Which is exactly what I wanted.

In fact this is very flexible. Note how the ts column is completely missing on all sides – because it has a DEFAULT value, SQLite will just do the right thing in any case, so I don’t have to take care of it myself.

You can also include a column on both the new and old sides and then use e.g. COALESCE(new.content, old.content) in the outer SELECT to say “insert the new content if there was any, otherwise keep the old content” – e.g. if you are using a fixed query and are binding the new values with placeholders.

SELECT last id, without INSERT

I think to add timestamp to every record and get the latest. In this situation you can get any ids, pack rows and other ops.

Deleting all files from a folder using PHP?

$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file)) {
    unlink($file); // delete file
  }
}

If you want to remove 'hidden' files like .htaccess, you have to use

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);

How to get Python requests to trust a self signed SSL certificate?

With the verify parameter you can provide a custom certificate authority bundle

requests.get(url, verify=path_to_bundle_file)

From the docs:

You can pass verify the path to a CA_BUNDLE file with certificates of trusted CAs. This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable.

Finding what branch a Git commit came from

If the OP is trying to determine the history that was traversed by a branch when a particular commit was created ("find out what branch a commit comes from given its SHA-1 hash value"), then without the reflog there aren't any records in the Git object database that shows what named branch was bound to what commit history.

(I posted this as an answer in reply to a comment.)

Hopefully this script illustrates my point:

rm -rf /tmp/r1 /tmp/r2; mkdir /tmp/r1; cd /tmp/r1
git init; git config user.name n; git config user.email [email protected]
git commit -m"empty" --allow-empty; git branch -m b1; git branch b2
git checkout b1; touch f1; git add f1; git commit -m"Add f1"
git checkout b2; touch f2; git add f2; git commit -m"Add f2"
git merge -m"merge branches" b1; git checkout b1; git merge b2
git clone /tmp/r1 /tmp/r2; cd /tmp/r2; git fetch origin b2:b2
set -x;
cd /tmp/r1; git log --oneline --graph --decorate; git reflog b1; git reflog b2;
cd /tmp/r2; git log --oneline --graph --decorate; git reflog b1; git reflog b2;

The output shows the lack of any way to know whether the commit with 'Add f1' came from branch b1 or b2 from the remote clone /tmp/r2.

(Last lines of the output here)

+ cd /tmp/r1
+ git log --oneline --graph --decorate
*   f0c707d (HEAD, b2, b1) merge branches
|\
| * 086c9ce Add f1
* | 80c10e5 Add f2
|/
* 18feb84 empty
+ git reflog b1
f0c707d b1@{0}: merge b2: Fast-forward
086c9ce b1@{1}: commit: Add f1
18feb84 b1@{2}: Branch: renamed refs/heads/master to refs/heads/b1
18feb84 b1@{3}: commit (initial): empty
+ git reflog b2
f0c707d b2@{0}: merge b1: Merge made by the 'recursive' strategy.
80c10e5 b2@{1}: commit: Add f2
18feb84 b2@{2}: branch: Created from b1
+ cd /tmp/r2
+ git log --oneline --graph --decorate
*   f0c707d (HEAD, origin/b2, origin/b1, origin/HEAD, b2, b1) merge branches
|\
| * 086c9ce Add f1
* | 80c10e5 Add f2
|/
* 18feb84 empty
+ git reflog b1
f0c707d b1@{0}: clone: from /tmp/r1
+ git reflog b2
f0c707d b2@{0}: fetch origin b2:b2: storing head

How to resize image (Bitmap) to a given size?

Bitmap scaledBitmap = scaleDown(realImage, MAX_IMAGE_SIZE, true);

Scale down method:

public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
        boolean filter) {
    float ratio = Math.min(
            (float) maxImageSize / realImage.getWidth(),
            (float) maxImageSize / realImage.getHeight());
    int width = Math.round((float) ratio * realImage.getWidth());
    int height = Math.round((float) ratio * realImage.getHeight());

    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
            height, filter);
    return newBitmap;
}

How to include JavaScript file or library in Chrome console?

Install tampermonkey and add the following UserScript with one (or more) @match with specific page url (or a match of all pages: https://*) e.g.:

// ==UserScript==
// @name         inject-rx
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Inject rx library on the page
// @author       Me
// @match        https://www.some-website.com/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
     window.injectedRx = rxjs;
     //Or even:  window.rxjs = rxjs;

})();

Whenever you need the library on the console, or on a snippet enable the specific UserScript and refresh.

This solution prevents namespace pollution. You can use custom namespaces to avoid accidental overwrite of existing global variables on the page.

YouTube API to fetch all videos on a channel

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

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

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

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

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

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

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

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

Take the content of a list and append it to another list

Using the map() and reduce() built-in functions

def file_to_list(file):
     #stuff to parse file to a list
     return list

files = [...list of files...]

L = map(file_to_list, files)

flat_L = reduce(lambda x,y:x+y, L)

Minimal "for looping" and elegant coding pattern :)

a page can have only one server-side form tag

It sounds like you have a form tag in a Master Page and in the Page that is throwing the error.

You can have only one.

How Can I Truncate A String In jQuery?

Instead of using jQuery, use css property text-overflow:ellipsis. It will automatically truncate the string.

.truncated { display:inline-block; 
             max-width:100px; 
             overflow:hidden; 
             text-overflow:ellipsis; 
             white-space:nowrap; 
           }

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

Get loop counter/index using for…of syntax in JavaScript

To use for..of loop on array and retrieve index you can you use array1.indexOf(element) which will return the index value of an element in the loop. You can return both the index and the value using this method.

_x000D_
_x000D_
array1 = ['a', 'b', 'c']
for (element of array1) {
    console.log(array1.indexOf(element), element) // 0 a 1 b 2 c
}
_x000D_
_x000D_
_x000D_

Mercurial: how to amend the last commit?

I'm tuning into what krtek has written. More specifically solution 1:

Assumptions:

  • you've committed one (!) changeset but have not pushed it yet
  • you want to modify this changeset (e.g. add, remove or change files and/or the commit message)

Solution:

  • use hg rollback to undo the last commit
  • commit again with the new changes in place

The rollback really undoes the last operation. Its way of working is quite simple: normal operations in HG will only append to files; this includes a commit. Mercurial keeps track of the file lengths of the last transaction and can therefore completely undo one step by truncating the files back to their old lengths.

Python datetime strptime() and strftime(): how to preserve the timezone information

Part of the problem here is that the strings usually used to represent timezones are not actually unique. "EST" only means "America/New_York" to people in North America. This is a limitation in the C time API, and the Python solution is… to add full tz features in some future version any day now, if anyone is willing to write the PEP.

You can format and parse a timezone as an offset, but that loses daylight savings/summer time information (e.g., you can't distinguish "America/Phoenix" from "America/Los_Angeles" in the summer). You can format a timezone as a 3-letter abbreviation, but you can't parse it back from that.

If you want something that's fuzzy and ambiguous but usually what you want, you need a third-party library like dateutil.

If you want something that's actually unambiguous, just append the actual tz name to the local datetime string yourself, and split it back off on the other end:

d = datetime.datetime.now(pytz.timezone("America/New_York"))
dtz_string = d.strftime(fmt) + ' ' + "America/New_York"

d_string, tz_string = dtz_string.rsplit(' ', 1)
d2 = datetime.datetime.strptime(d_string, fmt)
tz2 = pytz.timezone(tz_string)

print dtz_string 
print d2.strftime(fmt) + ' ' + tz_string

Or… halfway between those two, you're already using the pytz library, which can parse (according to some arbitrary but well-defined disambiguation rules) formats like "EST". So, if you really want to, you can leave the %Z in on the formatting side, then pull it off and parse it with pytz.timezone() before passing the rest to strptime.

Javascript: Unicode string to hex

Here you go. :D

"??".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")
"6f225b57"

for non unicode

"hi".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")
"6869"

ASCII (utf-8) binary HEX string to string

"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")

String to ASCII (utf-8) binary HEX string

"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")

--- unicode ---

String to UNICODE (utf-16) binary HEX string

"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")

UNICODE (utf-16) binary HEX string to string

"00680065006c006c006f00200077006f0072006c00640021".match(/.{1,4}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")

"webxml attribute is required" error in Maven

I had the exact same problem and i solved it like this :

Make a new folder named WEB-INF under src/main/webbapp then

Right Click on your Project -> Java EE Tools -> Generate Deployment Descriptor Stub

This should generate your web.xml

I hope this helps by solving your problem :D

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

Looping through a DataTable

Please try the following code below:

//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.

using (reader = cmd.ExecuteReader())
{
// Load the Data table object
  dataTable.Load(reader);
  if (dataTable.Rows.Count > 0)
  {
    DataColumn col = dataTable.Columns["YourColumnName"];  
    foreach (DataRow row in dataTable.Rows)
    {                                   
       strJsonData = row[col].ToString();
    }
  }
}

How to write ternary operator condition in jQuery?

Ternary operator works because the first part of it returns a Boolean value. In your case, jQuery's css method returns the jQuery object, thus not valid for ternary operation.

jQuery find() method not working in AngularJS directive

Before the days of jQuery you would use:

   document.getElementById('findmebyid');

If this one line will save you an entire jQuery library, it might be worth while using it instead.

For those concerned about performance: Beginning your selector with an ID is always best as it uses native function document.getElementById.

// Fast:
$( "#container div.robotarm" );

// Super-fast:
$( "#container" ).find( "div.robotarm" );

http://learn.jquery.com/performance/optimize-selectors/

jsPerf http://jsperf.com/jquery-selector-benchmark/32

Create Generic method constraining T to an Enum

Hope this is helpful:

public static TValue ParseEnum<TValue>(string value, TValue defaultValue)
                  where TValue : struct // enum 
{
      try
      {
            if (String.IsNullOrEmpty(value))
                  return defaultValue;
            return (TValue)Enum.Parse(typeof (TValue), value);
      }
      catch(Exception ex)
      {
            return defaultValue;
      }
}

How to detect lowercase letters in Python?

You should use raw_input to take a string input. then use islower method of str object.

s = raw_input('Type a word')
l = []
for c in s.strip():
    if c.islower():
        print c
        l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)

Just do -

dir(s)

and you will find islower and other attributes of str

How do I restart a service on a remote machine in Windows?

You can use mmc:

  1. Start / Run. Type "mmc".
  2. File / Add/Remove Snap-in... Click "Add..."
  3. Find "Services" and click "Add"
  4. Select "Another computer:" and type the host name / IP address of the remote machine. Click Finish, Close, etc.

At that point you will be able to manage services as if they were on your local machine.

How can I provide multiple conditions for data trigger in WPF?

@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)

but if you have values other than boolean try using type converters:

<MultiDataTrigger.Conditions>
    <Condition Value="True">
        <Condition.Binding>
            <MultiBinding Converter="{StaticResource conditionConverter}">
                <Binding Path="Name" />
                <Binding Path="State" />
            </MultiBinding>
        </Condition.Binding>
        <Setter Property="Background" Value="Cyan" />
    </Condition>
</MultiDataTrigger.Conditions>

you can use the values in Convert method any way you like to produce a condition which suits you.

TypeScript: casting HTMLElement

Could be solved in the declaration file (lib.d.ts) if TypeScript would define HTMLCollection instead of NodeList as a return type.

DOM4 also specifies this as the correct return type, but older DOM specifications are less clear.

See also http://typescript.codeplex.com/workitem/252

Transform DateTime into simple Date in Ruby on Rails

Hello collimarco :) you can use ruby strftime method to create ur own date/time display.

time.strftime( string ) => string

  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character

   t = Time.now
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM"

React Js conditionally applying class attributes

As others have commented, classnames utility is the currently recommended approach to handle conditional CSS class names in ReactJs.

In your case, the solution will look like:

var btnGroupClasses = classNames(
  'btn-group',
  'pull-right',
  {
    'show': this.props.showBulkActions,
    'hidden': !this.props.showBulkActions
  }
);

...

<div className={btnGroupClasses}>...</div>

As a side note, I would suggest you to try to avoid using both show and hidden classes, so the code could be simpler. Most likely you don't need to set a class for something to be shown by default.

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

Get sum of MySQL column in PHP

$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);

$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
    $qty += $num['ColumnName'];
}
echo $qty;

Java for loop syntax: "for (T obj : objects)"

for each S3ObjecrSummary in objectListing.getObjectSummaries()

it's looping through each item in the collection

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

javascript: pause setTimeout();

I don't think you'll find anything better than clearTimeout. Anyway, you can always schedule another timeout later, instead 'resuming' it.

$(this).attr("id") not working

I recommend you to read more about the this keyword.

You cannot expect "this" to select the "select" tag in this case.

What you want to do in this case is use obj.id to get the id of select tag.

Angular2 - Focusing a textbox on component load

See Angular 2: Focus on newly added input element for how to set the focus.

For "on load" use the ngAfterViewInit() lifecycle callback.

How to make flutter app responsive according to different screen size?

An Another approach :) easier for flutter web

class SampleView extends StatelessWidget {
@override
Widget build(BuildContext context) {
 return Center(
  child: Container(
    width: 200,
    height: 200,
    color: Responsive().getResponsiveValue(
        forLargeScreen: Colors.red,
        forMediumScreen: Colors.green,
        forShortScreen: Colors.yellow,
        forMobLandScapeMode: Colors.blue,
        context: context),
    // You dodn't need to provide the values for every 
    //parameter(except shortScreen & context)
    // but default its provide the value as ShortScreen for Larger and 
    //mediumScreen
    ),
   );
 }
}



 // utility 
          class Responsive {
            // function reponsible for providing value according to screensize
            getResponsiveValue(
                {dynamic forShortScreen,
                dynamic forMediumScreen,
                dynamic forLargeScreen,
                dynamic forMobLandScapeMode,
                BuildContext context}) {

              if (isLargeScreen(context)) {

                return forLargeScreen ?? forShortScreen;
              } else if (isMediumScreen(context)) {

                return forMediumScreen ?? forShortScreen;
              } 
           else if (isSmallScreen(context) && isLandScapeMode(context)) {

                return forMobLandScapeMode ?? forShortScreen;
              } else {
                return forShortScreen;
              }
            }
          
            isLandScapeMode(BuildContext context) {
              if (MediaQuery.of(context).orientation == Orientation.landscape) {
                return true;
              } else {
                return false;
              }
            }
          
            static bool isLargeScreen(BuildContext context) {
              return getWidth(context) > 1200;
            }
          
            static bool isSmallScreen(BuildContext context) {
              return getWidth(context) < 800;
            }
          
            static bool isMediumScreen(BuildContext context) {
              return getWidth(context) > 800 && getWidth(context) < 1200;
            }
          
            static double getWidth(BuildContext context) {
              return MediaQuery.of(context).size.width;
            }
          }

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.

Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.

Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.

The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.

 &obj; //  valid
 &12;  //invalid

How can I make sticky headers in RecyclerView? (Without external lib)

Easiest way is to just create an Item Decoration for your RecyclerView.

import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class RecyclerSectionItemDecoration extends RecyclerView.ItemDecoration {

private final int             headerOffset;
private final boolean         sticky;
private final SectionCallback sectionCallback;

private View     headerView;
private TextView header;

public RecyclerSectionItemDecoration(int headerHeight, boolean sticky, @NonNull SectionCallback sectionCallback) {
    headerOffset = headerHeight;
    this.sticky = sticky;
    this.sectionCallback = sectionCallback;
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);

    int pos = parent.getChildAdapterPosition(view);
    if (sectionCallback.isSection(pos)) {
        outRect.top = headerOffset;
    }
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
    super.onDrawOver(c,
                     parent,
                     state);

    if (headerView == null) {
        headerView = inflateHeaderView(parent);
        header = (TextView) headerView.findViewById(R.id.list_item_section_text);
        fixLayoutSize(headerView,
                      parent);
    }

    CharSequence previousHeader = "";
    for (int i = 0; i < parent.getChildCount(); i++) {
        View child = parent.getChildAt(i);
        final int position = parent.getChildAdapterPosition(child);

        CharSequence title = sectionCallback.getSectionHeader(position);
        header.setText(title);
        if (!previousHeader.equals(title) || sectionCallback.isSection(position)) {
            drawHeader(c,
                       child,
                       headerView);
            previousHeader = title;
        }
    }
}

private void drawHeader(Canvas c, View child, View headerView) {
    c.save();
    if (sticky) {
        c.translate(0,
                    Math.max(0,
                             child.getTop() - headerView.getHeight()));
    } else {
        c.translate(0,
                    child.getTop() - headerView.getHeight());
    }
    headerView.draw(c);
    c.restore();
}

private View inflateHeaderView(RecyclerView parent) {
    return LayoutInflater.from(parent.getContext())
                         .inflate(R.layout.recycler_section_header,
                                  parent,
                                  false);
}

/**
 * Measures the header view to make sure its size is greater than 0 and will be drawn
 * https://yoda.entelect.co.za/view/9627/how-to-android-recyclerview-item-decorations
 */
private void fixLayoutSize(View view, ViewGroup parent) {
    int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(),
                                                     View.MeasureSpec.EXACTLY);
    int heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(),
                                                      View.MeasureSpec.UNSPECIFIED);

    int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
                                                   parent.getPaddingLeft() + parent.getPaddingRight(),
                                                   view.getLayoutParams().width);
    int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
                                                    parent.getPaddingTop() + parent.getPaddingBottom(),
                                                    view.getLayoutParams().height);

    view.measure(childWidth,
                 childHeight);

    view.layout(0,
                0,
                view.getMeasuredWidth(),
                view.getMeasuredHeight());
}

public interface SectionCallback {

    boolean isSection(int position);

    CharSequence getSectionHeader(int position);
}

}

XML for your header in recycler_section_header.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_item_section_text"
    android:layout_width="match_parent"
    android:layout_height="@dimen/recycler_section_header_height"
    android:background="@android:color/black"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:textColor="@android:color/white"
    android:textSize="14sp"
/>

And finally to add the Item Decoration to your RecyclerView:

RecyclerSectionItemDecoration sectionItemDecoration =
        new RecyclerSectionItemDecoration(getResources().getDimensionPixelSize(R.dimen.recycler_section_header_height),
                                          true, // true for sticky, false for not
                                          new RecyclerSectionItemDecoration.SectionCallback() {
                                              @Override
                                              public boolean isSection(int position) {
                                                  return position == 0
                                                      || people.get(position)
                                                               .getLastName()
                                                               .charAt(0) != people.get(position - 1)
                                                                                   .getLastName()
                                                                                   .charAt(0);
                                              }

                                              @Override
                                              public CharSequence getSectionHeader(int position) {
                                                  return people.get(position)
                                                               .getLastName()
                                                               .subSequence(0,
                                                                            1);
                                              }
                                          });
    recyclerView.addItemDecoration(sectionItemDecoration);

With this Item Decoration you can either make the header pinned/sticky or not with just a boolean when creating the Item Decoration.

You can find a complete working example on github: https://github.com/paetztm/recycler_view_headers

Differences between .NET 4.0 and .NET 4.5 in High level in .NET


.NET Framework 4


Microsoft announced the intention to ship .NET Framework 4 on 29 September 2008. The Public Beta was released on 20 May 2009.

  • Parallel Extensions to improve support for parallel computing, which target multi-core or distributed systems. To this end, technologies like PLINQ (Parallel LINQ), a parallel implementation of the LINQ engine, and Task Parallel Library, which exposes parallel constructs via method calls., are included.
  • New Visual Basic .NET and C# language features, such as implicit line continuations, dynamic dispatch, named parameters, and optional parameters.
  • Support for Code Contracts.
  • Inclusion of new types to work with arbitrary-precision arithmetic (System.Numerics.BigInteger) and complex numbers (System.Numerics.Complex).
  • Introduce Common Language Runtime (CLR) 4.0.

After the release of the .NET Framework 4, Microsoft released a set of enhancements, named Windows Server AppFabric, for application server capabilities in the form of AppFabric Hosting and in-memory distributed caching support.


.NET Framework 4.5


.NET Framework 4.5 was released on 15 August 2012., a set of new or improved features were added into this version. The .NET Framework 4.5 is only supported on Windows Vista or later. The .NET Framework 4.5 uses Common Language Runtime 4.0, with some additional runtime features.

1. .NET for Metro style apps

Metro-style apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework is available for building Metro style apps for Windows 8 using C# or Visual Basic. This subset is called .NET APIs for apps. The version of .NET Framework, runtime and libraries, used for Metro style apps is a part of the new Windows Runtime, which is the new platform and application model for Metro style apps. It is an ecosystem that houses many platforms and languages, including .NET Framework, C++ and HTML5/JavaScript.

2. Core Features

  • Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out.
  • Ability to define the culture for an application domain.
  • Console support for Unicode (UTF-16) encoding.
  • Support for versioning of cultural string ordering and comparison data.
  • Better performance when retrieving resources.
  • Zip compression improvements to reduce the size of a compressed file.
  • Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.

3. Managed Extensibility Framework (MEF)

  • Support for generic types.
  • Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.
  • Multiple scopes.

4. Asynchronous operations

In the .NET Framework 4.5, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations.

5. ASP.NET

  • Support for new HTML5 form types.
  • Support for model binders in Web Forms. These let you bind data controls directly to data-access methods, and automatically convert user input to and from .NET Framework data types.
  • Support for unobtrusive JavaScript in client-side validation scripts.
  • Improved handling of client script through bundling and minification for improved page performance.
  • Integrated encoding routines from the AntiXSS library (previously an external library) to protect from cross-site scripting attacks.
  • Support for WebSocket protocol.
  • Support for reading and writing HTTP requests and responses asynchronously.
  • Support for asynchronous modules and handlers.
  • Support for content distribution network (CDN) fallback in the ScriptManager control.

6. Networking

  • Provides a new programming interface for HTTP applications: System.Net.Http namespace and System.Net.Http.Headers namespaces are added.
  • Other improvements: Improved internationalization and IPv6 support. RFC-compliant URI support. Support for Internationalized Domain Name (IDN) parsing. Support for Email Address Internationalization (EAI).

7. Windows Presentation Foundation (WPF)

  • The new Ribbon control, which enables you to implement a ribbon user interface that hosts a Quick Access Toolbar, Application Menu, and tabs.
  • The new INotifyDataErrorInfo interface, which supports synchronous and asynchronous data validation.
  • New features for the VirtualizingPanel and Dispatcher classes.
  • Improved performance when displaying large sets of grouped data, and by accessing collections on non-UI threads.
  • Data binding to static properties, data binding to custom types that implement the ICustomTypeProvider interface and retrieval of data binding information from a binding expression.
  • Repositioning of data as the values change (live shaping).
  • Better integration between WPF and Win32 user interface components.
  • Ability to check whether the data context for an item container is disconnected.
  • Ability to set the amount of time that should elapse between property changes and data source updates.
  • Improved support for implementing weak event patterns. Also, events can now accept markup extensions.

8. Windows Communication Foundation (WCF)

In the .NET Framework 4.5, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:

  • Simplification of generated configuration files.
  • Support for contract-first development.
  • Ability to configure ASP.NET compatibility mode more easily.
  • Changes in default transport property values to reduce the likelihood that you will have to set them.
  • Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.
  • Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.
  • New asynchronous streaming support.
  • New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).
  • Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.
  • Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.
  • Support for configuring services in code.
  • XML Editor tooltips.
  • ChannelFactory caching support.
  • Binary encoder compression support.
  • Support for a UDP transport that enables developers to write services that use "fire and forget" messaging. A client sends a message to a service and expects no response from the service.
  • Ability to support multiple authentication modes on a single WCF endpoint when using the HTTP transport and transport security.
  • Support for WCF services that use internationalized domain names (IDNs).

9. Tools

  • Resource File Generator (Resgen.exe) enables you to create a .resw file for use in Windows Store apps from a .resources file embedded in a .NET Framework assembly.
  • Managed Profile Guided Optimization (Mpgo.exe) enables you to improve application startup time, memory utilization (working set size), and throughput by optimizing native image assemblies. The command-line tool generates profile data for native image application assemblies.

For more information and access to reference links, please visit:

===========.Net 4.5 Poster=========

enter image description here

Spring Boot Multiple Datasource

MySqlBDConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "mysqlEmFactory" ,transactionManagerRef = "mysqlTransactionManager")
public class MySqlBDConfig{

@Autowired
private Environment env;

@Bean(name="mysqlProperities")
@ConfigurationProperties(prefix="spring.mysql")
public DataSourceProperties mysqlProperities(){
    return new  DataSourceProperties();
}


@Bean(name="mysqlDataSource")
public DataSource interfaceDS(@Qualifier("mysqlProperities")DataSourceProperties dataSourceProperties){
    return dataSourceProperties.initializeDataSourceBuilder().build();

}

@Primary
@Bean(name="mysqlEmFactory")
public LocalContainerEntityManagerFactoryBean mysqlEmFactory(@Qualifier("mysqlDataSource")DataSource mysqlDataSource,EntityManagerFactoryBuilder builder){
    return builder.dataSource(mysqlDataSource).packages("PACKAGE OF YOUR MODELS").build();
}


@Bean(name="mysqlTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEmFactory")EntityManagerFactory factory){
    return new JpaTransactionManager(factory);
}
}

H2DBConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "dsEmFactory" ,transactionManagerRef = "dsTransactionManager")
public class H2DBConfig{

        @Autowired
        private Environment env;

        @Bean(name="dsProperities")
        @ConfigurationProperties(prefix="spring.h2")
        public DataSourceProperties dsProperities(){
            return new  DataSourceProperties();
        }


    @Bean(name="dsDataSource")
    public DataSource dsDataSource(@Qualifier("dsProperities")DataSourceProperties dataSourceProperties){
        return dataSourceProperties.initializeDataSourceBuilder().build();

    }

    @Bean(name="dsEmFactory")
    public LocalContainerEntityManagerFactoryBean dsEmFactory(@Qualifier("dsDataSource")DataSource dsDataSource,EntityManagerFactoryBuilder builder){
        LocalContainerEntityManagerFactoryBean em =  builder.dataSource(dsDataSource).packages("PACKAGE OF YOUR MODELS").build();
        HibernateJpaVendorAdapter ven = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(ven);
        HashMap<String, Object> prop = new HashMap<>();
        prop.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
        prop.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));

        em.setJpaPropertyMap(prop);
        em.afterPropertiesSet();
        return em;
    }


    @Bean(name="dsTransactionManager")
    public PlatformTransactionManager dsTransactionManager(@Qualifier("dsEmFactory")EntityManagerFactory factory){
        return new JpaTransactionManager(factory);
    }
}

application.properties

#---mysql DATASOURCE---
spring.mysql.driverClassName = com.mysql.jdbc.Driver
spring.mysql.url = jdbc:mysql://127.0.0.1:3306/test
spring.mysql.username = root
spring.mysql.password = root
#----------------------

#---H2 DATASOURCE----
spring.h2.driverClassName = org.h2.Driver
spring.h2.url = jdbc:h2:file:~/test
spring.h2.username = root
spring.h2.password = root
#---------------------------

#------JPA----- 
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

Application.java

@SpringBootApplication
public class Application {


    public static void main(String[] args)   {
        ApplicationContext ac=SpringApplication.run(KeopsSageInvoiceApplication.class, args);
        UserMysqlDao userRepository = ac.getBean(UserMysqlDao.class)
        //for exemple save a new user using your repository 
        userRepository.save(new UserMysql());

    }
}

How to add/update child entities when updating a parent entity in EF

public async Task<IHttpActionResult> PutParent(int id, Parent parent)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != parent.Id)
            {
                return BadRequest();
            }

            db.Entry(parent).State = EntityState.Modified;

            foreach (Child child in parent.Children)
            {
                db.Entry(child).State = child.Id == 0 ? EntityState.Added : EntityState.Modified;
            }

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ParentExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Ok(db.Parents.Find(id));
        }

This is how I solved this problem. This way, EF knows which to add which to update.

How to edit .csproj file

For JetBrains Rider:

First Option

  1. Unload Project
  2. Double click the unloaded project

Second option:

  1. Click on the project
  2. Press F4

That's it!

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

Setting up an MS-Access DB for multi-user access

i think Access is a best choice for your case. But you have to split database, see: http://accessblog.net/2005/07/how-to-split-database-into-be-and-fe.html

•How can we make sure that the write-user can make changes to the table data while other users use the data? Do the read-users put locks on tables? Does the write-user have to put locks on the table? Does Access do this for us or do we have to explicitly code this?

there are no read locks unless you put them explicitly. Just use "No Locks"

•Are there any common problems with "MS Access transactions" that we should be aware of?

should not be problems with 1-2 write users

•Can we work on forms, queries etc. while they are being used? How can we "program" without being in the way of the users?

if you split database - then no problem to work on FE design.

•Which settings in MS Access have an influence on how things are handled?

What do you mean?

•Our background is mostly in Oracle, where is Access different in handling multiple users? Is there such thing as "isolation levels" in Access?

no isolation levels in access. BTW, you can then later move data to oracle and keep access frontend, if you have lot of users and big database.

Convert integer into byte array (Java)

Simple solution which properly handles ByteOrder:

ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array();

How to open html file?

You can read HTML page using 'urllib'.

 #python 2.x

  import urllib

  page = urllib.urlopen("your path ").read()
  print page

Convert JSON array to Python list

data will return you a string representation of a list, but it is actually still a string. Just check the type of data with type(data). That means if you try using indexing on this string representation of a list as such data['fruits'][0], it will return you "[" as it is the first character of data['fruits']

You can do json.loads(data['fruits']) to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here

Can inner classes access private variables?

An inner class is a friend of the class it is defined within.
So, yes; an object of type Outer::Inner can access the member variable var of an object of type Outer.

Unlike Java though, there is no correlation between an object of type Outer::Inner and an object of the parent class. You have to make the parent child relationship manually.

#include <string>
#include <iostream>

class Outer
{
    class Inner
    {
        public:
            Inner(Outer& x): parent(x) {}
            void func()
            {
                std::string a = "myconst1";
                std::cout << parent.var << std::endl;

                if (a == MYCONST)
                {   std::cout << "string same" << std::endl;
                }
                else
                {   std::cout << "string not same" << std::endl;
                }
            }
        private:
            Outer&  parent;
    };

    public:
        Outer()
            :i(*this)
            ,var(4)
        {}
        Outer(Outer& other)
            :i(other)
            ,var(22)
        {}
        void func()
        {
            i.func();
        }
    private:
        static const char* const MYCONST;
        Inner i;
        int var;
};

const char* const Outer::MYCONST = "myconst";

int main()
{

    Outer           o1;
    Outer           o2(o1);
    o1.func();
    o2.func();
}

Why does "return list.sort()" return None, not the list?

Here is an email from Guido van Rossum in Python's dev list explaining why he choose not to return self on operations that affects the object and don't return a new one.

This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:

 x.compress().chop(y).sort(z)

which would be the same as

  x.compress()
  x.chop(y)
  x.sort(z)

I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else.

I'd like to reserve chaining for operations that return new values, like string processing operations:

 y = x.rstrip("\n").split(":").lower()

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Just like to contribute that the above answers of :not() can be very effective in angular forms, rather than creating effects or adjusting the view/DOM,

input.ng-invalid:not(.ng-pristine) { ... your css here i.e. border-color: red; ...}

Ensures that on loading your page, the input fields will only show the invalid (red borders or backgrounds, etc) if they have data added (i.e. no longer pristine) but are invalid.

Cannot add a project to a Tomcat server in Eclipse

In my case:

Project properties ? Project Facets. Make sure "Dynamic Web Module" is checked. Finally, I enter the version number "2.3" instead of "3.0". After that, the Apache Tomcat 5.5 runtime is listed in the "Runtimes" tab.

Changing Node.js listening port

I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js

var server = app.listen(8080, function() {
    console.log('Ready on port %d', server.address().port);
});

This will log Ready on port 8080 to your console.

Setting a max character length in CSS

There is a CSS 'length value' of ch.

From MDN

This unit represents the width, or more precisely the advance measure, of the glyph '0' (zero, the Unicode character U+0030) in the element's font.

This may approximate what you are after.

_x000D_
_x000D_
p {_x000D_
  overflow: hidden;_x000D_
  max-width: 75ch;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!Lorem ipsum dolor sit amet, consectetur_x000D_
  adipisicing elit. Dolorem voluptates vel dolorum autem ex repudiandae iste quasi. Minima explicabo qui necessitatibus porro nihil aliquid deleniti ullam repudiandae dolores corrupti eaque.</p>
_x000D_
_x000D_
_x000D_

Succeeded installing but could not start apache 2.4 on my windows 7 system

I was also facing the same issue, then i tried restarting my system after every change and it worked for me:

  1. Uninstall Apache2.4 in cmd prompt (run administrator) with the command: httpd -k uninstall.
  2. Restart the system.
  3. open cmd prompt (run administrator) with the command: httpd -k install.
  4. Then httpd -k install.

Hope you find useful.

StringIO in Python3

I hope this will meet your requirement

import PyPDF4
import io

pdfFile = open(r'test.pdf', 'rb')
pdfReader = PyPDF4.PdfFileReader(pdfFile)
pageObj = pdfReader.getPage(1)
pagetext = pageObj.extractText()

for line in io.StringIO(pagetext):
    print(line)

How a thread should close itself in Java?

If you simply call interrupt(), the thread will not automatically be closed. Instead, the Thread might even continue living, if isInterrupted() is implemented accordingly. The only way to guaranteedly close a thread, as asked for by OP, is

Thread.currentThread().stop();

Method is deprecated, however.

Calling return only returns from the current method. This only terminates the thread if you're at its top level.

Nevertheless, you should work with interrupt() and build your code around it.

How to pass url arguments (query string) to a HTTP request on Angular?

The HttpClient methods allow you to set the params in it's options.

You can configure it by importing the HttpClientModule from the @angular/common/http package.

import {HttpClientModule} from '@angular/common/http';

@NgModule({
  imports: [ BrowserModule, HttpClientModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

After that you can inject the HttpClient and use it to do the request.

import {HttpClient} from '@angular/common/http'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor(private httpClient: HttpClient) {
    this.httpClient.get('/url', {
      params: {
        appid: 'id1234',
        cnt: '5'
      },
      observe: 'response'
    })
    .toPromise()
    .then(response => {
      console.log(response);
    })
    .catch(console.log);
  }
}

For angular versions prior to version 4 you can do the same using the Http service.

The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.

The search field of that object can be used to set a string or a URLSearchParams object.

An example:

 // Parameters obj-
 let params: URLSearchParams = new URLSearchParams();
 params.set('appid', StaticSettings.API_KEY);
 params.set('cnt', days.toString());

 //Http request-
 return this.http.get(StaticSettings.BASE_URL, {
   search: params
 }).subscribe(
   (response) => this.onGetForecastResult(response.json()), 
   (error) => this.onGetForecastError(error.json()), 
   () => this.onGetForecastComplete()
 );

The documentation for the Http class has more details. It can be found here and an working example here.

Populating spinner directly in the layout xml

In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!

Example -Before :

<string-array name="roomSize">
    <item>Small(0-4)</item>
    <item>Medium(4-8)</item>
    <item>Large(9+)</item>
</string-array>

Example - After:

<string-array android:name="roomSize">
    <item>Small(0-4)</item>
    <item>Medium(4-8)</item>
    <item>Large(9+)</item>
</string-array>

How can I check whether a variable is defined in Node.js?

If your variable is not declared nor defined:

if ( typeof query !== 'undefined' ) { ... }

If your variable is declared but undefined. (assuming the case here is that the variable might not be defined but it can be any other falsy value like false or "")

if ( query ) { ... }

If your variable is declared but can be undefined or null:

if ( query != null ) { ... } // undefined == null

How do we check if a pointer is NULL pointer?

The representation of pointers is irrelevant to comparing them, since all comparisons in C take place as values not representations. The only way to compare the representation would be something hideous like:

static const char ptr_rep[sizeof ptr] = { 0 };
if (!memcmp(&ptr, ptr_rep, sizeof ptr)) ...

RestTemplate: How to send URL and query parameters together

I would use buildAndExpand from UriComponentsBuilder to pass all types of URI parameters.

For example:

String url = "http://test.com/solarSystem/planets/{planet}/moons/{moon}";

// URI (URL) parameters
Map<String, String> urlParams = new HashMap<>();
urlParams.put("planets", "Mars");
urlParams.put("moons", "Phobos");

// Query parameters
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
        // Add query parameter
        .queryParam("firstName", "Mark")
        .queryParam("lastName", "Watney");

System.out.println(builder.buildAndExpand(urlParams).toUri());
/**
 * Console output:
 * http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney
 */

restTemplate.exchange(builder.buildAndExpand(urlParams).toUri() , HttpMethod.PUT,
        requestEntity, class_p);

/**
 * Log entry:
 * org.springframework.web.client.RestTemplate Created PUT request for "http://test.com/solarSystem/planets/Mars/moons/Phobos?firstName=Mark&lastName=Watney"
 */

Angular ngClass and click event for toggling class

ngClass should be wrapped in square brackets as this is a property binding. Try this:

<div class="my_class" (click)="clickEvent($event)"  [ngClass]="{'active': toggle}">                
     Some content
</div>

In your component:

     //define the toogle property
     private toggle : boolean = false;

    //define your method
    clickEvent(event){
       //if you just want to toggle the class; change toggle variable.
       this.toggle = !this.toggle;       
    }

Hope that helps.

How do I print to the debug output window in a Win32 app?

If you need to see the output of an existing program that extensively used printf w/o changing the code (or with minimal changes) you can redefine printf as follows and add it to the common header (stdafx.h).

int print_log(const char* format, ...)
{
    static char s_printf_buf[1024];
    va_list args;
    va_start(args, format);
    _vsnprintf(s_printf_buf, sizeof(s_printf_buf), format, args);
    va_end(args);
    OutputDebugStringA(s_printf_buf);
    return 0;
}

#define printf(format, ...) \
        print_log(format, __VA_ARGS__)

Node / Express: EADDRINUSE, Address already in use - Kill server

FYI, you can kill the process in one command sudo fuser -k 3000/tcp. This can be done for all other ports like 8000, 8080 or 9000 which are commonly used for development.

stop service in android

This code works for me: check this link
This is my code when i stop and start service in activity

case R.id.buttonStart:
  Log.d(TAG, "onClick: starting srvice");
  startService(new Intent(this, MyService.class));
  break;
case R.id.buttonStop:
  Log.d(TAG, "onClick: stopping srvice");
  stopService(new Intent(this, MyService.class));
  break;
}
}
 }

And in service class:

  @Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

    player = MediaPlayer.create(this, R.raw.braincandy);
    player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    player.stop();
}

HAPPY CODING!

Re-sign IPA (iPhone)

None of these resigning approaches were working for me, so I had to work out something else.

In my case, I had an IPA with an expired certificate. I could have rebuilt the app, but because we wanted to ensure we were distributing exactly the same version (just with a new certificate), we did not want to rebuild it.

Instead of the ways of resigning mentioned in the other answers, I turned to Xcode’s method of creating an IPA, which starts with an .xcarchive from a build.

  1. I duplicated an existing .xcarchive and started replacing the contents. (I ignored the .dSYM file.)

  2. I extracted the old app from the old IPA file (via unzipping; the app is the only thing in the Payload folder)

  3. I moved this app into the new .xcarchive, under Products/Applications replacing the app that was there.

  4. I edited Info.plist, editing

    • ApplicationProperties/ApplicationPath
    • ApplicationProperties/CFBundleIdentifier
    • ApplicationProperties/CFBundleShortVersionString
    • ApplicationProperties/CFBundleVersion
    • Name
  5. I moved the .xcarchive into Xcode’s archive folder, usually /Users/xxxx/Library/Developer/Xcode/Archives.

  6. In Xcode, I opened the Organiser window, picked this new archive and did a regular (in this case Enterprise) export.

The result was a good IPA that works.

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

When you approach this question as a programmer, one factor stands out: if you're using recursion, then depth-first search is simpler to implement, because you don't need to maintain an additional data structure containing the nodes yet to explore.

Here's depth-first search for a non-oriented graph if you're storing “already visited” information in the nodes:

def dfs(origin):                               # DFS from origin:
    origin.visited = True                      # Mark the origin as visited
    for neighbor in origin.neighbors:          # Loop over the neighbors
        if not neighbor.visited: dfs(neighbor) # Visit each neighbor if not already visited

If storing “already visited” information in a separate data structure:

def dfs(node, visited):                        # DFS from origin, with already-visited set:
    visited.add(node)                          # Mark the origin as visited
    for neighbor in node.neighbors:            # Loop over the neighbors
        if not neighbor in visited:            # If the neighbor hasn't been visited yet,
            dfs(neighbor, visited)             # then visit the neighbor
dfs(origin, set())

Contrast this with breadth-first search where you need to maintain a separate data structure for the list of nodes yet to visit, no matter what.

How to align this span to the right of the div?

You can do this without modifying the html. http://jsfiddle.net/8JwhZ/1085/

<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>

.title span:nth-of-type(1) { float:right }
.title span:nth-of-type(2) { float:left }

How to beautifully update a JPA entity in Spring Data?

This is more an object initialzation question more than a jpa question, both methods work and you can have both of them at the same time , usually if the data member value is ready before the instantiation you use the constructor parameters, if this value could be updated after the instantiation you should have a setter.

Detect iPhone/iPad purely by css

I use these:

/* Non-Retina */
@media screen and (-webkit-max-device-pixel-ratio: 1) {
}

/* Retina */
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
}

/* iPhone Portrait */
@media screen and (max-device-width: 480px) and (orientation:portrait) {
} 

/* iPhone Landscape */
@media screen and (max-device-width: 480px) and (orientation:landscape) {
}

/* iPad Portrait */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
}

/* iPad Landscape */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
}

http://zsprawl.com/iOS/2012/03/css-for-iphone-ipad-and-retina-displays/

Windows service on Local Computer started and then stopped error

EventLog.Log should be set as "Application"

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

Ubuntu: Using curl to download an image

For ones who got permission denied for saving operation, here is the command that worked for me:

$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png --output py.png

Why can't overriding methods throw exceptions broader than the overridden method?

To understand this let's consider an example where we have a class Mammal which defines readAndGet method which is reading some file, doing some operation on it and returning an instance of class Mammal.

class Mammal {
    public Mammal readAndGet() throws IOException {//read file and return Mammal`s object}
}

Class Human extends class Mammal and overrides readAndGet method to return the instance of Human instead of the instance of Mammal.

class Human extends Mammal {
    @Override
    public Human readAndGet() throws FileNotFoundException {//read file and return Human object}
}

To call readAndGet we will need to handle IOException because its a checked exception and mammal's readAndMethod is throwing it.

Mammal mammal = new Human();
try {
    Mammal obj = mammal.readAndGet();
} catch (IOException ex) {..}

And we know that for compiler mammal.readAndGet() is getting called from the object of class Mammal but at, runtime JVM will resolve mammal.readAndGet() method call to a call from class Human because mammal is holding new Human().

Method readAndMethod from Mammal is throwing IOException and because it is a checked exception compiler will force us to catch it whenever we call readAndGet on mammal

Now suppose readAndGet in Human is throwing any other checked exception e.g. Exception and we know readAndGet will get called from the instance of Human because mammal is holding new Human().

Because for compiler the method is getting called from Mammal, so the compiler will force us to handle only IOException but at runtime we know method will be throwing Exception exception which is not getting handled and our code will break if the method throws the exception.

That's why it is prevented at the compiler level itself and we are not allowed to throw any new or broader checked exception because it will not be handled by JVM at the end.

There are other rules as well which we need to follow while overriding the methods and you can read more on Why We Should Follow Method Overriding Rules to know the reasons.

How to return multiple values in one column (T-SQL)?

Well... I see that an answer was already accepted... but I think you should see another solutions anyway:

/* EXAMPLE */
DECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))
INSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'
     UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'
     UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'

/* QUERY */
;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )
SELECT 
    LEFT(tmp.UserId, 10) +
    '/ ' +
    STUFF(
            (   SELECT ', '+Alias 
                FROM @UserAliases 
                WHERE UserId = tmp.UserId 
                FOR XML PATH('') 
            ) 
            , 1, 2, ''
        ) AS [UserId/Alias]
FROM tmp

/* -- OUTPUT
  UserId/Alias
  1/ MrX, MrY, MrA
  2/ Abc, Xyz    
*/

Quickest way to convert XML to JSON in Java

I don't know what your exact problem is, but if you're receiving XML and want to return JSON (or something) you could also look at JAX-B. This is a standard for marshalling/unmarshalling Java POJO's to XML and/or Json. There are multiple libraries that implement JAX-B, for example Apache's CXF.

Making text bold using attributed string in swift

Just use code something like this:

 let font = UIFont(name: "Your-Font-Name", size: 10.0)!

        let attributedText = NSMutableAttributedString(attributedString: noteLabel.attributedText!)
        let boldedRange = NSRange(attributedText.string.range(of: "Note:")!, in: attributedText.string)
        attributedText.addAttributes([NSAttributedString.Key.font : font], range: boldedRange)
        noteLabel.attributedText = attributedText

New lines (\r\n) are not working in email body

Another thing use "", there is a difference between "\r\n" and '\r\n'.

Strip first and last character from C string

Another option, again assuming that "edit" means you want to modify in place:

void topntail(char *str) {
    size_t len = strlen(str);
    assert(len >= 2); // or whatever you want to do with short strings
    memmove(str, str+1, len-2);
    str[len-2] = 0;
}

This modifies the string in place, without generating a new address as pmg's solution does. Not that there's anything wrong with pmg's answer, but in some cases it's not what you want.

Why am I getting InputMismatchException?

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

UPDATE

CASE 1

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

CASE 2

You have entered something, which is out of range as I have mentioned above.

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*;

public class Test {
    public static void main(String... args) {
        new Test().askForMarks(5);
    }

    public void askForMarks(int student) {
        double marks[] = new double[student];
        int index = 0;
        Scanner reader = new Scanner(System.in);
        while (index < student) {
            System.out.print("Please enter a mark (0..30): ");
            marks[index] = (double) checkValueWithin(0, 30); 
            index++;
        }
    }

    public double checkValueWithin(int min, int max) {
        double num;
        Scanner reader = new Scanner(System.in);
        num = reader.nextDouble();                         
        while (num < min || num > max) {                 
            System.out.print("Invalid. Re-enter number: "); 
            num = reader.nextDouble();                         
        } 

        return num;
    }
}

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).

SUM of grouped COUNT in SQL Query

I required having count(*) > 1 also. So, I wrote my own query after referring some the above queries

SYNTAX:

select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where {some condition} group by {some_column} having count(`table_name`.`id`) > 1) as `tmp`;

Example:

select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where `table_name`.`name` IS NOT NULL and `table_name`.`name` != '' group by `table_name`.`name` having count(`table_name`.`id`) > 1) as `tmp`;

rewrite a folder name using .htaccess

try:

RewriteRule ^/apple(.*)?$ /folder1$1 [NC]

Where the folder you want to appear in the url is in the first part of the statement - this is what it will match against and the second part 'rewrites' it to your existing folder. the [NC] flag means that it will ignore case differences eg Apple/ will still forward.

See here for a tutorial: http://www.sitepoint.com/article/guide-url-rewriting/

There is also a nice test utility for windows you can download from here: http://www.helicontech.com/download/rxtest.zip Just to note for the tester you need to leave out the domain name - so the test would be against /folder1/login.php

to redirect from /folder1 to /apple try this:

RewriteRule ^/folder1(.*)?$ /apple$1 [R]

to redirect and then rewrite just combine the above in the htaccess file:

RewriteRule ^/folder1(.*)?$ /apple$1 [R]
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]

Android Overriding onBackPressed()

Override the onBackPressed() method as per the example by codeMagic, and remove the call to super.onBackPressed(); if you do not want the default action (finishing the current activity) to be executed.

How to pass the password to su/sudo/ssh without overriding the TTY?

Hardcoding a password in an expect script is the same as having a passwordless sudo, actually worse, since sudo at least logs its commands.

set option "selected" attribute from dynamic created option

To set the input option at run time try setting the 'checked' value. (even if it isn't a checkbox)

elem.checked=true;

Where elem is a reference to the option to be selected.

So for the above issue:

var country = document.getElementById("country");
country.options[country.options.selectedIndex].checked=true;

This works for me, even when the options are not wrapped in a .

If all of the tags share the same name, they should uncheck when the new one is checked.

Function to calculate R2 (R-squared) in R

It is not something obvious, but the caret package has a function postResample() that will calculate "A vector of performance estimates" according to the documentation. The "performance estimates" are

  • RMSE
  • Rsquared
  • mean absolute error (MAE)

and have to be accessed from the vector like this

library(caret)
vect1 <- c(1, 2, 3)
vect2 <- c(3, 2, 2)
res <- caret::postResample(vect1, vect2)
rsq <- res[2]

However, this is using the correlation squared approximation for r-squared as mentioned in another answer. I'm not sure why Max Kuhn didn't just use the conventional 1-SSE/SST.

caret also has an R2() method, although it's hard to find in the documentation.

The way to implement the normal coefficient of determination equation is:

preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)
tss <- sum((actual - mean(actual)) ^ 2)
rsq <- 1 - rss/tss

Not too bad to code by hand of course, but why isn't there a function for it in a language primarily made for statistics? I'm thinking I must be missing the implementation of R^2 somewhere, or no one cares enough about it to implement it. Most of the implementations, like this one, seem to be for generalized linear models.

How to drop a list of rows from Pandas dataframe?

To drop rows with indices 1, 2, 4 you can use:

df[~df.index.isin([1, 2, 4])]

The tilde operator ~ negates the result of the method isin. Another option is to drop indices:

df.loc[df.index.drop([1, 2, 4])]

Changing the interval of SetInterval while it's running

You could use an anonymous function:

var counter = 10;
var myFunction = function(){
    clearInterval(interval);
    counter *= 10;
    interval = setInterval(myFunction, counter);
}
var interval = setInterval(myFunction, counter);

UPDATE: As suggested by A. Wolff, use setTimeout to avoid the need for clearInterval.

var counter = 10;
var myFunction = function() {
    counter *= 10;
    setTimeout(myFunction, counter);
}
setTimeout(myFunction, counter);

Google Chrome Full Black Screen

You are probably using an AMD/ATI graphics card. If so go to Catalyst Control Centre and switch Chrome to use only the Intel HD graphics (power saving). It is a problem with Chrome 18 and it is being fixed shortly (as advised by google six hours before this post)

It fixed after switched the graphics card in Catalyst, then restarted the computer.

How to parse a JSON object to a TypeScript Object

i like to use a littly tiny library called class-transformer.

it can handle nested-objects, map strings to date-objects and handle different json-property-names a lot more.

Maybe worth a look.

import { Type, plainToClass, Expose } from "class-transformer";
import 'reflect-metadata';

export class Employee{
    @Expose({ name: "uid" })
    id: number;

    firstname: string;
    lastname: string;
    birthdate: Date;
    maxWorkHours: number;
    department: string;

    @Type(() => Permission)
    permissions: Permission[] = [];
    typeOfEmployee: string;
    note: string;

    @Type(() => Date)
    lastUpdate: Date;
}

export class Permission {
  type : string;
}

let json:string = {
    "uid": 123,
    "department": "<anystring>",
    "typeOfEmployee": "<anystring>",
    "firstname": "<anystring>",
    "lastname": "<anystring>",
    "birthdate": "<anydate>",
    "maxWorkHours": 1,
    "username": "<anystring>",
    "permissions": [
      {'type' : 'read'},
      {'type' : 'write'}
    ],
    "lastUpdate": "2020-05-08"
}

console.log(plainToClass(Employee, json));

```

How to get the total number of rows of a GROUP BY query?

There are two ways you can count the number of rows.

$query = "SELECT count(*) as total from table1";
$prepare = $link->prepare($query);
$prepare->execute();
$row = $prepare->fetch(PDO::FETCH_ASSOC);
echo $row['total']; // This will return you a number of rows.

Or second way is

$query = "SELECT field1, field2 from table1";
$prepare = $link->prepare($query);
$prepare->execute();
$row = $prepare->fetch(PDO::FETCH_NUM);
echo $rows[0]; // This will return you a number of rows as well.

Placing border inside of div and not on its edge

If you use box-sizing: border-box means not only border, padding,margin, etc. All element will come inside of the parent element.

_x000D_
_x000D_
div p {_x000D_
    box-sizing: border-box;_x000D_
    -moz-box-sizing: border-box;_x000D_
    -webkit-box-sizing: border-box;_x000D_
    width: 150px;_x000D_
    height:100%;_x000D_
    border: 20px solid #f00;_x000D_
    background-color: #00f;_x000D_
    color:#fff;_x000D_
    padding: 10px;_x000D_
  _x000D_
}
_x000D_
<div>_x000D_
  <p>It was popularised in the 1960s with the release of Letraset sheets</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

datetime datatype in java

java.util.Date represents an instant in time, with no reference to a particular time zone or calendar system. It does hold both date and time though - it's basically a number of milliseconds since the Unix epoch.

Alternatively you can use java.util.Calendar which does know about both of those things.

Personally I would strongly recommend you use Joda Time which is a much richer date/time API. It allows you to express your data much more clearly, with types for "just dates", "just local times", "local date/time", "instant", "date/time with time zone" etc. Most of the types are also immutable, which is a huge benefit in terms of code clarity.

BSTR to std::string (std::wstring) and vice versa

BSTR to std::wstring:

// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));

 
std::wstring to BSTR:

// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());

Doc refs:

  1. std::basic_string<typename CharT>::basic_string(const CharT*, size_type)
  2. std::basic_string<>::empty() const
  3. std::basic_string<>::data() const
  4. std::basic_string<>::size() const
  5. SysStringLen()
  6. SysAllocStringLen()

How do I merge my local uncommitted changes into another Git branch?

A shorter alternative to the previously mentioned stash approach would be:

Temporarily move the changes to a stash.

  1. git stash

Create and switch to a new branch and then pop the stash to it in just one step.

  1. git stash branch new_branch_name

Then just add and commit the changes to this new branch.

How do you read CSS rule values with JavaScript?

Adapted from here, building on scunliffe's answer:

function getStyle(className) {
    var cssText = "";
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var x = 0; x < classes.length; x++) {        
        if (classes[x].selectorText == className) {
            cssText += classes[x].cssText || classes[x].style.cssText;
        }         
    }
    return cssText;
}

alert(getStyle('.test'));

TypeError: Image data can not convert to float

try

import skimage
import random
from random import randint
import numpy as np
import matplotlib.pyplot as plt


xrow = raw_input("Enter the number of rows to be present in image.=>")
row = int(xrow)
ycolumn = raw_input("Enter the number of columns to be present in image.=>")
column = int(ycolumn)

A = np.zeros((row,column))
for x in xrange(1, row):
    for y in xrange(1, column):
        a = randint(0, 65535)
        A[x, y] = a

plt.imshow(A)
plt.show()

Non-static variable cannot be referenced from a static context

Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.

Static variables are marked as static and instance variables doesn't have specific keyword.

Segmentation fault on large array sizes

Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.

Is there a way to access an iteration-counter in Java's for-each loop?

If you need a counter in an for-each loop you have to count yourself. There is no built in counter as far as I know.

How can I String.Format a TimeSpan object with a custom format in .NET?

Simple. Use TimeSpan.ToString with c, g or G. More information at MSDN

How to use vertical align in bootstrap

.parent {
    display: table;
    table-layout: fixed;
}

.child {
    display:table-cell;
    vertical-align:middle;
    text-align:center;
}

table-layout: fixed prevents breaking the functionality of the col-* classes.

How to remove gaps between subplots in matplotlib?

Have you tried plt.tight_layout()?

with plt.tight_layout() enter image description here without it: enter image description here

Or: something like this (use add_axes)

left=[0.1,0.3,0.5,0.7]
width=[0.2,0.2, 0.2, 0.2]
rectLS=[]
for x in left:
   for y in left:
       rectLS.append([x, y, 0.2, 0.2])
axLS=[]
fig=plt.figure()
axLS.append(fig.add_axes(rectLS[0]))
for i in [1,2,3]:
     axLS.append(fig.add_axes(rectLS[i],sharey=axLS[-1]))    
axLS.append(fig.add_axes(rectLS[4]))
for i in [1,2,3]:
     axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))
axLS.append(fig.add_axes(rectLS[8]))
for i in [5,6,7]:
     axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))     
axLS.append(fig.add_axes(rectLS[12]))
for i in [9,10,11]:
     axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))

If you don't need to share axes, then simply axLS=map(fig.add_axes, rectLS) enter image description here

Make an Installation program for C# applications and include .NET Framework installer into the setup

You need to create installer, which will check if user has required .NET Framework 4.0. You can use WiX to create installer. It's very powerfull and customizable. Also you can use ClickOnce to create installer - it's very simple to use. It will allow you with one click add requirement to install .NET Framework 4.0.

How can I use modulo operator (%) in JavaScript?

It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:

10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.

Apparently it is not the same as the modulo operator entirely.

Revert to a commit by a SHA hash in Git?

It reverts the said commit, that is, adds the commit opposite to it. If you want to checkout an earlier revision, you do:

git checkout 56e05fced214c44a37759efa2dfc25a65d8ae98d

Understanding the map function

map doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map.

map in Python 3 is equivalent to this:

def map(func, iterable):
    for i in iterable:
        yield func(i)

and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yielding.

Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map, particularly if you're using a lambda expression as the first argument:

[func(i) for i in iterable]

As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -

 >>> a = "hello, world"
 >>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')

A use of map here would be if you start with a list of strings instead of a single string - map can listify all of them individually:

>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Note that map(list, a) is equivalent in Python 2, but in Python 3 you need the list call if you want to do anything other than feed it into a for loop (or a processing function such as sum that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:

>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Android Left to Right slide animation

You can overwrite your default activity animation. Here is the solution that I use:

Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorPrimary</item>
    <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>

</style>

<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
    <item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
    <item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
    <item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
    <item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>

Create anim folder under res folder and then create this four animation files:

slide_in_right.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_out_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%p"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_in_left.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_out_right.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="100%p"
        android:duration="@android:integer/config_mediumAnimTime"/>
</set>

This is my sample project in github.

That's all... Happy coding :)

How do I protect Python code?

The best you can do with Python is to obscure things.

  • Strip out all docstrings
  • Distribute only the .pyc compiled files.
  • freeze it
  • Obscure your constants inside a class/module so that help(config) doesn't show everything

You may be able to add some additional obscurity by encrypting part of it and decrypting it on the fly and passing it to eval(). But no matter what you do someone can break it.

None of this will stop a determined attacker from disassembling the bytecode or digging through your api with help, dir, etc.

How can I share Jupyter notebooks with non-programmers?

Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.

Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing:

!ipython nbconvert <notebook name>.ipynb --to html

EDIT: With Jupyter/IPython's Big Split, you'll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html now.

How do I move to end of line in Vim?

Or there's the obvious answer: use the End key to go to the end of the line.

CSS background opacity with rgba not working in IE 8

It is very simply you have to give first you have to give backgound as rgb because Internet Explorer 8 will support rgb instead rgba and then u have to give opacity like filter:alpha(opacity=50);

background:rgb(0,0,0);
filter:alpha(opacity=50);

New line in Sql Query

Pinal Dave explains this well in his blog.

http://blog.sqlauthority.com/2009/07/01/sql-server-difference-between-line-feed-n-and-carriage-return-r-t-sql-new-line-char/

DECLARE @NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
PRINT ('SELECT FirstLine AS FL ' + @NewLineChar + 'SELECT SecondLine AS SL')

keytool error Keystore was tampered with, or password was incorrect

I fixed this issue by deleting the output file and running the command again. It turns out it does NOT overwrite the previous file. I had this issue when renewing a let's encrypt cert with tomcat

Python constructors and __init__

There is no notion of method overloading in Python. But you can achieve a similar effect by specifying optional and keyword arguments

display:inline vs display:block

display: block means that the element is displayed as a block, as paragraphs and headers have always been. A block has some whitespace above and below it and tolerates no HTML elements next to it, except when ordered otherwise (by adding a float declaration to another element, for instance).

display: inline means that the element is displayed inline, inside the current block on the same line. Only when it's between two blocks does the element form an 'anonymous block', that however has the smallest possible width.

Read more about display options : http://www.quirksmode.org/css/display.html

How to return a custom object from a Spring Data JPA GROUP BY query

Solution for JPQL queries

This is supported for JPQL queries within the JPA specification.

Step 1: Declare a simple bean class

package com.path.to;

public class SurveyAnswerStatistics {
  private String answer;
  private Long   cnt;

  public SurveyAnswerStatistics(String answer, Long cnt) {
    this.answer = answer;
    this.count  = cnt;
  }
}

Step 2: Return bean instances from the repository method

public interface SurveyRepository extends CrudRepository<Survey, Long> {
    @Query("SELECT " +
           "    new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) " +
           "FROM " +
           "    Survey v " +
           "GROUP BY " +
           "    v.answer")
    List<SurveyAnswerStatistics> findSurveyCount();
}

Important notes

  1. Make sure to provide the fully-qualified path to the bean class, including the package name. For example, if the bean class is called MyBean and it is in package com.path.to, the fully-qualified path to the bean will be com.path.to.MyBean. Simply providing MyBean will not work (unless the bean class is in the default package).
  2. Make sure to call the bean class constructor using the new keyword. SELECT new com.path.to.MyBean(...) will work, whereas SELECT com.path.to.MyBean(...) will not.
  3. Make sure to pass attributes in exactly the same order as that expected in the bean constructor. Attempting to pass attributes in a different order will lead to an exception.
  4. Make sure the query is a valid JPA query, that is, it is not a native query. @Query("SELECT ..."), or @Query(value = "SELECT ..."), or @Query(value = "SELECT ...", nativeQuery = false) will work, whereas @Query(value = "SELECT ...", nativeQuery = true) will not work. This is because native queries are passed without modifications to the JPA provider, and are executed against the underlying RDBMS as such. Since new and com.path.to.MyBean are not valid SQL keywords, the RDBMS then throws an exception.

Solution for native queries

As noted above, the new ... syntax is a JPA-supported mechanism and works with all JPA providers. However, if the query itself is not a JPA query, that is, it is a native query, the new ... syntax will not work as the query is passed on directly to the underlying RDBMS, which does not understand the new keyword since it is not part of the SQL standard.

In situations like these, bean classes need to be replaced with Spring Data Projection interfaces.

Step 1: Declare a projection interface

package com.path.to;

public interface SurveyAnswerStatistics {
  String getAnswer();

  int getCnt();
}

Step 2: Return projected properties from the query

public interface SurveyRepository extends CrudRepository<Survey, Long> {
    @Query(nativeQuery = true, value =
           "SELECT " +
           "    v.answer AS answer, COUNT(v) AS cnt " +
           "FROM " +
           "    Survey v " +
           "GROUP BY " +
           "    v.answer")
    List<SurveyAnswerStatistics> findSurveyCount();
}

Use the SQL AS keyword to map result fields to projection properties for unambiguous mapping.

How to execute two mysql queries as one in PHP/MYSQL?

Like this:

$result1 = mysql_query($query1);
$result2 = mysql_query($query2);

// do something with the 2 result sets...

if ($result1)
    mysql_free_result($result1);

if ($result2)
    mysql_free_result($result2);

How to return a resolved promise from an AngularJS Service using $q?

How to simply return a pre-resolved promise in AngularJS

Resolved promise:

return $q.when( someValue );    // angularjs 1.2+
return $q.resolve( someValue ); // angularjs 1.4+, alias to `when` to match ES6

Rejected promise:

return $q.reject( someValue );

Custom HTTP headers : naming conventions

RFC6648 recommends that you assume that your custom header "might become standardized, public, commonly deployed, or usable across multiple implementations." Therefore, it recommends not to prefix it with "X-" or similar constructs.

However, there is an exception "when it is extremely unlikely that [your header] will ever be standardized." For such "implementation-specific and private-use" headers, the RFC says a namespace such as a vendor prefix is justified.

__FILE__ macro shows full path

I have use the same solution with @Patrick 's answer for years.

It has a small issue when the full path contains symbol-link.

Better solution.

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-builtin-macro-redefined -D'__FILE__=\"$(subst $(realpath ${CMAKE_SOURCE_DIR})/,,$(abspath $<))\"'")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-builtin-macro-redefined -D'__FILE__=\"$(subst $(realpath ${CMAKE_SOURCE_DIR})/,,$(abspath $<))\"'")

Why should use this ?

  • -Wno-builtin-macro-redefined to mute the compiler warnings for redefining __FILE__ macro.

    For those compilers do not support this, refer to the Robust way below.

  • Strip the project path from the file path is your real requirement. You won't like to waste the time to find out where is a header.h file, src/foo/header.h or src/bar/header.h.

  • We should strip the __FILE__ macro in cmake config file.

    This macro is used in most exists codes. Simply redefine it can set you free.

    Compilers like gcc predefines this macro from the command line arguments. And the full path is written in makefiles generated by cmake.

  • Hard code in CMAKE_*_FLAGS is required.

    There is some commands to add compiler options or definitions in some more recently version, like add_definitions() and add_compile_definitions(). These commands will parse the make functions like subst before apply to source files. That is not we want.

Robust way for -Wno-builtin-macro-redefined.

include(CheckCCompilerFlag)
check_c_compiler_flag(-Wno-builtin-macro-redefined SUPPORT_C_WNO_BUILTIN_MACRO_REDEFINED)
if (SUPPORT_C_WNO_BUILTIN_MACRO_REDEFINED)
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-builtin-macro-redefined")
endif (SUPPORT_C_WNO_BUILTIN_MACRO_REDEFINED)
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-Wno-builtin-macro-redefined SUPPORT_CXX_WNO_BUILTIN_MACRO_REDEFINED)
if (SUPPORT_CXX_WNO_BUILTIN_MACRO_REDEFINED)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-builtin-macro-redefined")
endif (SUPPORT_CXX_WNO_BUILTIN_MACRO_REDEFINED)

Remember to remove this compiler option from the set(*_FLAGS ... -D__FILE__=...) line.

Preventing twitter bootstrap carousel from auto sliding on page load

Actually, the problem is now solved. I added the 'pause' argument to the method 'carousel' like below:

$(document).ready(function() {      
   $('.carousel').carousel('pause');
});

Anyway, thanks so much @Yohn for your tips toward this solution.

Adding extra zeros in front of a number using jQuery?

Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.

var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);

Setting selection to Nothing when programming Excel

If using a button to call the paste procedure,

try activating the button after the operation. this successfully clears the selection

without

  • having to mess around with hidden things
  • selecting another cell (which is exactly the opposite of what was asked)
  • affecting the clipboard mode
  • having the hacky method of pressing escape which doesn't always work

HTH

Sub BtnCopypasta_Worksheet_Click()
   range.copy
   range.paste
BtnCopypasta.Activate
End sub

HTH

Formatting numbers (decimal places, thousands separators, etc) with CSS

Another solution with pure CSS+HTML and the pseudo-class :lang().

Use some HTML to mark up the number with the classes thousands-separator and decimal-separator:

<html lang="es">
  Spanish: 1<span class="thousands-separator">200</span><span class="thousands-separator">000</span><span class="decimal-separator">.</span>50
</html>

Use the lang pseudo-class to format the number.

/* Spanish */
.thousands-separator:lang(es):before{
  content: ".";
}
.decimal-separator:lang(es){
  visibility: hidden;
  position: relative;
}
.decimal-separator:lang(es):before{
  position: absolute;
  visibility: visible;
  content: ",";
}

/* English and Mexican Spanish */
.thousands-separator:lang(en):before, .thousands-separator:lang(es-MX):before{
  content: ",";
}

Codepen: https://codepen.io/danielblazquez/pen/qBqVjGy

How to set UTF-8 encoding for a PHP file

Html:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="x" content="xx" />

vs Php:

<?php header('Content-type: text/html; charset=ISO-8859-1'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta name="x" content="xx" />

UICollectionView Self Sizing Cells with Auto Layout

Updated for Swift 5

preferredLayoutAttributesFittingAttributes renamed to preferredLayoutAttributesFitting and use auto sizing


Updated for Swift 4

systemLayoutSizeFittingSize renamed to systemLayoutSizeFitting


Updated for iOS 9

After seeing my GitHub solution break under iOS 9 I finally got the time to investigate the issue fully. I have now updated the repo to include several examples of different configurations for self sizing cells. My conclusion is that self sizing cells are great in theory but messy in practice. A word of caution when proceeding with self sizing cells.

TL;DR

Check out my GitHub project


Self sizing cells are only supported with flow layout so make sure thats what you are using.

There are two things you need to setup for self sizing cells to work.

1. Set estimatedItemSize on UICollectionViewFlowLayout

Flow layout will become dynamic in nature once you set the estimatedItemSize property.

self.flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize

2. Add support for sizing on your cell subclass

This comes in 2 flavours; Auto-Layout or custom override of preferredLayoutAttributesFittingAttributes.

Create and configure cells with Auto Layout

I won't go to in to detail about this as there's a brilliant SO post about configuring constraints for a cell. Just be wary that Xcode 6 broke a bunch of stuff with iOS 7 so, if you support iOS 7, you will need to do stuff like ensure the autoresizingMask is set on the cell's contentView and that the contentView's bounds is set as the cell's bounds when the cell is loaded (i.e. awakeFromNib).

Things you do need to be aware of is that your cell needs to be more seriously constrained than a Table View Cell. For instance, if you want your width to be dynamic then your cell needs a height constraint. Likewise, if you want the height to be dynamic then you will need a width constraint to your cell.

Implement preferredLayoutAttributesFittingAttributes in your custom cell

When this function is called your view has already been configured with content (i.e. cellForItem has been called). Assuming your constraints have been appropriately set you could have an implementation like this:

//forces the system to do one layout pass
var isHeightCalculated: Bool = false

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    //Exhibit A - We need to cache our calculation to prevent a crash.
    if !isHeightCalculated {
        setNeedsLayout()
        layoutIfNeeded()
        let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
        var newFrame = layoutAttributes.frame
        newFrame.size.width = CGFloat(ceilf(Float(size.width)))
        layoutAttributes.frame = newFrame
        isHeightCalculated = true
    }
    return layoutAttributes
}

NOTE On iOS 9 the behaviour changed a bit that could cause crashes on your implementation if you are not careful (See more here). When you implement preferredLayoutAttributesFittingAttributes you need to ensure that you only change the frame of your layout attributes once. If you don't do this the layout will call your implementation indefinitely and eventually crash. One solution is to cache the calculated size in your cell and invalidate this anytime you reuse the cell or change its content as I have done with the isHeightCalculated property.

Experience your layout

At this point you should have 'functioning' dynamic cells in your collectionView. I haven't yet found the out-of-the box solution sufficient during my tests so feel free to comment if you have. It still feels like UITableView wins the battle for dynamic sizing IMHO.

Caveats

Be very mindful that if you are using prototype cells to calculate the estimatedItemSize - this will break if your XIB uses size classes. The reason for this is that when you load your cell from a XIB its size class will be configured with Undefined. This will only be broken on iOS 8 and up since on iOS 7 the size class will be loaded based on the device (iPad = Regular-Any, iPhone = Compact-Any). You can either set the estimatedItemSize without loading the XIB, or you can load the cell from the XIB, add it to the collectionView (this will set the traitCollection), perform the layout, and then remove it from the superview. Alternatively you could also make your cell override the traitCollection getter and return the appropriate traits. It's up to you.

Let me know if I missed anything, hope I helped and good luck coding


Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

There is no best way, it depends on your use case.

  • Use way 1 if you want to create several similar objects. In your example, Person (you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages.
  • Use way 2 if you only need one object of a kind (like a singleton). If you want this object to inherit from another one, then you have to use a constructor function though.
  • Use way 3 if you want to initialize properties of the object depending on other properties of it or if you have dynamic property names.

Update: As requested examples for the third way.

Dependent properties:

The following does not work as this does not refer to book. There is no way to initialize a property with values of other properties in a object literal:

var book = {
    price: somePrice * discount,
    pages: 500,
    pricePerPage: this.price / this.pages
};

instead, you could do:

var book = {
    price: somePrice * discount,
    pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;

Dynamic property names:

If the property name is stored in some variable or created through some expression, then you have to use bracket notation:

var name = 'propertyName';

// the property will be `name`, not `propertyName`
var obj = {
    name: 42
}; 

// same here
obj.name = 42;

// this works, it will set `propertyName`
obj[name] = 42;

Rails find_or_create_by more than one attribute?

By passing a block to find_or_create, you can pass additional parameters that will be added to the object if it is created new. This is useful if you are validating the presence of a field that you aren't searching by.

Assuming:

class GroupMember < ActiveRecord::Base
    validates_presence_of :name
end

then

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create { |gm| gm.name = "John Doe" }

will create a new GroupMember with the name "John Doe" if it doesn't find one with member_id 4 and group_id 7

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

Check if value is zero or not null in python

If number could be None or a number, and you wanted to include 0, filter on None instead:

if number is not None:

If number can be any number of types, test for the type; you can test for just int or a combination of types with a tuple:

if isinstance(number, int):  # it is an integer
if isinstance(number, (int, float)):  # it is an integer or a float

or perhaps:

from numbers import Number

if isinstance(number, Number):

to allow for integers, floats, complex numbers, Decimal and Fraction objects.

How to iterate over each string in a list of strings and operate on it's elements

Try:

for word in words:
    if word[0] == word[-1]:
        c += 1
    print c

for word in words returns the items of words, not the index. If you need the index sometime, try using enumerate:

for idx, word in enumerate(words):
    print idx, word

would output

0, 'aba'
1, 'xyz'
etc.

The -1 in word[-1] above is Python's way of saying "the last element". word[-2] would give you the second last element, and so on.

You can also use a generator to achieve this.

c = sum(1 for word in words if word[0] == word[-1])

.war vs .ear file

A WAR (Web Archive) is a module that gets loaded into a Web container of a Java Application Server. A Java Application Server has two containers (runtime environments) - one is a Web container and the other is a EJB container.

The Web container hosts Web applications based on JSP or the Servlets API - designed specifically for web request handling - so more of a request/response style of distributed computing. A Web container requires the Web module to be packaged as a WAR file - that is a special JAR file with a web.xml file in the WEB-INF folder.

An EJB container hosts Enterprise java beans based on the EJB API designed to provide extended business functionality such as declarative transactions, declarative method level security and multiprotocol support - so more of an RPC style of distributed computing. EJB containers require EJB modules to be packaged as JAR files - these have an ejb-jar.xml file in the META-INF folder.

Enterprise applications may consist of one or more modules that can either be Web modules (packaged as a WAR file), EJB modules (packaged as a JAR file), or both of them. Enterprise applications are packaged as EAR files - these are special JAR files containing an application.xml file in the META-INF folder.

Basically, EAR files are a superset containing WAR files and JAR files. Java Application Servers allow deployment of standalone web modules in a WAR file, though internally, they create EAR files as a wrapper around WAR files. Standalone web containers such as Tomcat and Jetty do not support EAR files - these are not full-fledged Application servers. Web applications in these containers are to be deployed as WAR files only.

In application servers, EAR files contain configurations such as application security role mapping, EJB reference mapping and context root URL mapping of web modules.

Apart from Web modules and EJB modules, EAR files can also contain connector modules packaged as RAR files and Client modules packaged as JAR files.

How to use a link to call JavaScript?

And, why not unobtrusive with jQuery:

  $(function() {
    $("#unobtrusive").click(function(e) {
      e.preventDefault(); // if desired...
      // other methods to call...
    });
  });

HTML

<a id="unobtrusive" href="http://jquery.com">jquery</a>

Checking whether the pip is installed?

In CMD, type:

pip freeze

And it will show you a list of all the modules installed including the version number.

Output:

aiohttp==1.1.4
async-timeout==1.1.0
cx-Freeze==4.3.4
Django==1.9.2
django-allauth==0.24.1
django-cors-headers==1.2.2
django-crispy-forms==1.6.0
django-robots==2.0
djangorestframework==3.3.2
easygui==0.98.0
future==0.16.0
httpie==0.9.6
matplotlib==1.5.3
multidict==2.1.2
numpy==1.11.2
oauthlib==1.0.3
pandas==0.19.1
pefile==2016.3.28
pygame==1.9.2b1
Pygments==2.1.3
PyInstaller==3.2
pyparsing==2.1.10
pypiwin32==219
PyQt5==5.7
pytz==2016.7
requests==2.9.1
requests-oauthlib==0.6
six==1.10.0
sympy==1.0
virtualenv==15.0.3
xlrd==1.0.0
yarl==0.7.0

HTML Image not displaying, while the src url works

You can try just putting the image in the source directory. You'd link it by replacing the file path with src="../imagenamehere.fileextension In your case, j3evn.jpg.

Function not defined javascript

There are a couple of things to check:

  • In FireBug, see if there are any loading errors that would indicate that your script is badly formatted and the functions do not get registered.
  • You can also try typing "proceedToSecond" into the FireBug console to see if the function gets defined
  • One thing you may try is removing the space around the @type attribute to the script tag: it should be <script type="text/javascript"> instead of <script type = "text/javascript">

How to configure slf4j-simple

I noticed that Eemuli said that you can't change the log level after they are created - and while that might be the design, it isn't entirely true.

I ran into a situation where I was using a library that logged to slf4j - and I was using the library while writing a maven mojo plugin.

Maven uses a (hacked) version of the slf4j SimpleLogger, and I was unable to get my plugin code to reroute its logging to something like log4j, which I could control.

And I can't change the maven logging config.

So, to quiet down some noisy info messages, I found I could use reflection like this, to futz with the SimpleLogger at runtime.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
    try
    {
        Logger l = LoggerFactory.getLogger("full.classname.of.noisy.logger");  //This is actually a MavenSimpleLogger, but due to various classloader issues, can't work with the directly.
        Field f = l.getClass().getSuperclass().getDeclaredField("currentLogLevel");
        f.setAccessible(true);
        f.set(l, LocationAwareLogger.WARN_INT);
    }
    catch (Exception e)
    {
        getLog().warn("Failed to reset the log level of " + loggerName + ", it will continue being noisy.", e);
    }

Of course, note, this isn't a very stable / reliable solution... as it will break the next time the maven folks change their logger.

Responsive image align center bootstrap 3

If you're using Bootstrap v3.0.1 or greater, you should use this solution instead. It doesn't override Bootstrap's styles with custom CSS, but instead uses a Bootstrap feature.

My original answer is shown below for posterity


This is a pleasantly easy fix. Because .img-responsive from Bootstrap already sets display: block, you can use margin: 0 auto to center the image:

.product .img-responsive {
    margin: 0 auto;
}

How to add local jar files to a Maven project?

Install the JAR into your local Maven repository as follows:

mvn install:install-file \
   -Dfile=<path-to-file> \
   -DgroupId=<group-id> \
   -DartifactId=<artifact-id> \
   -Dversion=<version> \
   -Dpackaging=<packaging> \
   -DgeneratePom=true

Where each refers to:

<path-to-file>: the path to the file to load e.g ? c:\kaptcha-2.3.jar

<group-id>: the group that the file should be registered under e.g ? com.google.code

<artifact-id>: the artifact name for the file e.g ? kaptcha

<version>: the version of the file e.g ? 2.3

<packaging>: the packaging of the file e.g. ? jar

Reference

Load arrayList data into JTable

You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the List.

 PingScan p = new PingScan();
 List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
                for (final Future<String> f : scanResult) {
                    try {
                        if (f.get() instanceof String) {
                            String ip = f.get();
                            Object[] data = {ip};
                            tableModel.addRow(data);
                        }
                    } catch (InterruptedException | ExecutionException ex) {
                        Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

Margin-Top not working for span element?

Unlike div, p 1 which are Block Level elements which can take up margin on all sides,span2 cannot as it's an Inline element which takes up margins horizontally only.

From the specification:

Margin properties specify the width of the margin area of a box. The 'margin' shorthand property sets the margin for all four sides while the other margin properties only set their respective side. These properties apply to all elements, but vertical margins will not have any effect on non-replaced inline elements.

Demo 1 (Vertical margin not applied as span is an inline element)

Solution? Make your span element, display: inline-block; or display: block;.

Demo 2

Would suggest you to use display: inline-block; as it will be inline as well as block. Making it block only will result in your element to render on another line, as block level elements take 100% of horizontal space on the page, unless they are made inline-block or they are floated to left or right.


1. Block Level Elements - MDN Source

2. Inline Elements - MDN Resource

How to make my font bold using css?

Selector name{
font-weight:bold;
}

Suppose you want to make bold for p element

p{
font-weight:bold;
}

You can use other alternative value instead of bold like

p{
 font-weight:bolder;
 font-weight:600;
}

Display SQL query results in php

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

Change your code to this :

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

Correct way to quit a Qt program?

You can call qApp.exit();. I always use that and never had a problem with it.

If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.

What does it mean to "call" a function in Python?

To "call" means to make a reference in your code to a function that is written elsewhere. This function "call" can be made to the standard Python library (stuff that comes installed with Python), third-party libraries (stuff other people wrote that you want to use), or your own code (stuff you wrote). For example:

#!/usr/env python

import os

def foo():
    return "hello world"

print os.getlogin()
print foo()

I created a function called "foo" and called it later on with that print statement. I imported the standard "os" Python library then I called the "getlogin" function within that library.

How to check if multiple array keys exists

It seems to me, that the easiest method by far would be this:

$required = array('a','b','c','d');

$values = array(
    'a' => '1',
    'b' => '2'
);

$missing = array_diff_key(array_flip($required), $values);

Prints:

Array(
    [c] => 2
    [d] => 3
)

This also allows to check which keys are missing exactly. This might be useful for error handling.

Global variables in header file

There are 3 scenarios, you describe:

  1. with 2 .c files and with int i; in the header.
  2. With 2 .c files and with int i=100; in the header (or any other value; that doesn't matter).
  3. With 1 .c file and with int i=100; in the header.

In each scenario, imagine the contents of the header file inserted into the .c file and this .c file compiled into a .o file and then these linked together.

Then following happens:

  1. works fine because of the already mentioned "tentative definitions": every .o file contains one of them, so the linker says "ok".

  2. doesn't work, because both .o files contain a definition with a value, which collide (even if they have the same value) - there may be only one with any given name in all .o files which are linked together at a given time.

  3. works of course, because you have only one .o file and so no possibility for collision.

IMHO a clean thing would be

  • to put either extern int i; or just int i; into the header file,
  • and then to put the "real" definition of i (namely int i = 100;) into file1.c. In this case, this initialization gets used at the start of the program and the corresponding line in main() can be omitted. (Besides, I hope the naming is only an example; please don't name any global variables as i in real programs.)

Change remote repository credentials (authentication) on Intellij IDEA 14

I needed to change my user name and password in Intellij Did it by

preferences -> version control -> GitHub

There you can change user name and password.

"Cloning" row or column vectors

import numpy as np
x=np.array([1,2,3])
y=np.multiply(np.ones((len(x),len(x))),x).T
print(y)

yields:

[[ 1.  1.  1.]
 [ 2.  2.  2.]
 [ 3.  3.  3.]]

Get filename from input [type='file'] using jQuery

You can access to the properties you want passing an argument to your callback function (like evt), and then accessing the files with it (evt.target.files[0].name) :

$("document").ready(function(){
  $("main").append('<input type="file" name="photo" id="upload-photo"/>');
  $('#upload-photo').on('change',function(evt) {
    alert(evt.target.files[0].name);
  });
});

Ellipsis for overflow text in dropdown boxes

Found this absolute hack that actually works quite well:

https://codepen.io/nikitahl/pen/vyZbwR

Not CSS only though.

The basic gist is to have a container on the dropdown, .select-container in this case. That container has it's ::before set up to display content based on its data-content attribute/dataset, along with all of the overflow:hidden; text-overflow: ellipsis; and sizing necessary to make the ellipsis work.

When the select changes, javascript assigns the value (or you could retrieve the text of the option out of the select.options list) to the dataset.content of the container, and voila!

Copying content of the codepen here:

_x000D_
_x000D_
var selectContainer = document.querySelector(".select-container");_x000D_
var select = selectContainer.querySelector(".select");_x000D_
select.value = "lingua latina non penis canina";_x000D_
_x000D_
selectContainer.dataset.content = select.value;_x000D_
_x000D_
function handleChange(e) {_x000D_
  selectContainer.dataset.content = e.currentTarget.value;_x000D_
  console.log(select.value);_x000D_
}_x000D_
_x000D_
select.addEventListener("change", handleChange);
_x000D_
span {_x000D_
  margin: 0 10px 0 0;_x000D_
}_x000D_
_x000D_
.select-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.select-container::before {_x000D_
  content: attr(data-content);_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 10px;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  padding: 7px;_x000D_
  font: 11px Arial, sans-serif;_x000D_
  white-space: nowrap;_x000D_
  text-overflow: ellipsis;_x000D_
  overflow: hidden;_x000D_
  text-transform: capitalize;_x000D_
  pointer-events: none;_x000D_
}_x000D_
_x000D_
.select {_x000D_
  width: 80px;_x000D_
  padding: 5px;_x000D_
  appearance: none;_x000D_
  background: transparent url("https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-down-b-128.png") no-repeat calc(~"100% - 5px") 7px;_x000D_
  background-size: 10px 10px;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.regular {_x000D_
  display: inline-block;_x000D_
  margin: 10px 0 0;_x000D_
  .select {_x000D_
    color: #000;_x000D_
  }_x000D_
}
_x000D_
<span>Hack:</span><div class="select-container" data-content="">_x000D_
  <select class="select" id="words">_x000D_
    <option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
    <option value="lorem">Lorem</option>_x000D_
    <option value="ipsum">Ipsum</option>_x000D_
    <option value="dolor">Dolor</option>_x000D_
    <option value="sit">Sit</option>_x000D_
    <option value="amet">Amet</option>_x000D_
    <option value="lingua">Lingua</option>_x000D_
    <option value="latina">Latina</option>_x000D_
    <option value="non">Non</option>_x000D_
    <option value="penis">Penis</option>_x000D_
    <option value="canina">Canina</option>_x000D_
  </select>_x000D_
</div>_x000D_
<br />_x000D_
_x000D_
<span>Regular:</span>_x000D_
<div class="regular">_x000D_
  <select style="width: 80px;">_x000D_
    <option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
    <option value="lorem">Lorem</option>_x000D_
    <option value="ipsum">Ipsum</option>_x000D_
    <option value="dolor">Dolor</option>_x000D_
    <option value="sit">Sit</option>_x000D_
    <option value="amet">Amet</option>_x000D_
    <option value="lingua">Lingua</option>_x000D_
    <option value="latina">Latina</option>_x000D_
    <option value="non">Non</option>_x000D_
    <option value="penis">Penis</option>_x000D_
    <option value="canina">Canina</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

What is the purpose of meshgrid in Python / NumPy?

Suppose you have a function:

def sinus2d(x, y):
    return np.sin(x) + np.sin(y)

and you want, for example, to see what it looks like in the range 0 to 2*pi. How would you do it? There np.meshgrid comes in:

xx, yy = np.meshgrid(np.linspace(0,2*np.pi,100), np.linspace(0,2*np.pi,100))
z = sinus2d(xx, yy) # Create the image on this grid

and such a plot would look like:

import matplotlib.pyplot as plt
plt.imshow(z, origin='lower', interpolation='none')
plt.show()

enter image description here

So np.meshgrid is just a convenience. In principle the same could be done by:

z2 = sinus2d(np.linspace(0,2*np.pi,100)[:,None], np.linspace(0,2*np.pi,100)[None,:])

but there you need to be aware of your dimensions (suppose you have more than two ...) and the right broadcasting. np.meshgrid does all of this for you.

Also meshgrid allows you to delete coordinates together with the data if you, for example, want to do an interpolation but exclude certain values:

condition = z>0.6
z_new = z[condition] # This will make your array 1D

so how would you do the interpolation now? You can give x and y to an interpolation function like scipy.interpolate.interp2d so you need a way to know which coordinates were deleted:

x_new = xx[condition]
y_new = yy[condition]

and then you can still interpolate with the "right" coordinates (try it without the meshgrid and you will have a lot of extra code):

from scipy.interpolate import interp2d
interpolated = interp2d(x_new, y_new, z_new)

and the original meshgrid allows you to get the interpolation on the original grid again:

interpolated_grid = interpolated(xx[0], yy[:, 0]).reshape(xx.shape)

These are just some examples where I used the meshgrid there might be a lot more.

How to comment out particular lines in a shell script

You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):

:10,20 s/^/#

with 10 and 20 being the start and end line numbers of the lines you want to comment out

and to undo when you are complete:

:10,20 s/^#//

Regex to check if valid URL that ends in .jpg, .png, or .gif

Actually.

Why are you checking the URL? That's no guarantee what you're going to get is an image, and no guarantee that the things you're rejecting aren't images. Try performing a HEAD request on it, and see what content-type it actually is.

select2 - hiding the search box

I like to do this dynamically depending on the number of options in the select; to hide the search for selects with 10 or fewer results, I do:

$fewResults = $("select>option:nth-child(11)").closest("select");
$fewResults.select2();
$('select').not($fewResults).select2({ minimumResultsForSearch : -1 });

Call fragment from fragment

In MainActivity

private static android.support.v4.app.FragmentManager fragmentManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);                     

    fragmentManager = getSupportFragmentManager();                                                                 


    }

public void secondFragment() {

    fragmentManager
            .beginTransaction()
            .setCustomAnimations(R.anim.right_enter, R.anim.left_out)
            .replace(R.id.frameContainer, new secondFragment(), "secondFragmentTag").addToBackStack(null)
            .commit();
}

In FirstFragment call SecondFrgment Like this:

new MainActivity().secondFragment();

Confirm postback OnClientClick button ASP.NET

You can put the above answers into one line like this. And you don't need to write the function.

    <asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
         OnClick="BtnUserDelete_Click" meta:resourcekey="BtnUserDeleteResource1"
OnClientClick="if ( !confirm('Are you sure you want to delete this user?')) return false;"  />

Java 8 Iterable.forEach() vs foreach loop

When reading this question one can get the impression, that Iterable#forEach in combination with lambda expressions is a shortcut/replacement for writing a traditional for-each loop. This is simply not true. This code from the OP:

joins.forEach(join -> mIrc.join(mSession, join));

is not intended as a shortcut for writing

for (String join : joins) {
    mIrc.join(mSession, join);
}

and should certainly not be used in this way. Instead it is intended as a shortcut (although it is not exactly the same) for writing

joins.forEach(new Consumer<T>() {
    @Override
    public void accept(T join) {
        mIrc.join(mSession, join);
    }
});

And it is as a replacement for the following Java 7 code:

final Consumer<T> c = new Consumer<T>() {
    @Override
    public void accept(T join) {
        mIrc.join(mSession, join);
    }
};
for (T t : joins) {
    c.accept(t);
}

Replacing the body of a loop with a functional interface, as in the examples above, makes your code more explicit: You are saying that (1) the body of the loop does not affect the surrounding code and control flow, and (2) the body of the loop may be replaced with a different implementation of the function, without affecting the surrounding code. Not being able to access non final variables of the outer scope is not a deficit of functions/lambdas, it is a feature that distinguishes the semantics of Iterable#forEach from the semantics of a traditional for-each loop. Once one gets used to the syntax of Iterable#forEach, it makes the code more readable, because you immediately get this additional information about the code.

Traditional for-each loops will certainly stay good practice (to avoid the overused term "best practice") in Java. But this doesn't mean, that Iterable#forEach should be considered bad practice or bad style. It is always good practice, to use the right tool for doing the job, and this includes mixing traditional for-each loops with Iterable#forEach, where it makes sense.

Since the downsides of Iterable#forEach have already been discussed in this thread, here are some reasons, why you might probably want to use Iterable#forEach:

  • To make your code more explicit: As described above, Iterable#forEach can make your code more explicit and readable in some situations.

  • To make your code more extensible and maintainable: Using a function as the body of a loop allows you to replace this function with different implementations (see Strategy Pattern). You could e.g. easily replace the lambda expression with a method call, that may be overwritten by sub-classes:

    joins.forEach(getJoinStrategy());
    

    Then you could provide default strategies using an enum, that implements the functional interface. This not only makes your code more extensible, it also increases maintainability because it decouples the loop implementation from the loop declaration.

  • To make your code more debuggable: Seperating the loop implementation from the declaration can also make debugging more easy, because you could have a specialized debug implementation, that prints out debug messages, without the need to clutter your main code with if(DEBUG)System.out.println(). The debug implementation could e.g. be a delegate, that decorates the actual function implementation.

  • To optimize performance-critical code: Contrary to some of the assertions in this thread, Iterable#forEach does already provide better performance than a traditional for-each loop, at least when using ArrayList and running Hotspot in "-client" mode. While this performance boost is small and negligible for most use cases, there are situations, where this extra performance can make a difference. E.g. library maintainers will certainly want to evaluate, if some of their existing loop implementations should be replaced with Iterable#forEach.

    To back this statement up with facts, I have done some micro-benchmarks with Caliper. Here is the test code (latest Caliper from git is needed):

    @VmOptions("-server")
    public class Java8IterationBenchmarks {
    
        public static class TestObject {
            public int result;
        }
    
        public @Param({"100", "10000"}) int elementCount;
    
        ArrayList<TestObject> list;
        TestObject[] array;
    
        @BeforeExperiment
        public void setup(){
            list = new ArrayList<>(elementCount);
            for (int i = 0; i < elementCount; i++) {
                list.add(new TestObject());
            }
            array = list.toArray(new TestObject[list.size()]);
        }
    
        @Benchmark
        public void timeTraditionalForEach(int reps){
            for (int i = 0; i < reps; i++) {
                for (TestObject t : list) {
                    t.result++;
                }
            }
            return;
        }
    
        @Benchmark
        public void timeForEachAnonymousClass(int reps){
            for (int i = 0; i < reps; i++) {
                list.forEach(new Consumer<TestObject>() {
                    @Override
                    public void accept(TestObject t) {
                        t.result++;
                    }
                });
            }
            return;
        }
    
        @Benchmark
        public void timeForEachLambda(int reps){
            for (int i = 0; i < reps; i++) {
                list.forEach(t -> t.result++);
            }
            return;
        }
    
        @Benchmark
        public void timeForEachOverArray(int reps){
            for (int i = 0; i < reps; i++) {
                for (TestObject t : array) {
                    t.result++;
                }
            }
        }
    }
    

    And here are the results:

    When running with "-client", Iterable#forEach outperforms the traditional for loop over an ArrayList, but is still slower than directly iterating over an array. When running with "-server", the performance of all approaches is about the same.

  • To provide optional support for parallel execution: It has already been said here, that the possibility to execute the functional interface of Iterable#forEach in parallel using streams, is certainly an important aspect. Since Collection#parallelStream() does not guarantee, that the loop is actually executed in parallel, one must consider this an optional feature. By iterating over your list with list.parallelStream().forEach(...);, you explicitly say: This loop supports parallel execution, but it does not depend on it. Again, this is a feature and not a deficit!

    By moving the decision for parallel execution away from your actual loop implementation, you allow optional optimization of your code, without affecting the code itself, which is a good thing. Also, if the default parallel stream implementation does not fit your needs, no one is preventing you from providing your own implementation. You could e.g. provide an optimized collection depending on the underlying operating system, on the size of the collection, on the number of cores, and on some preference settings:

    public abstract class MyOptimizedCollection<E> implements Collection<E>{
        private enum OperatingSystem{
            LINUX, WINDOWS, ANDROID
        }
        private OperatingSystem operatingSystem = OperatingSystem.WINDOWS;
        private int numberOfCores = Runtime.getRuntime().availableProcessors();
        private Collection<E> delegate;
    
        @Override
        public Stream<E> parallelStream() {
            if (!System.getProperty("parallelSupport").equals("true")) {
                return this.delegate.stream();
            }
            switch (operatingSystem) {
                case WINDOWS:
                    if (numberOfCores > 3 && delegate.size() > 10000) {
                        return this.delegate.parallelStream();
                    }else{
                        return this.delegate.stream();
                    }
                case LINUX:
                    return SomeVerySpecialStreamImplementation.stream(this.delegate.spliterator());
                case ANDROID:
                default:
                    return this.delegate.stream();
            }
        }
    }
    

    The nice thing here is, that your loop implementation doesn't need to know or care about these details.

How to get current user, and how to use User class in MVC5?

If you want the ApplicationUser object in one line of code (if you have the latest ASP.NET Identity installed), try:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

You'll need the following using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

'python' is not recognized as an internal or external command

Option 1 : Select on add environment var during installation Option 2 : Go to C:\Users-> AppData (hidden file) -> Local\Programs\Python\Python38-32(depends on version installed)\Scripts Copy path and add to env vars path.

For me this path worked : C:\Users\Username\AppData\Local\Programs\Python\Python38-32\Scripts

What is use of c_str function In c++

It's used to make std::string interoperable with C code that requires a null terminated char*.

Git: How configure KDiff3 as merge tool and diff tool

Well, the problem is that Git can't find KDiff3 in the %PATH%.

In a typical Unix installation all executables reside in several well-known locations (/bin/, /usr/bin/, /usr/local/bin/, etc.), and one can invoke a program by simply typing its name in a shell processor (e.g. cmd.exe :) ).

In Microsoft Windows, programs are usually installed in dedicated paths so you can't simply type kdiff3 in a cmd session and get KDiff3 running.

The hard solution: you should tell Git where to find KDiff3 by specifying the full path to kdiff3.exe. Unfortunately, Git doesn't like spaces in the path specification in its config, so the last time I needed this, I ended up with those ancient "C:\Progra~1...\kdiff3.exe" as if it was late 1990s :)

The simple solution: Edit your computer settings and include the directory with kdiff3.exe in %PATH%. Then test if you can invoke it from cmd.exe by its name and then run Git.

How do you add an image?

The other option to try is a straightforward

<img width="100" height="100" src="/root/Image/image.jpeg" class="CalloutRightPhoto"/>

i.e. without {} but instead giving the direct image path

Row numbers in query result using Microsoft Access

I might be late. Simply add a new field ID in the table with type AutoNumber. This will generate unique IDs and can utilize in Access too

What is the meaning of <> in mysql query?

<> means not equal to, != also means not equal to.

Documentation

Django MEDIA_URL and MEDIA_ROOT

Following the steps mentioned above for =>3.0 for Debug mode

urlpatterns = [
...
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And also the part that caught me out, the above static URL only worked in my main project urls.py file. I was first attempting to add to my app, and wondering why I couldn't see the images.

Lastly make sure you set the following:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Bootstrap4 adding scrollbar to div

Use the overflow-y: scroll property on the element that contains the elements.

The overflow-y property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.

Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:

<ul class="nav nav-pills nav-stacked" style="height: 250px; overflow-y: scroll;">
  <li class="nav-item">
    <a class="nav-link active" href="#">Active</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" href="#">Disabled</a>
  </li>
</ul>

Automatic exit from Bash shell script on error

One idiom is:

cd some_dir && ./configure --some-flags && make && make install

I realize that can get long, but for larger scripts you could break it into logical functions.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

As already explained in other answers, when in Private Browsing mode Safari will always throw this exception when trying to save data with localStorage.setItem() .

To fix this I wrote a fake localStorage that mimics localStorage, both methods and events.

Fake localStorage: https://gist.github.com/engelfrost/fd707819658f72b42f55

This is probably not a good general solution to the problem. This was a good solution for my scenario, where the alternative would be major re-writes to an already existing application.

How to disable submit button once it has been clicked?

function xxxx() {
// submit or validate here , disable after that using below
  document.getElementById('buttonId').disabled = 'disabled';
  document.getElementById('buttonId').disabled = '';
}

How to convert UTF-8 byte[] to string?

hier is a result where you didnt have to bother with encoding. I used it in my network class and send binary objects as string with it.

        public static byte[] String2ByteArray(string str)
        {
            char[] chars = str.ToArray();
            byte[] bytes = new byte[chars.Length * 2];

            for (int i = 0; i < chars.Length; i++)
                Array.Copy(BitConverter.GetBytes(chars[i]), 0, bytes, i * 2, 2);

            return bytes;
        }

        public static string ByteArray2String(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / 2];

            for (int i = 0; i < chars.Length; i++)
                chars[i] = BitConverter.ToChar(bytes, i * 2);

            return new string(chars);
        }

How to disable scrolling in UITableView table when the content fits on the screen

I think you want to set

tableView.alwaysBounceVertical = NO;

Move the most recent commit(s) to a new branch with Git

Simplest way to do this:

1. Rename master branch to your newbranch (assuming you are on master branch):

git branch -m newbranch

2. Create master branch from the commit that you wish:

git checkout -b master <seven_char_commit_id>

e.g. git checkout -b master a34bc22