Programs & Examples On #Magnolia

Magnolia is an open source Java- and JCR-based content management system, targeted at the enterprise.

MySQL Server has gone away when importing large sql file

I am doing some large calculations which involves the mysql connection to stay long time and with heavy data. i was facing this "Mysql go away issue". So i tried t optimize the queries but that doen't helped me then i increased the mysql variables limit which is set to a lower value by default.

wait_timeout max_allowed_packet

To the limit what ever suits to you it should be the Any Number * 1024(Bytes). you can login to terminal using 'mysql -u username - p' command and can check and change for these variable limits.

Prevent text selection after double click

For those looking for a solution for Angular 2+.

You can use the mousedown output of the table cell.

<td *ngFor="..."
    (mousedown)="onMouseDown($event)"
    (dblclick) ="onDblClick($event)">
  ...
</td>

And prevent if the detail > 1.

public onMouseDown(mouseEvent: MouseEvent) {
  // prevent text selection for dbl clicks.
  if (mouseEvent.detail > 1) mouseEvent.preventDefault();
}

public onDblClick(mouseEvent: MouseEvent) {
 // todo: do what you really want to do ...
}

The dblclick output continues to work as expected.

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

AWK: Access captured group from line pattern

I struggled a bit with coming up with a bash function that wraps Peter Tillemans' answer but here's what I came up with:

function regex { perl -n -e "/$1/ && printf \"%s\n\", "'$1' }

I found this worked better than opsb's awk-based bash function for the following regular expression argument, because I do not want the "ms" to be printed.

'([0-9]*)ms$'

Is there an equivalent of lsusb for OS X

On Mac OS X, the Xcode developer suite includes the USB Proper.app application. This is found in /Developer/Applications/Utilities/. USB Prober will allow you to examine the device and interface descriptors.

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

How can I do an asc and desc sort using underscore.js?

Underscore Mixins

Extending on @emil_lundberg's answer, you can also write a "mixin" if you're using Underscore to make a custom function for sorting if it's a kind of sorting you might repeat in an application somewhere.

For example, maybe you have a controller or view sorting results with sort order of "ASC" or "DESC", and you want to toggle between that sort, you could do something like this:

Mixin.js

_.mixin({
    sortByOrder: function(stooges, prop, order) {
      if (String(order) === "desc") {
          return _.sortBy(stooges, prop).reverse();
      } else if (String(order) === "asc") {
          return _.sortBy(stooges, prop);
      } else {
          return stooges;
      }
    }
})

Usage Example

var sort_order = "asc";
var stooges = [
  {name: 'moe', age: 40}, 
  {name: 'larry', age: 50}, 
  {name: 'curly', age: 60},
  {name: 'July', age: 35},
  {name: 'mel', age: 38}
 ];

_.mixin({
    sortByOrder: function(stooges, prop, order) {
    if (String(order) === "desc") {
        return _.sortBy(stooges, prop).reverse();
    } else if (String(order) === "asc") {
        return _.sortBy(stooges, prop);
    } else {
        return stooges;
    }
  }
})


// find elements
var banner = $("#banner-message");
var sort_name_btn = $("button.sort-name");
var sort_age_btn = $("button.sort-age");

function showSortedResults(results, sort_order, prop) {
    banner.empty();
    banner.append("<p>Sorting: " + prop + ', ' + sort_order + "</p><hr>")
  _.each(results, function(r) {
    banner.append('<li>' + r.name + ' is '+ r.age + ' years old.</li>');
  }) 
}

// handle click and add class
sort_name_btn.on("click", function() {
  sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'name', sort_order);
  showSortedResults(sortedResults, sort_order, 'name');
})

sort_age_btn.on('click', function() {
    sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'age', sort_order);
  showSortedResults(sortedResults, sort_order, 'age');
})

Here's a JSFiddle demonstrating this: JSFiddle for SortBy Mixin

Enable UTF-8 encoding for JavaScript

I think you just need to make

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

Before calling your .js files or code

Duplicate Symbols for Architecture arm64

to solve this problem go to Build phases and search about duplicate file like (facebookSDK , unityads ) and delete (extension file.o) then build again .

How can I remove a trailing newline?

s = s.rstrip()

will remove all newlines at the end of the string s. The assignment is needed because rstrip returns a new string instead of modifying the original string.

Convert to date format dd/mm/yyyy

If your date is in the format of a string use the explode function

    array explode ( string $delimiter , string $string [, int $limit ] )
//In the case of your code

$length = strrpos($oldDate," ");
$newDate = explode( "-" , substr($oldDate,$length));
$output = $newDate[2]."/".$newDate[1]."/".$newDate[0];

Hope the above works now

Splitting a dataframe string column into multiple different columns

Is this what you are trying to do?

# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)

#  Split into individual elements by the '.' character
#  Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )

#  We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )

#  Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
#  V1 V2  V3  V4
#1  F US CLE V13
#2  F US CA6 U13
#3  F US CA6 U13
#4  F US CA6 U13
#5  F US CA6 U13
#6  F US CA6 U13

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Automating running command on Linux from Windows using PuTTY

You can do both tasks (the upload and the command execution) using WinSCP. Use WinSCP script like:

option batch abort
option confirm off
open your_session
put %1%
call script.sh
exit

Reference for the call command:
https://winscp.net/eng/docs/scriptcommand_call

Reference for the %1% syntax:
https://winscp.net/eng/docs/scripting#syntax

You can then run the script like:

winscp.exe /console /script=script_path\upload.txt /parameter file_to_upload.dat

Actually, you can put a shortcut to the above command to the Windows Explorer's Send To menu, so that you can then just right-click any file and go to the Send To > Upload using WinSCP and Execute Remote Command (=name of the shortcut).

For that, go to the folder %USERPROFILE%\SendTo and create a shortcut with the following target:

winscp_path\winscp.exe /console /script=script_path\upload.txt /parameter %1

See Creating entry in Explorer's "Send To" menu.

input type="submit" Vs button tag are they interchangeable?

The <input type="button"> is just a button and won't do anything by itself. The <input type="submit">, when inside a form element, will submit the form when clicked.

Another useful 'special' button is the <input type="reset"> that will clear the form.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

What is declarative programming?

Loosely:

Declarative programming tends towards:-

  • Sets of declarations, or declarative statements, each of which has meaning (often in the problem domain) and may be understood independently and in isolation.

Imperative programming tends towards:-

  • Sequences of commands, each of which perform some action; but which may or may not have meaning in the problem domain.

As a result, an imperative style helps the reader to understand the mechanics of what the system is actually doing, but may give little insight into the problem that it is intended to solve. On the other hand, a declarative style helps the reader to understand the problem domain and the approach that the system takes towards the solution of the problem, but is less informative on the matter of mechanics.

Real programs (even ones written in languages that favor the ends of the spectrum, such as ProLog or C) tend to have both styles present to various degrees at various points, to satisfy the varying complexities and communication needs of the piece. One style is not superior to the other; they just serve different purposes, and, as with many things in life, moderation is key.

Color theme for VS Code integrated terminal

You can actually modify your user settings and edit each colour individually by adding the following to the user settings.

  1. Open user settings (ctrl + ,)
  2. Search for workbench and select Edit in settings.json under Color Customizations
"workbench.colorCustomizations" : {
    "terminal.foreground" : "#00FD61",
    "terminal.background" : "#383737"
}

For more on what colors you can edit you can find out here.

HTML combo box with option to type an entry

in HTML, you do this backwards: You define a text input:

<input type="text" list="browsers" />

and attach a datalist to it. (note the list attribute of the input).

<datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist> 

Creating stored procedure and SQLite?

Answer: NO

Here's Why ... I think a key reason for having stored procs in a database is that you're executing SP code in the same process as the SQL engine. This makes sense for database engines designed to work as a network connected service but the imperative for SQLite is much less given that it runs as a DLL in your application process rather than in a separate SQL engine process. So it makes more sense to implement all your business logic including what would have been SP code in the host language.

You can however extend SQLite with your own user defined functions in the host language (PHP, Python, Perl, C#, Javascript, Ruby etc). You can then use these custom functions as part of any SQLite select/update/insert/delete. I've done this in C# using DevArt's SQLite to implement password hashing.

MySQL select query with multiple conditions

You have conditions that are mutually exclusive - if meta_key is 'first_name', it can't also be 'yearofpassing'. Most likely you need your AND's to be OR's:

$result = mysql_query("SELECT user_id FROM wp_usermeta 
WHERE (meta_key = 'first_name' AND meta_value = '$us_name') 
OR (meta_key = 'yearofpassing' AND meta_value = '$us_yearselect') 
OR (meta_key = 'u_city' AND meta_value = '$us_reg') 
OR (meta_key = 'us_course' AND meta_value = '$us_course')")

Is Google Play Store supported in avd emulators?

There is no google play store in avd emulator. But you can install it manually.

  1. Install Google APIs System Image, so you will have google services already (without play store)

  2. Create AVD based on Google APIs image

  3. Download smallest archive from http://opengapps.org/ and extract Phonesky.apk from it

  4. Push Phonesky.apk to /system/priv-app/ on avd.

  5. Restart avd. Google play should be there.

Recently I've just tried to do it by myself and you can find detailed tutorial on my blog: http://linuxoidchannel.blogspot.com/2017/01/how-to-install-google-play-store-on.html

Load json from local file with http.get() in angular 2

You have to change

loadNavItems() {
        this.navItems = this.http.get("../data/navItems.json");
        console.log(this.navItems);
    }

for

loadNavItems() {
        this.navItems = this.http.get("../data/navItems.json")
                        .map(res => res.json())
                        .do(data => console.log(data));
                        //This is optional, you can remove the last line 
                        // if you don't want to log loaded json in 
                        // console.
    }

Because this.http.get returns an Observable<Response> and you don't want the response, you want its content.

The console.log shows you an observable, which is correct because navItems contains an Observable<Response>.

In order to get data properly in your template, you should use async pipe.

<app-nav-item-comp *ngFor="let item of navItems | async" [item]="item"></app-nav-item-comp>

This should work well, for more informations, please refer to HTTP Client documentation

How do I solve this error, "error while trying to deserialize parameter"

I found the actual solution...There is a problem in invoking your service from the client.. check the following things.

  1. Make sure all [datacontract], [datamember] attribute are placed properly i.e. make sure WCF is error free

  2. The WCF client, either web.config or any window app config, make sure config entries are properly pointing to the right ones.. binding info, url of the service..etc..etc

Then above problem : tempuri issue is resolved.. it has nothing to do with namespace.. though you are sure you lived with default,

Hope it saves your number of hours!

Flask SQLAlchemy query, specify column names

You can use Query.values, Query.values

session.query(SomeModel).values('id', 'user')

PHP regular expressions: No ending delimiter '^' found in

Your regex pattern needs to be in delimiters:

$numpattern="/^([0-9]+)$/";

How to convert a list into data table

Just add this function and call it, it will convert List to DataTable.

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}

libstdc++.so.6: cannot open shared object file: No such file or directory

/usr/local/cilk/bin/../lib32/pinbin is dynamically linked to a library libstdc++.so.6 which is not present anymore. You need to recompile Cilk

What is the proper #include for the function 'sleep()'?

What is the proper #include for the function 'sleep()'?

sleep() isn't Standard C, but POSIX so it should be:

#include <unistd.h>

Drawing a simple line graph in Java

There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV) file with the XChart library. Disclaimer: I'm the lead developer of the project.

In this example, two text files exist in ./CSV/CSVChartRows/. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1 contains x, y, and error bar data, whereas series2 contains just x and y, data.

series1.csv

1,12,1.4
2,34,1.12
3,56,1.21
4,47,1.5

series2.csv

1,56
2,34
3,12
4,26

Source Code

public class CSVChartRows {

  public static void main(String[] args) throws Exception {

    // import chart from a folder containing CSV files
    XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);

    // Show it
    new SwingWrapper(chart).displayChart();
  }
}

Resulting Plot

enter image description here

How to replace negative numbers in Pandas Data Frame by zero

Another succinct way of doing this is pandas.DataFrame.clip.

For example:

import pandas as pd

In [20]: df = pd.DataFrame({'a': [-1, 100, -2]})

In [21]: df
Out[21]: 
     a
0   -1
1  100
2   -2

In [22]: df.clip(lower=0)
Out[22]: 
     a
0    0
1  100
2    0

There's also df.clip_lower(0).

How to close a Tkinter window by pressing a Button?

You can associate directly the function object window.destroy to the command attribute of your button:

button = Button (frame, text="Good-bye.", command=window.destroy)

This way you will not need the function close_window to close the window for you.

How to set a default Value of a UIPickerView

You have to send - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated to the picker view before it appears. The documentation states that the method selectedRowInComp... will give -1, thus it is possible that the picker view is in a state with no selected row. It turns out to be in that state when created.

How to add a column in TSQL after a specific column?

You have to rebuild the table. Luckily, the order of the columns doesn't matter at all!

Watch as I magically reorder your columns:

SELECT ID, Newfield, FieldA, FieldB FROM MyTable

Also this has been asked about a bazillion times before.

Shuffle DataFrame rows

AFAIK the simplest solution is:

df_shuffled = df.reindex(np.random.permutation(df.index))

How can I get form data with JavaScript/jQuery?

Here's my version in vanilla JS (tested on Chrome)

works with:

  • name="input"
  • name="form[name]" (creates an object)
  • name="checkbox[]" (creates an object with an array)
  • name="form[checkbox][]" (creates an array)
  • name="form[select][name]" (creates an object with an object containing only the selected value)
/**
 * Get the values from a form
 * @param formId ( ID without the # )
 * @returns {object}
 */
function getFormValues( formId )
{
    let postData = {};
    let form = document.forms[formId];
    let formData = new FormData( form );

    for ( const value of formData.entries() )
    {
        let container = postData;
        let key = value[0];
        let arrayKeys = key.match( /\[[\w\-]*\]/g ); // Check for any arrays

        if ( arrayKeys !== null )
        {
            arrayKeys.unshift( key.substr( 0, key.search( /\[/ ) ) );  // prepend the first key to the list
            for ( let i = 0, count = arrayKeys.length, lastRun = count - 1; i < count; i++ )
            {
                let _key = arrayKeys[i];
                _key = _key.replace( "[", '' ).replace( "]", '' ); // Remove the brackets []
                if ( _key === '' )
                {
                    if ( ! Array.isArray( container ) )
                    {
                        container = [];
                    }

                    _key = container.length;
                }

                if ( ! (_key in container) ) // Create an object for the key if it doesn't exist
                {
                    if ( i !== lastRun && arrayKeys[i + 1] === '[]' )
                    {
                        container[_key] = [];
                    }
                    else
                    {
                        container[_key] = {};
                    }
                }

                if ( i !== lastRun ) // Until we're the last item, swap container with it's child
                {
                    container = container[_key];
                }

                key = _key;
            }
        }
        container[key] = value[1]; // finally assign the value
    }

    return postData;
}

How to detect a textbox's content has changed

Use closures to remember what was the text in the checkbox before the key stroke and check whether this has changed.

Yep. You don't have to use closures necessarily, but you will need to remember the old value and compare it to the new.

However! This still won't catch every change, because there a ways of editing textbox content that do not involve any keypress. For example selecting a range of text then right-click-cut. Or dragging it. Or dropping text from another app into the textbox. Or changing a word via the browser's spell-check. Or...

So if you must detect every change, you have to poll for it. You could window.setInterval to check the field against its previous value every (say) second. You could also wire onkeyup to the same function so that changes that are caused by keypresses are reflected quicker.

Cumbersome? Yes. But it's that or just do it the normal HTML onchange way and don't try to instant-update.

How to pass json POST data to Web API method as an object?

EDIT : 31/10/2017

The same code/approach will work for Asp.Net Core 2.0 as well. The major difference is, In asp.net core, both web api controllers and Mvc controllers are merged together to single controller model. So your return type might be IActionResult or one of it's implementation (Ex :OkObjectResult)


Use

contentType:"application/json"

You need to use JSON.stringify method to convert it to JSON string when you send it,

And the model binder will bind the json data to your class object.

The below code will work fine (tested)

$(function () {
    var customer = {contact_name :"Scott",company_name:"HP"};
    $.ajax({
        type: "POST",
        data :JSON.stringify(customer),
        url: "api/Customer",
        contentType: "application/json"
    });
});

Result

enter image description here

contentType property tells the server that we are sending the data in JSON format. Since we sent a JSON data structure,model binding will happen properly.

If you inspect the ajax request's headers, you can see that the Content-Type value is set as application/json.

If you do not specify contentType explicitly, It will use the default content type which is application/x-www-form-urlencoded;


Edit on Nov 2015 to address other possible issues raised in comments

Posting a complex object

Let's say you have a complex view model class as your web api action method parameter like this

public class CreateUserViewModel
{
   public int Id {set;get;}
   public string Name {set;get;}  
   public List<TagViewModel> Tags {set;get;}
}
public class TagViewModel
{
  public int Id {set;get;}
  public string Code {set;get;}
}

and your web api end point is like

public class ProductController : Controller
{
    [HttpPost]
    public CreateUserViewModel Save([FromBody] CreateUserViewModel m)
    {
        // I am just returning the posted model as it is. 
        // You may do other stuff and return different response.
        // Ex : missileService.LaunchMissile(m);
        return m;
    }
}

At the time of this writing, ASP.NET MVC 6 is the latest stable version and in MVC6, Both Web api controllers and MVC controllers are inheriting from Microsoft.AspNet.Mvc.Controller base class.

To send data to the method from client side, the below code should work fine

//Build an object which matches the structure of our view model class
var model = {
    Name: "Shyju",
    Id: 123,
    Tags: [{ Id: 12, Code: "C" }, { Id: 33, Code: "Swift" }]
};

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: "../product/save",
    contentType: "application/json"
}).done(function(res) {       
    console.log('res', res);
    // Do something with the result :)
});

Model binding works for some properties, but not all ! Why ?

If you do not decorate the web api method parameter with [FromBody] attribute

[HttpPost]
public CreateUserViewModel Save(CreateUserViewModel m)
{
    return m;
}

And send the model(raw javascript object, not in JSON format) without specifying the contentType property value

$.ajax({
    type: "POST",
    data: model,
    url: "../product/save"
}).done(function (res) {
     console.log('res', res);
});

Model binding will work for the flat properties on the model, not the properties where the type is complex/another type. In our case, Id and Name properties will be properly bound to the parameter m, But the Tags property will be an empty list.

The same problem will occur if you are using the short version, $.post which will use the default Content-Type when sending the request.

$.post("../product/save", model, function (res) {
    //res contains the markup returned by the partial view
    console.log('res', res);
});

How to install the Raspberry Pi cross compiler on my Linux host machine?

I'm gonna try to write this as a tutorial for you so it becomes easy to follow.

NOTE: This tutorial only works for older raspbian images. For the newer Raspbian based on Debian Buster see the following how-to in this thread: https://stackoverflow.com/a/58559140/869402

Pre-requirements

Before you start you need to make sure the following is installed:

apt-get install git rsync cmake libc6-i386 lib32z1 lib32stdc++6

Let's cross compile a Pie!

Start with making a folder in your home directory called raspberrypi.

Go in to this folder and pull down the ENTIRE tools folder you mentioned above:

git clone git://github.com/raspberrypi/tools.git

You wanted to use the following of the 3 ones, gcc-linaro-arm-linux-gnueabihf-raspbian, if I did not read wrong.

Go into your home directory and add:

export PATH=$PATH:$HOME/raspberrypi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin

to the end of the file named ~/.bashrc

Now you can either log out and log back in (i.e. restart your terminal session), or run . ~/.bashrc in your terminal to pick up the PATH addition in your current terminal session.

Now, verify that you can access the compiler arm-linux-gnueabihf-gcc -v. You should get something like this:

Using built-in specs.
COLLECT_GCC=arm-linux-gnueabihf-gcc
COLLECT_LTO_WRAPPER=/home/tudhalyas/raspberrypi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/../libexec/gcc/arm-linux-gnueabihf/4.7.2/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: /cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-raspbian-linux/.b
 uild/src/gcc-linaro-4.7-2012.08/configure --build=i686-build_pc-linux-gnu --host=i686-build_pc-
 linux-gnu --target=arm-linux-gnueabihf --prefix=/cbuild/slaves/oort61/crosstool-ng/builds/arm-l
 inux-gnueabihf-raspbian-linux/install --with-sysroot=/cbuild/slaves/oort61/crosstool-ng/builds/
 arm-linux-gnueabihf-raspbian-linux/install/arm-linux-gnueabihf/libc --enable-languages=c,c++,fo
 rtran --disable-multilib --with-arch=armv6 --with-tune=arm1176jz-s --with-fpu=vfp --with-float=
 hard --with-pkgversion='crosstool-NG linaro-1.13.1+bzr2458 - Linaro GCC 2012.08' --with-bugurl=
 https://bugs.launchpad.net/gcc-linaro --enable-__cxa_atexit --enable-libmudflap --enable-libgom
 p --enable-libssp --with-gmp=/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-rasp
 bian-linux/.build/arm-linux-gnueabihf/build/static --with-mpfr=/cbuild/slaves/oort61/crosstool-
 ng/builds/arm-linux-gnueabihf-raspbian-linux/.build/arm-linux-gnueabihf/build/static --with-mpc
 =/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-raspbian-linux/.build/arm-linux-
 gnueabihf/build/static --with-ppl=/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf
 -raspbian-linux/.build/arm-linux-gnueabihf/build/static --with-cloog=/cbuild/slaves/oort61/cros
 stool-ng/builds/arm-linux-gnueabihf-raspbian-linux/.build/arm-linux-gnueabihf/build/static --wi
 th-libelf=/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-raspbian-linux/.build/a
 rm-linux-gnueabihf/build/static --with-host-libstdcxx='-L/cbuild/slaves/oort61/crosstool-ng/bui
 lds/arm-linux-gnueabihf-raspbian-linux/.build/arm-linux-gnueabihf/build/static/lib -lpwl' --ena
 ble-threads=posix --disable-libstdcxx-pch --enable-linker-build-id --enable-plugin --enable-gol
 d --with-local-prefix=/cbuild/slaves/oort61/crosstool-ng/builds/arm-linux-gnueabihf-raspbian-li
 nux/install/arm-linux-gnueabihf/libc --enable-c99 --enable-long-long
Thread model: posix
gcc version 4.7.2 20120731 (prerelease) (crosstool-NG linaro-1.13.1+bzr2458 - Linaro GCC 2012.08
 )

But hey! I did that and the libs still don't work!

We're not done yet! So far, we've only done the basics.

In your raspberrypi folder, make a folder called rootfs.

Now you need to copy the entire /liband /usr directory to this newly created folder. I usually bring the rpi image up and copy it via rsync:

rsync -rl --delete-after --safe-links [email protected]:/{lib,usr} $HOME/raspberrypi/rootfs

where 192.168.1.PI is replaced by the IP of your Raspberry Pi.

Now, we need to write a cmake config file. Open ~/home/raspberrypi/pi.cmake in your favorite editor and insert the following:

SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_SYSTEM_VERSION 1)
SET(CMAKE_C_COMPILER $ENV{HOME}/raspberrypi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-gcc)
SET(CMAKE_CXX_COMPILER $ENV{HOME}/raspberrypi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-g++)
SET(CMAKE_FIND_ROOT_PATH $ENV{HOME}/raspberrypi/rootfs)
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

Now you should be able to compile your cmake programs simply by adding this extra flag: -D CMAKE_TOOLCHAIN_FILE=$HOME/raspberrypi/pi.cmake.

Using a cmake hello world example:

git clone https://github.com/jameskbride/cmake-hello-world.git 
cd cmake-hello-world
mkdir build
cd build
cmake -D CMAKE_TOOLCHAIN_FILE=$HOME/raspberrypi/pi.cmake ../
make
scp CMakeHelloWorld [email protected]:/home/pi/
ssh [email protected] ./CMakeHelloWorld

Calling Web API from MVC controller

Controller:

    public JsonResult GetProductsData()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:5136/api/");
            //HTTP GET
            var responseTask = client.GetAsync("product");
            responseTask.Wait();

            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<IList<product>>();
                readTask.Wait();

                var alldata = readTask.Result;

                var rsproduct = from x in alldata
                             select new[]
                             {
                             Convert.ToString(x.pid),
                             Convert.ToString(x.pname),
                             Convert.ToString(x.pprice),
                      };

                return Json(new
                {
                    aaData = rsproduct
                },
    JsonRequestBehavior.AllowGet);


            }
            else //web api sent error response 
            {
                //log response status here..

               var pro = Enumerable.Empty<product>();


                return Json(new
                {
                    aaData = pro
                },
    JsonRequestBehavior.AllowGet);


            }
        }
    }

    public JsonResult InupProduct(string id,string pname, string pprice)
    {
        try
        {

            product obj = new product
            {
                pid = Convert.ToInt32(id),
                pname = pname,
                pprice = Convert.ToDecimal(pprice)
            };



            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5136/api/product");


                if(id=="0")
                {
                    //insert........
                    //HTTP POST
                    var postTask = client.PostAsJsonAsync<product>("product", obj);
                    postTask.Wait();

                    var result = postTask.Result;

                    if (result.IsSuccessStatusCode)
                    {
                        return Json(1, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(0, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    //update........
                    //HTTP POST
                    var postTask = client.PutAsJsonAsync<product>("product", obj);
                    postTask.Wait();
                    var result = postTask.Result;
                    if (result.IsSuccessStatusCode)
                    {
                        return Json(1, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(0, JsonRequestBehavior.AllowGet);
                    }

                }




            }


            /*context.InUPProduct(Convert.ToInt32(id),pname,Convert.ToDecimal(pprice));

            return Json(1, JsonRequestBehavior.AllowGet);*/
        }
        catch (Exception ex)
        {
            return Json(0, JsonRequestBehavior.AllowGet);
        }

    }

    public JsonResult deleteRecord(int ID)
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5136/api/product");

                //HTTP DELETE
                var deleteTask = client.DeleteAsync("product/" + ID);
                deleteTask.Wait();

                var result = deleteTask.Result;
                if (result.IsSuccessStatusCode)
                {

                    return Json(1, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
            }



           /* var data = context.products.Where(x => x.pid == ID).FirstOrDefault();
            context.products.Remove(data);
            context.SaveChanges();
            return Json(1, JsonRequestBehavior.AllowGet);*/
        }
        catch (Exception ex)
        {
            return Json(0, JsonRequestBehavior.AllowGet);
        }
    }

Import Android volley to Android Studio

In the "build.gradle" for your app, (the app, not the project), add this:

dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.0'
}

HTML5 textarea placeholder not appearing

Delete all spaces and line breaks between <textarea> opening and closing </textarea> tags.

<textarea placeholder="YOUR TEXT"></textarea>  ///Correct one

<textarea placeholder="YOUR TEXT"> </textarea>  ///Bad one It's treats as a value so browser won't display the Placeholder value

<textarea placeholder="YOUR TEXT"> 
</textarea>  ///Bad one 

Batch Extract path and filename from a variable

@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Not really sure what you mean by no "function"

Obviously, change ECHO to SET to set the variables rather thon ECHOing them...

See for documentation for a full list.


ceztko's test case (for reference)

@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Comment : please see comments.

In Powershell what is the idiomatic way of converting a string to an int?

A quick true/false test of whether it will cast to [int]

[bool]($var -as [int] -is [int])

Using HTTPS with REST in Java

When you say "is there an easier way to... trust this cert", that's exactly what you're doing by adding the cert to your Java trust store. And this is very, very easy to do, and there's nothing you need to do within your client app to get that trust store recognized or utilized.

On your client machine, find where your cacerts file is (that's your default Java trust store, and is, by default, located at <java-home>/lib/security/certs/cacerts.

Then, type the following:

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to cacerts>

That will import the cert into your trust store, and after this, your client app will be able to connect to your Grizzly HTTPS server without issue.

If you don't want to import the cert into your default trust store -- i.e., you just want it to be available to this one client app, but not to anything else you run on your JVM on that machine -- then you can create a new trust store just for your app. Instead of passing keytool the path to the existing, default cacerts file, pass keytool the path to your new trust store file:

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to new trust store>

You'll be asked to set and verify a new password for the trust store file. Then, when you start your client app, start it with the following parameters:

java -Djavax.net.ssl.trustStore=<path to new trust store> -Djavax.net.ssl.trustStorePassword=<trust store password>

Easy cheesy, really.

Go build: "Cannot find package" (even though GOPATH is set)

If you have a valid $GOROOT and $GOPATH but are developing outside of them, you might get this error if the package (yours or someone else's) hasn't been downloaded.

If that's the case, try go get -d (-d flag prevents installation) to ensure the package is downloaded before you run, build or install.

Default Values to Stored Procedure in Oracle

Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:

EXEC TEST()

Share and enjoy.

Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:

CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
                                 Y IN NUMBER DEFAULT 1)
AS
  varX VARCHAR2(32767) := NVL(X, 'P');
  varY NUMBER          := NVL(Y, 1);
BEGIN
  DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;

Disable beep of Linux Bash on Windows 10

Uncommenting set bell-style none in /etc/inputrc and creating a .bash_profile with setterm -blength 0 didn't stop vim from beeping.

What worked for me was creating a .vimrc file in my home directory with set visualbell.

Source: https://linuxconfig.org/turn-off-beep-bell-on-linux-terminal

Add a column with a default value to an existing table in SQL Server

Beware when the column you are adding has a NOT NULL constraint, yet does not have a DEFAULT constraint (value). The ALTER TABLE statement will fail in that case if the table has any rows in it. The solution is to either remove the NOT NULL constraint from the new column, or provide a DEFAULT constraint for it.

Why use double indirection? or Why use pointers to pointers?

I have used double pointers today while I was programming something for work, so I can answer why we had to use them (it's the first time I actually had to use double pointers). We had to deal with real time encoding of frames contained in buffers which are members of some structures. In the encoder we had to use a pointer to one of those structures. The problem was that our pointer was being changed to point to other structures from another thread. In order to use the current structure in the encoder, I had to use a double pointer, in order to point to the pointer that was being modified in another thread. It wasn't obvious at first, at least for us, that we had to take this approach. A lot of address were printed in the process :)).

You SHOULD use double pointers when you work on pointers that are changed in other places of your application. You might also find double pointers to be a must when you deal with hardware that returns and address to you.

How to shutdown a Spring Boot Application in a correct way?

You can make the springboot application to write the PID into file and you can use the pid file to stop or restart or get the status using a bash script. To write the PID to a file, register a listener to SpringApplication using ApplicationPidFileWriter as shown below :

SpringApplication application = new SpringApplication(Application.class);
application.addListeners(new ApplicationPidFileWriter("./bin/app.pid"));
application.run();

Then write a bash script to run the spring boot application . Reference.

Now you can use the script to start,stop or restart.

Function overloading in Python: Missing

Oftentimes you see the suggestion use use keyword arguments, with default values, instead. Look into that.

css width: calc(100% -100px); alternative using jquery

I think this may be another way

    var width=  $('#elm').width();

    $('#element').css({ 'width': 'calc(100% - ' + width+ 'px)' });

How to scroll up or down the page to an anchor using jQuery?

Here is the solution that worked for me. This is a generic function which works for all of the a tags referring to a named a

$("a[href^=#]").on('click', function(event) { 
    event.preventDefault(); 
    var name = $(this).attr('href'); 
    var target = $('a[name="' + name.substring(1) + '"]'); 
    $('html,body').animate({ scrollTop: $(target).offset().top }, 'slow'); 
});

Note 1: Make sure that you use double quotes " in your html. If you use single quotes, change the above part of the code to var target = $("a[name='" + name.substring(1) + "']");

Note 2: In some cases, especially when you use the sticky bar from the bootstrap, the named a will hide beneath the navigation bar. In those cases (or any similar case), you can reduce the number of the pixels from your scroll to achieve the optimal location. For example: $('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow'); will take you to the target with 15 pixels left on the top.

How do I set cell value to Date and apply default Excel date format?

This code sample can be used to change date format. Here I want to change from yyyy-MM-dd to dd-MM-yyyy. Here pos is position of column.

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class Test{ 
public static void main( String[] args )
{
String input="D:\\somefolder\\somefile.xlsx";
String output="D:\\somefolder\\someoutfile.xlsx"
FileInputStream file = new FileInputStream(new File(input));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=5; // 5th column is date.
while(iterator.hasNext())
{
    row=iterator.next();

    cell=row.getCell(pos-1);
    //CellStyle cellStyle = wb.createCellStyle();
    XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
    CreationHelper createHelper = wb.getCreationHelper();
    cellStyle.setDataFormat(
        createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date d=null;
    try {
        d= sdf.parse(cell.getStringCellValue());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        d=null;
        e.printStackTrace();
        continue;
    }
    cell.setCellValue(d);
    cell.setCellStyle(cellStyle);
   }

file.close();
FileOutputStream outFile =new FileOutputStream(new File(output));
workbook.write(outFile);
workbook.close();
outFile.close();
}}

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Okay, this question was a year ago but I recently got this problem as well.

So what I did :

  1. Update tomcat 7 to tomcat 8.
  2. Update to the latest java (java 1.8.0_141).
  3. Update the JRE System Library in Project > Properties > Java Build Path. Make sure it has the latest version which in my case is jre1.8.0_141 (before it was the previous version jre1.8.0_111)

When I did the first two steps it still doesn't remove the error so the last step is important. It didn't automatically change the build path for jre.

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

UTF-8 all the way through

Unicode support in PHP is still a huge mess. While it's capable of converting an ISO8859 string (which it uses internally) to utf8, it lacks the capability to work with unicode strings natively, which means all the string processing functions will mangle and corrupt your strings. So you have to either use a separate library for proper utf8 support, or rewrite all the string handling functions yourself.

The easy part is just specifying the charset in HTTP headers and in the database and such, but none of that matters if your PHP code doesn't output valid UTF8. That's the hard part, and PHP gives you virtually no help there. (I think PHP6 is supposed to fix the worst of this, but that's still a while away)

What is the difference between include and require in Ruby?

From the Metaprogramming Ruby book,

The require() method is quite similar to load(), but it’s meant for a different purpose. You use load() to execute code, and you use require() to import libraries.

Converting a double to an int in Javascript without rounding

A trick to truncate that avoids a function call entirely is

var number = 2.9
var truncated = number - number % 1;
console.log(truncated); // 2 

To round a floating-point number to the nearest integer, use the addition/subtraction trick. This works for numbers with absolute value < 2 ^ 51.

var number = 2.9
var rounded = number + 6755399441055744.0 - 6755399441055744.0;  // (2^52 + 2^51)
console.log(rounded); // 3 

Note:

Halfway values are rounded to the nearest even using "round half to even" as the tie-breaking rule. Thus, for example, +23.5 becomes +24, as does +24.5. This variant of the round-to-nearest mode is also called bankers' rounding.

The magic number 6755399441055744.0 is explained in the stackoverflow post "A fast method to round a double to a 32-bit int explained".

_x000D_
_x000D_
// Round to whole integers using arithmetic operators
let trunc = (v) => v - v % 1;
let ceil  = (v) => trunc(v % 1 > 0 ? v + 1 : v);
let floor = (v) => trunc(v % 1 < 0 ? v - 1 : v);
let round = (v) => trunc(v < 0 ? v - 0.5 : v + 0.5);

let roundHalfEven = (v) => v + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)

console.log("number  floor   ceil  round  trunc");
var array = [1.5, 1.4, 1.0, -1.0, -1.4, -1.5];
array.forEach(x => {
    let f = x => (x).toString().padStart(6," ");
    console.log(`${f(x)} ${f(floor(x))} ${f(ceil(x))} ${f(round(x))} ${f(trunc(x))}`);  
});
_x000D_
_x000D_
_x000D_

Unable to show a Git tree in terminal

Keeping your commands short will make them easier to remember:

git log --graph --oneline

How to make a HTTP request using Ruby on Rails?

You can use Ruby's Net::HTTP class:

require 'net/http'

url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
  http.request(req)
}
puts res.body

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Thanks for the reply. I was using "mvn clean install" in the maven build configuration. we no need to use "mvn" command if running through eclipse.

After buiding the application using the command "clean install" , I got one more error -
"No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?"

I followed this link:- No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

now application building is fine in eclipse.

CertificateException: No name matching ssl.someUrl.de found

I created a method fixUntrustCertificate(), so when I am dealing with a domain that is not in trusted CAs you can invoke the method before the request. This code will gonna work after java1.4. This method applies for all hosts:

public void fixUntrustCertificate() throws KeyManagementException, NoSuchAlgorithmException{


        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }

            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // set the  allTrusting verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

How to do Base64 encoding in node.js?

The accepted answer previously contained new Buffer(), which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).

The Buffer constructor is deprecated according to the documentation.

Here is an example of a vulnerability that can result from using it in the ws library.

The code snippets should read:

console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));

After this answer was written, it has been updated and now matches this.

How to do paging in AngularJS?

I would like to add my solution that works with ngRepeat and filters that you use with it without using a $watch or a sliced array.

Your filter results will be paginated!

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

app.controller('myController', ['$scope', function($scope){
    $scope.list= ['a', 'b', 'c', 'd', 'e'];

    $scope.pagination = {
        currentPage: 1,
        numPerPage: 5,
        totalItems: 0
    };

    $scope.searchFilter = function(item) {
        //Your filter results will be paginated!
        //The pagination will work even with other filters involved
        //The total number of items in the result of your filter is accounted for
    };

    $scope.paginationFilter = function(item, index) {
        //Every time the filter is used it restarts the totalItems
        if(index === 0) 
            $scope.pagination.totalItems = 0;

        //This holds the totalItems after the filters are applied
        $scope.pagination.totalItems++;

        if(
            index >= (($scope.pagination.currentPage - 1) * $scope.pagination.numPerPage)
            && index < ((($scope.pagination.currentPage - 1) * $scope.pagination.numPerPage) + $scope.pagination.numPerPage)
        )
            return true; //return true if item index is on the currentPage

        return false;
    };
}]);

In the HTML make sure that you apply your filters to the ngRepeat before the pagination filter.

<table data-ng-controller="myController">
    <tr data-ng-repeat="item in list | filter: searchFilter | filter: paginationFilter track by $index">
        <td>
            {{item}}
        </td>
    <tr>
</table>
<ul class="pagination-sm"
    uib-pagination
    data-boundary-links="true"
    data-total-items="pagination.totalItems"
    data-items-per-page="pagination.numPerPage"
    data-ng-model="pagination.currentPage"
    data-previous-text="&lsaquo;"
    data-next-text="&rsaquo;"
    data-first-text="&laquo;"
    data-last-text="&raquo;">
 </ul>

How to make full screen background in a web page

CSS

.bbg { 
    /* The image used */
    background-image: url('...');

    /* Full height */
    height: 100%; 

    /* Center and scale the image nicely */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;    
}

HTML

<!doctype html>
<html class="h-100">
.
.
.
<body class="bbg">
</body>
.
.
.
</html>

text-align: right; not working for <label>

You can make a text align to the right inside of any element, including labels.

Html:

<label>Text</label>

Css:

label {display:block; width:x; height:y; text-align:right;}

This way, you give a width and height to your label and make any text inside of it align to the right.

What is the best way to add options to a select from a JavaScript object with jQuery?

There's an approach using the Microsoft Templating approach that's currently under proposal for inclusion into jQuery core. There's more power in using the templating so for the simplest scenario it may not be the best option. For more details see Scott Gu's post outlining the features.

First include the templating js file, available from github.

<script src="Scripts/jquery.tmpl.js" type="text/javascript" />

Next set-up a template

<script id="templateOptionItem" type="text/html">
    <option value=\'{{= Value}}\'>{{= Text}}</option>
</script>

Then with your data call the .render() method

var someData = [
    { Text: "one", Value: "1" },
    { Text: "two", Value: "2" },
    { Text: "three", Value: "3"}];

$("#templateOptionItem").render(someData).appendTo("#mySelect");

I've blogged this approach in more detail.

How can I use JSON data to populate the options of a select box?

Given returned json from your://site.com:

[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]

Use this:

    $.getJSON("your://site.com", function(json){
            $('#select').empty();
            $('#select').append($('<option>').text("Select"));
            $.each(json, function(i, obj){
                    $('#select').append($('<option>').text(obj.text).attr('value', obj.val));
            });
    });

Boxplot in R showing the mean

abline(h=mean(x))

for a horizontal line (use v instead of h for vertical if you orient your boxplot horizontally), or

points(mean(x))

for a point. Use the parameter pch to change the symbol. You may want to colour them to improve visibility too.

Note that these are called after you have drawn the boxplot.

If you are using the formula interface, you would have to construct the vector of means. For example, taking the first example from ?boxplot:

boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
means <- tapply(InsectSprays$count,InsectSprays$spray,mean)
points(means,col="red",pch=18)

If your data contains missing values, you might want to replace the last argument of the tapply function with function(x) mean(x,na.rm=T)

How to set value to form control in Reactive Forms in Angular

To assign value to a single Form control/individually, I propose to use setValue in the following way:

this.editqueForm.get('user').setValue(this.question.user);

this.editqueForm.get('questioning').setValue(this.question.questioning);

Setting max width for body using Bootstrap

In responsive.less, you can comment out the line that imports responsive-1200px-min.less.

// Large desktops

@import "responsive-1200px-min.less";

Like so:

// Large desktops

// @import "responsive-1200px-min.less";

Hex colors: Numeric representation for "transparent"?

HEXA - #RRGGBBAA

There's a relatively new way of doing transparency, it's called HEXA (HEX + Alpha). It takes in 8 digits instead of 6. The last pair is Alpha. So the pattern of pairs is #RRGGBBAA. Having 4 digits also works: #RGBA

I am not sure about its browser support for now but, you can check the DRAFT Docs for more information.

§ 4.2. The RGB hexadecimal notations: #RRGGBB

The syntax of a <hex-color> is a <hash-token> token whose value consists of 3, 4, 6, or 8 hexadecimal digits. In other words, a hex color is written as a hash character, "#", followed by some number of digits 0-9 or letters a-f (the case of the letters doesn’t matter - #00ff00 is identical to #00FF00).

8 digits

The first 6 digits are interpreted identically to the 6-digit notation. The last pair of digits, interpreted as a hexadecimal number, specifies the alpha channel of the color, where 00 represents a fully transparent color and ff represent a fully opaque color.

Example 3
In other words, #0000ffcc represents the same color as rgba(0, 0, 100%, 80%) (a slightly-transparent blue).

4 digits

This is a shorter variant of the 8-digit notation, "expanded" in the same way as the 3-digit notation is. The first digit, interpreted as a hexadecimal number, specifies the red channel of the color, where 0 represents the minimum value and f represents the maximum. The next three digits represent the green, blue, and alpha channels, respectively.

For the most part, Chrome and Firefox have started supporting this: enter image description here

How to find out what is locking my tables?

I have a stored procedure that I have put together, that deals not only with locks and blocking, but also to see what is running in a server. I have put it in master. I will share it with you, the code is below:

USE [master]
go


CREATE PROCEDURE [dbo].[sp_radhe] 

AS
BEGIN

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


-- the current_processes
-- marcelo miorelli 
-- CCHQ 
-- 04 MAR 2013 Wednesday

SELECT es.session_id AS session_id
,COALESCE(es.original_login_name, '') AS login_name
,COALESCE(es.host_name,'') AS hostname
,COALESCE(es.last_request_end_time,es.last_request_start_time) AS last_batch
,es.status
,COALESCE(er.blocking_session_id,0) AS blocked_by
,COALESCE(er.wait_type,'MISCELLANEOUS') AS waittype
,COALESCE(er.wait_time,0) AS waittime
,COALESCE(er.last_wait_type,'MISCELLANEOUS') AS lastwaittype
,COALESCE(er.wait_resource,'') AS waitresource
,coalesce(db_name(er.database_id),'No Info') as dbid
,COALESCE(er.command,'AWAITING COMMAND') AS cmd
,sql_text=st.text
,transaction_isolation =
CASE es.transaction_isolation_level
    WHEN 0 THEN 'Unspecified'
    WHEN 1 THEN 'Read Uncommitted'
    WHEN 2 THEN 'Read Committed'
    WHEN 3 THEN 'Repeatable'
    WHEN 4 THEN 'Serializable'
    WHEN 5 THEN 'Snapshot'
END
,COALESCE(es.cpu_time,0) 
    + COALESCE(er.cpu_time,0) AS cpu
,COALESCE(es.reads,0) 
    + COALESCE(es.writes,0) 
    + COALESCE(er.reads,0) 
+ COALESCE(er.writes,0) AS physical_io
,COALESCE(er.open_transaction_count,-1) AS open_tran
,COALESCE(es.program_name,'') AS program_name
,es.login_time
FROM sys.dm_exec_sessions es
LEFT OUTER JOIN sys.dm_exec_connections ec ON es.session_id = ec.session_id
LEFT OUTER JOIN sys.dm_exec_requests er ON es.session_id = er.session_id
LEFT OUTER JOIN sys.server_principals sp ON es.security_id = sp.sid
LEFT OUTER JOIN sys.dm_os_tasks ota ON es.session_id = ota.session_id
LEFT OUTER JOIN sys.dm_os_threads oth ON ota.worker_address = oth.worker_address
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS st
where es.is_user_process = 1 
  and es.session_id <> @@spid
  and es.status = 'running'
ORDER BY es.session_id

end 

GO

this procedure has done very good for me in the last couple of years. to run it just type sp_radhe

Regarding putting sp_radhe in the master database

I use the following code and make it a system stored procedure

exec sys.sp_MS_marksystemobject 'sp_radhe'

as you can see on the link below

Creating Your Own SQL Server System Stored Procedures

Regarding the transaction isolation level

Questions About T-SQL Transaction Isolation Levels You Were Too Shy to Ask

Jonathan Kehayias

Once you change the transaction isolation level it only changes when the scope exits at the end of the procedure or a return call, or if you change it explicitly again using SET TRANSACTION ISOLATION LEVEL.

In addition the TRANSACTION ISOLATION LEVEL is only scoped to the stored procedure, so you can have multiple nested stored procedures that execute at their own specific isolation levels.

time delayed redirect?

 <script type="text/JavaScript">
      setTimeout("location.href = 'http://www.your_site.com';",1500);
 </script>

Join vs. sub-query

The difference is only seen when the second joining table has significantly more data than the primary table. I had an experience like below...

We had a users table of one hundred thousand entries and their membership data (friendship) about 3 hundred thousand entries. It was a join statement in order to take friends and their data, but with a great delay. But it was working fine where there was only a small amount of data in the membership table. Once we changed it to use a sub-query it worked fine.

But in the mean time the join queries are working with other tables that have fewer entries than the primary table.

So I think the join and sub query statements are working fine and it depends on the data and the situation.

Java Embedded Databases Comparison

Java DB (Sun's distribution of Apache Derby) now ships in JDK 6!

I've been wanted to do something like Jason Cohen and have been thinking this looks like the easiest way being in the JDK distro (which of last week is now a requirement for my app). Or maybe I am just lazy that way.

How do I convert NSMutableArray to NSArray?

you try this code---

NSMutableArray *myMutableArray = [myArray mutableCopy];

and

NSArray *myArray = [myMutableArray copy];

What Java ORM do you prefer, and why?

While I share the concerns regarding Java replacements for free-form SQL queries, I really do think people criticizing ORM are doing so because of a generally poor application design.

True OOD is driven by classes and relationships, and ORM gives you consistent mapping of different relationship types and objects. If you use an ORM tool and end up coding query expressions in whatever query language the ORM framework supports (including, but not limited to Java expression trees, query methods, OQL etc.), you are definitely doing something wrong, i.e. your class model most likely doesn't support your requirements in the way it should. A clean application design doesn't really need queries on the application level. I've been refactoring many projects people started out using an ORM framework in the same way as they were used to embed SQL string constants in their code, and in the end everyone was suprised about how simple and maintainable the whole application gets once you match up your class model with the usage model. Granted, for things like search functionality etc. you need a query language, but even then queries are so much constrained that creating an even complex VIEW and mapping that to a read-only persistent class is much nicer to maintain and look at than building expressions in some query language in the code of your application. The VIEW approach also leverages database capabilities and, via materialization, can be much better performance-wise than any hand-written SQL in your Java source. So, I don't see any reason for a non-trivial application NOT to use ORM.

jQuery UI - Draggable is not a function?

This issue can also be caused if you include the normal jquery library twice. I had the following line twice, in my body and head.

It never caused any problems until I tried to use jquery UI as well.

C++ vector of char array

You can use boost::array to do that:

boost::array<char, 5> test = {'a', 'b', 'c', 'd', 'e'};
std::vector<boost::array<char, 5> > v;
v.push_back(test);

Edit:

Or you can use a vector of vectors as shown below:

char test[] = {'a', 'b', 'c', 'd', 'e'};
std::vector<std::vector<char> > v;
v.push_back(std::vector<char>(test, test + sizeof(test)/ sizeof(test[0])));

How to print in C

try this:

printf("%d", addNumber(a,b))

Here's the documentation for printf.

How do I get the last day of a month?

The last day of the month you get like this, which returns 31:

DateTime.DaysInMonth(1980, 08);

File tree view in Notepad++

As of Notepad++ 6.9, the new Folder as Workspace feature can be used.

Folder as Workspace opens your folder(s) in a panel so you can browse folder(s) and open any file in Notepad++. Every changement in the folder(s) from outside will be synchronized in the panel. Usage: Simply drop 1 (or more) folder(s) in Notepad++.

Folder as Workspace

This feature has the advantage of not showing your entire file system when just the working directory is needed. It also means you don't need plugins for it to work.

Accessing MVC's model property from Javascript

I know its too late but this solution is working perfect for both .net framework and .net core:

@System.Web.HttpUtility.JavaScriptStringEncode()

Adding new files to a subversion repository

Before you can add files in an unversioned directory, you have to add the directory itself to the versioning:

svn add directory_name

will add the directory directory_name and all sub-directories: http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.add.html

How to use wget in php?

Shellwrap is great tool for using the command-line in PHP!

Your example can be done quite easy and readable:

use MrRio\ShellWrap as sh;

$xml = (string)sh::curl(['u' => 'user:pass'], 'http://example.com/file.xml');

Java equivalent of unsigned long long?

I don't believe so. Once you want to go bigger than a signed long, I think BigInteger is the only (out of the box) way to go.

Maven2: Missing artifact but jars are in place

M2Eclipse sometimes does that. Select Project > Clean ... from the Menu and everything will be fine after the rebuild

set the iframe height automatically

If you a framework like Bootstrap you can make any iframe video responsive by using this snippet:

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" src="vid.mp4" allowfullscreen></iframe>
</div>

Splitting strings in PHP and get last part

The accepted answer has a bug in it where it still eats the first character of the input string if the delimiter is not found.

$str = '1-2-3-4-5';
echo substr($str, strrpos($str, '-') + 1);

Produces the expected result: 5

$str = '1-2-3-4-5';
echo substr($str, strrpos($str, ';') + 1);

Produces -2-3-4-5

$str = '1-2-3-4-5';
if (($pos = strrpos($str, ';')) !== false)
    echo substr($str, $pos + 1);
else
    echo $str;

Produces the whole string as desired.

3v4l link

New og:image size for Facebook share?

I'm using the minimum image size (200 x 200) and getting good results. Take a look:

enter image description here https://developers.facebook.com/tools/debug/og/object?q=origgami.com.br

This squared size is better than rectangles because it is the format that appears on facebook comments. The rectangle format gets cropped.

This size is on facebook documentation

How to validate Google reCAPTCHA v3 on server side?

In response to @mattgen88's answer ,Here is a CURL method with better arrangement:

   //$secret= 'your google captcha private key';
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL             => "https://www.google.com/recaptcha/api/siteverify",
        CURLOPT_HEADER          => "Content-Type: application/json",
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_SSL_VERIFYPEER  => FALSE, // to disable ssl verifiction set to false else true
        //CURLOPT_ENCODING      => "",
        CURLOPT_MAXREDIRS       => 10,
        CURLOPT_TIMEOUT         => 30,
        CURLOPT_HTTP_VERSION    => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST   => "POST",
        CURLOPT_POSTFIELDS      => array(
            'secret' => $secret,
            'response' => $_POST['g-recaptcha-response'],
            'remoteip' => $_SERVER['REMOTE_ADDR']
        )
    ));

    $response = json_decode(curl_exec($curl));
    $err = curl_error($curl);

    curl_close($curl);

    if ($response->success) {
        echo 'captcha';
    } 
    else if ($err){
        echo $err;
    }   
    else {
        echo 'no captcha';
    }

Only variables should be passed by reference

PHP offical Manual : end()

Parameters

array

The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

What is the canonical way to check for errors using the CUDA runtime API?

talonmies' answer above is a fine way to abort an application in an assert-style manner.

Occasionally we may wish to report and recover from an error condition in a C++ context as part of a larger application.

Here's a reasonably terse way to do that by throwing a C++ exception derived from std::runtime_error using thrust::system_error:

#include <thrust/system_error.h>
#include <thrust/system/cuda/error.h>
#include <sstream>

void throw_on_cuda_error(cudaError_t code, const char *file, int line)
{
  if(code != cudaSuccess)
  {
    std::stringstream ss;
    ss << file << "(" << line << ")";
    std::string file_and_line;
    ss >> file_and_line;
    throw thrust::system_error(code, thrust::cuda_category(), file_and_line);
  }
}

This will incorporate the filename, line number, and an English language description of the cudaError_t into the thrown exception's .what() member:

#include <iostream>

int main()
{
  try
  {
    // do something crazy
    throw_on_cuda_error(cudaSetDevice(-1), __FILE__, __LINE__);
  }
  catch(thrust::system_error &e)
  {
    std::cerr << "CUDA error after cudaSetDevice: " << e.what() << std::endl;

    // oops, recover
    cudaSetDevice(0);
  }

  return 0;
}

The output:

$ nvcc exception.cu -run
CUDA error after cudaSetDevice: exception.cu(23): invalid device ordinal

A client of some_function can distinguish CUDA errors from other kinds of errors if desired:

try
{
  // call some_function which may throw something
  some_function();
}
catch(thrust::system_error &e)
{
  std::cerr << "CUDA error during some_function: " << e.what() << std::endl;
}
catch(std::bad_alloc &e)
{
  std::cerr << "Bad memory allocation during some_function: " << e.what() << std::endl;
}
catch(std::runtime_error &e)
{
  std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}
catch(...)
{
  std::cerr << "Some other kind of error during some_function" << std::endl;

  // no idea what to do, so just rethrow the exception
  throw;
}

Because thrust::system_error is a std::runtime_error, we can alternatively handle it in the same manner of a broad class of errors if we don't require the precision of the previous example:

try
{
  // call some_function which may throw something
  some_function();
}
catch(std::runtime_error &e)
{
  std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}

Git resolve conflict using --ours/--theirs for all files

git checkout --[ours/theirs] . will do what you want, as long as you're at the root of all conflicts. ours/theirs only affects unmerged files so you shouldn't have to grep/find/etc conflicts specifically.

Finding height in Binary Search Tree

Here is a solution in C#

    private static int heightOfTree(Node root)
    {
        if (root == null)
        {
            return 0;
        }

        int left = 1 + heightOfTree(root.left);
        int right = 1 + heightOfTree(root.right);

        return Math.Max(left, right);
    }

What is the difference between RTP or RTSP in a streaming server?

I hear your pain. I'm going through this right now (years later). From what I've learned, you can think of RTSP as a "VCR controller", the protocol allows you to specify which streams (presentations) you want to play, it will then send you a description of the media, and then you can use RTSP to play, stop, pause, and record the remote stream. The media itself goes over RTP. RTSP is normally implemented over a different socket or communication layer. Although it is simply a protocol, most often it's implemented by a server over a socket. For live streams, the RTSP stream you request is simply a name of a stream. It doesn't need to refer to a file on the server, the server's RTSP implementation can parse that stream, put together a live graph, and then provide the SDP (description) for that stream name. But, this is of course specific to the way the RTSP server has been implemented. For "live" streams, it's probably simpler to just use RTP, but you'll need a way to transfer the SDP from the RTP server to the client that wants to play that stream.

Run C++ in command prompt - Windows

  • first Command is :

g++ -o program file_name.cpp

  • Second command is :

.\program.exe

Let us Check this image

How to use a switch case 'or' in PHP

I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.

Installing Apple's Network Link Conditioner Tool

It's in an additional download. Use this menu item:

Xcode > Open Developer Tool > More Developer Tools...

and get "Hardware IO Tools for Xcode".

For Xcode 8+, get "Additional Tools for Xcode [version]".

Double-click on a .prefPane file to install. If you already have an older .prefPane installed, you'll need to remove it from /Library/PreferencePanes.

PHPExcel - set cell type before writing a value in it

try this

$currencyFormat = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';
$textFormat='@';//'General','0.00','@'
$excel->getActiveSheet()->getStyle('B1')->getNumberFormat()->setFormatCode($currencyFormat);
$excel->getActiveSheet()->getStyle('C1')->getNumberFormat()->setFormatCode($textFormat);`

Add a UIView above all, even the navigation bar

Add you view as the subview of NavigationController.

[self.navigationController.navigationBar addSubview: overlayView)]

You can also add it over the window:

UIView *view = /* Your custom view */;
UIWindow *window = [UIApplication sharedApplication].keyWindow;
[window addSubview:view];

Hope this helps.. :)

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

How to fix Terminal not loading ~/.bashrc on OS X Lion

Terminal opens a login shell. This means, ~/.bash_profile will get executed, ~/.bashrc not.

The solution on most systems is to "require" the ~/.bashrc in the ~/.bash_profile: just put this snippet in your ~/.bash_profile:

[[ -s ~/.bashrc ]] && source ~/.bashrc

How to store a datetime in MySQL with timezone info

I once also faced such an issue where i needed to save data which was used by different collaborators and i ended up storing the time in unix timestamp form which represents the number of seconds since january 1970 which is an integer format. Example todays date and time in tanzania is Friday, September 13, 2019 9:44:01 PM which when store in unix timestamp would be 1568400241

Now when reading the data simply use something like php or any other language and extract the date from the unix timestamp. An example with php will be

echo date('m/d/Y', 1568400241);

This makes it easier even to store data with other collaborators in different locations. They can simply convert the date to unix timestamp with their own gmt offset and store it in a integer format and when outputting this simply convert with a

See :hover state in Chrome Developer Tools

In case it helps, this seems to be easier in the latest Chrome (47.0.2526.106):

Inspect element and then click on the three white dots in the left gutter:
click on the three white dots

Then choose the desired element state from this dropdown:
this dropdown

How to move a marker in Google Maps API

<style>
    #frame{
        position: fixed;
        top: 5%;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        width: 98%;
        height: 92%;
        display: none;
        z-index: 1000;
    }
    #map{
        position: fixed;
        display: inline-block;
        width: 99%;
        height: 93%;
        display: none;
        z-index: 1000;
    }

    #loading{
        position: fixed;
        top: 50%;
        left: 50%;
        opacity: 1!important;
        margin-top: -100px;
        margin-left: -150px;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        max-width: 66%;
        display: none;
        color: #000;

    }
    #mytitle{
        color: #FFF;
        background-image: linear-gradient(to bottom,#d67631,#d67631);
        //  border-color: rgba(47, 164, 35, 1);
        width: 100%;
        cursor: move;
    }
    #closex{ 
        display: block;
        float:right;
        position:relative;
        top:-10px;
        right: -10px;
        height: 20px;
        cursor: pointer;
    }
    .pointer{
        cursor: pointer !important;
    }

</style> 
<div id="loading">
    <i class="fa fa-circle-o-notch fa-spin fa-2x"></i>
    Loading...
</div>
<div id="frame">
    <div id="headerx"></div>
    <div id="map" >    
    </div>
</div>


<?php
$url = Yii::app()->baseUrl . '/reports/reports/transponderdetails';
?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

<script>
    function clode() {
        $('#frame').hide();
        $('#frame').html();
    }
    function track(id) {
        $('#loading').show();
        $('#loading').parent().css("opacity", '0.7');


        $.ajax({
            type: "POST",
            url: '<?php echo $url; ?>',
            data: {'id': id},
            success: function(data) {
                $('#frame').show();
                $('#headerx').html(data);
                $('#loading').parents().css("opacity", '1');
                $('#loading').hide();
                var thelat = parseFloat($('#lat').text());
                var long = parseFloat($('#long').text());
                $('#map').show();
                var lat = thelat;
                var lng = long;
                var orlat=thelat;
                var orlong=long;
                //Intialize the Path Array
                var path = new google.maps.MVCArray();
                var service = new google.maps.DirectionsService();


                var myLatLng = new google.maps.LatLng(lat, lng), myOptions = {zoom: 4, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP};
                var map = new google.maps.Map(document.getElementById('map'), myOptions);
                var poly = new google.maps.Polyline({map: map, strokeColor: '#4986E7'});
                var marker = new google.maps.Marker({position: myLatLng, map: map});

                function initialize() {
                    marker.setMap(map);
                    movepointer(map, marker);
                    var drawingManager = new google.maps.drawing.DrawingManager();
                    drawingManager.setMap(map);
                }

                function movepointer(map, marker) {
                    marker.setPosition(new google.maps.LatLng(lat, lng));
                    map.panTo(new google.maps.LatLng(lat, lng));

                    var src = myLatLng;//start point
                    var des = myLatLng;// should be the destination
                    path.push(src);
                    poly.setPath(path);
                    service.route({
                        origin: src,
                        destination: des,
                        travelMode: google.maps.DirectionsTravelMode.DRIVING
                    }, function(result, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                                path.push(result.routes[0].overview_path[i]);
                            }
                        }
                    });

                }
                ;

                // function()
                setInterval(function() {
                    lat = Math.random() + orlat;
                    lng = Math.random() + orlong;
                    console.log(lat + "-" + lng);
                    myLatLng = new google.maps.LatLng(lat, lng);
                    movepointer(map, marker);

                }, 1000);



            },
            error: function() {
                $('#frame').html('Sorry, no details found');
            },
        });
        return false;
    }
    $(function() {
        $("#frame").draggable();
    });

</script>

Execute combine multiple Linux commands in one line

If you want to execute all the commands, whether the previous one executes or not, you can use semicolon (;) to separate the commands.

cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install

If you want to execute the next command only if the previous command succeeds, then you can use && to separate the commands.

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install

In your case, the execution of consecutive commands seems to depend upon the previous commands, so use the second example i.e. use && to join the commands.

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

Try this

date = new Date('2013-03-10T02:00:00Z');
date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();//prints expected format.

Update:-

As pointed out in comments, I am updating the answer to print leading zeros for date and month if needed.

_x000D_
_x000D_
date = new Date('2013-08-03T02:00:00Z');_x000D_
year = date.getFullYear();_x000D_
month = date.getMonth()+1;_x000D_
dt = date.getDate();_x000D_
_x000D_
if (dt < 10) {_x000D_
  dt = '0' + dt;_x000D_
}_x000D_
if (month < 10) {_x000D_
  month = '0' + month;_x000D_
}_x000D_
_x000D_
console.log(year+'-' + month + '-'+dt);
_x000D_
_x000D_
_x000D_

Horizontal list items

I guess the simple solution i found is below

ul{
    display:flex;
}

Can I make dynamic styles in React Native?

You'll want something like this:

var RandomBgApp = React.createClass({
    render: function() {

        var getRandomColor = function() {
            var letters = '0123456789ABCDEF'.split('');
            var color = '#';
            for (var i = 0; i < 6; i++ ) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        };

        var rows = [
            { name: 'row 1'},
            { name: 'row 2'},
            { name: 'row 3'}
        ];

        var rowNodes = rows.map(function(row) {
            return <Text style={{backgroundColor:getRandomColor()}}>{row.name}</Text>
        });

        return (
            <View>
                {rowNodes}
            </View>
        );

    }
});

In this example I take the rows array, containing the data for the rows in the component, and map it into an array of Text components. I use inline styles to call the getRandomColor function every time I create a new Text component.

The issue with your code is that you define the style once and therefore getRandomColor only gets called once - when you define the style.

How to create hyperlink to call phone number on mobile devices?

- doesnt make matter but + sign is important when mobile user is in roaming
this is the standard format

<a href="tel:+4917640206387">+49 (0)176 - 402 063 87</a>

You can read more about it in the spec, see Make Telephone Numbers "Click-to-Call".

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

  1. return None or return can be used to exit out of a function or program, both does the same thing
  2. quit() function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter.
    import site
    
    def func():
        print("Hi")
        quit()
        print("Bye")
  1. exit() function can be used, similar to quit() but the use is discouraged for making real world applications.
import site
    
    def func():
        print("Hi")
        exit()
        print("Bye")
  1. sys.exit([arg]) function can be used and need to import sys module for that, this function can be used for real world applications unlike the other two functions.
import sys 
  height = 150
  
if height < 165: # in cm 
      
    # exits the program 
    sys.exit("Height less than 165")     
else: 
    print("You ride the rollercoaster.") 
  1. os._exit(n) function can be used to exit from a process, and need to import os module for that.

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

Unable to generate an explicit migration in entity framework

There is an ambiguity and so error. Best way is to exclude the current migration file and create new migration(add-migration) file and then copy the content of new migration to excluded file and include it again and run update-database command.

splitting a number into the integer and decimal parts

We can use a not famous built-in function; divmod:

>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338

Is it a good practice to place C++ definitions in header files?

As Tuomas said, your header should be minimal. To be complete I will expand a bit.

I personally use 4 types of files in my C++ projects:

  • Public:
  • Forwarding header: in case of templates etc, this file get the forwarding declarations that will appear in the header.
  • Header: this file includes the forwarding header, if any, and declare everything that I wish to be public (and defines the classes...)
  • Private:
  • Private header: this file is a header reserved for implementation, it includes the header and declares the helper functions / structures (for Pimpl for example or predicates). Skip if unnecessary.
  • Source file: it includes the private header (or header if no private header) and defines everything (non-template...)

Furthermore, I couple this with another rule: Do not define what you can forward declare. Though of course I am reasonable there (using Pimpl everywhere is quite a hassle).

It means that I prefer a forward declaration over an #include directive in my headers whenever I can get away with them.

Finally, I also use a visibility rule: I limit the scopes of my symbols as much as possible so that they do not pollute the outer scopes.

Putting it altogether:

// example_fwd.hpp
// Here necessary to forward declare the template class,
// you don't want people to declare them in case you wish to add
// another template symbol (with a default) later on
class MyClass;
template <class T> class MyClassT;

// example.hpp
#include "project/example_fwd.hpp"

// Those can't really be skipped
#include <string>
#include <vector>

#include "project/pimpl.hpp"

// Those can be forward declared easily
#include "project/foo_fwd.hpp"

namespace project { class Bar; }

namespace project
{
  class MyClass
  {
  public:
    struct Color // Limiting scope of enum
    {
      enum type { Red, Orange, Green };
    };
    typedef Color::type Color_t;

  public:
    MyClass(); // because of pimpl, I need to define the constructor

  private:
    struct Impl;
    pimpl<Impl> mImpl; // I won't describe pimpl here :p
  };

  template <class T> class MyClassT: public MyClass {};
} // namespace project

// example_impl.hpp (not visible to clients)
#include "project/example.hpp"
#include "project/bar.hpp"

template <class T> void check(MyClass<T> const& c) { }

// example.cpp
#include "example_impl.hpp"

// MyClass definition

The lifesaver here is that most of the times the forward header is useless: only necessary in case of typedef or template and so is the implementation header ;)

matplotlib error - no module named tkinter

Maybe you installed python from source. In this case, you can recompile python with tcl/tk supported.

  1. Complie and install tcl/tk from http://www.tcl.tk/software/tcltk/download.html, I'll suppose you installed python at /home/xxx/local/tcl-tk/.
# install tcl
wget -c https://prdownloads.sourceforge.net/tcl/tcl8.6.9-src.tar.gz
tar -xvzf tcl8.6.9-src.tar.gz
cd tcl8.6.9
./configure --prefix=/home/xxx/local/tcl-tk/
make
make install

# install tk
wget -c https://prdownloads.sourceforge.net/tcl/tk8.6.9.1-src.tar.gz
tar -xvzf tk8.6.9.1-src.tar.gz
cd tk8.6.9.1
./configure --prefix=/home/xxx/local/tcl-tk/
make
make install
  1. Recompile python with tcl/tk supported, for example:
# download the source code of python and decompress it first.

cd <your-python-src-dir>
./configure --prefix=/home/xxx/local/python \
 --with-tcltk-includes=/home/xxx/local/tcl-tk/include \
 --with-tcltk-libs=/home/xxx/local/tcl-tk/lib
make 
make install

Less than or equal to

You can use:

EQU - equal

NEQ - not equal

LSS - less than

LEQ - less than or equal

GTR - greater than

GEQ - greater than or equal

AVOID USING:

() ! ~ - * / % + - << >> & | = *= /= %= += -= &= ^= |= <<= >>=

Java: Reading integers from a file into an array

You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.

App.Config Transformation for projects which are not Web Projects in Visual Studio?

Another solution I've found is NOT to use the transformations but just have a separate config file, e.g. app.Release.config. Then add this line to your csproj file.

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <AppConfig>App.Release.config</AppConfig>
  </PropertyGroup>

This will not only generate the right myprogram.exe.config file but if you're using Setup and Deployment Project in Visual Studio to generate MSI, it'll force the deployment project to use the correct config file when packaging.

How can you tell if a value is not numeric in Oracle?

There is no built-in function. You could write one

CREATE FUNCTION is_numeric( p_str IN VARCHAR2 )
  RETURN NUMBER
IS
  l_num NUMBER;
BEGIN
  l_num := to_number( p_str );
  RETURN 1;
EXCEPTION
  WHEN value_error
  THEN
    RETURN 0;
END;

and/or

CREATE FUNCTION my_to_number( p_str IN VARCHAR2 )
  RETURN NUMBER
IS
  l_num NUMBER;
BEGIN
  l_num := to_number( p_str );
  RETURN l_num;
EXCEPTION
  WHEN value_error
  THEN
    RETURN NULL;
END;

You can then do

IF( is_numeric( str ) = 1 AND 
    my_to_number( str ) >= 1000 AND
    my_to_number( str ) <= 7000 )

If you happen to be using Oracle 12.2 or later, there are enhancements to the to_number function that you could leverage

IF( to_number( str default null on conversion error ) >= 1000 AND
    to_number( str default null on conversion error ) <= 7000 )

Graphviz: How to go from .dot to a graph?

You can use a very good online tool for it. Here is the link dreampuf.github.io Just replace the code inside editer with your code.

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

How can I open Java .class files in a human-readable way?

jd-gui is the best decompiler at the moment. it can handle newer features in Java, as compared to the getting-dusty JAD.

Sort a List of objects by multiple fields

Hope this Helps:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

class Person implements Comparable {
  String firstName, lastName;

  public Person(String f, String l) {
    this.firstName = f;
    this.lastName = l;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public String toString() {
    return "[ firstname=" + firstName + ",lastname=" + lastName + "]";
  }

  public int compareTo(Object obj) {
    Person emp = (Person) obj;
    int deptComp = firstName.compareTo(emp.getFirstName());

    return ((deptComp == 0) ? lastName.compareTo(emp.getLastName()) : deptComp);
  }

  public boolean equals(Object obj) {
    if (!(obj instanceof Person)) {
      return false;
    }
    Person emp = (Person) obj;
    return firstName.equals(emp.getFirstName()) && lastName.equals(emp.getLastName());
  }
}

class PersonComparator implements Comparator<Person> {
  public int compare(Person emp1, Person emp2) {
    int nameComp = emp1.getLastName().compareTo(emp2.getLastName());
    return ((nameComp == 0) ? emp1.getFirstName().compareTo(emp2.getFirstName()) : nameComp);
  }
}

public class Main {
  public static void main(String args[]) {
    ArrayList<Person> names = new ArrayList<Person>();
    names.add(new Person("E", "T"));
    names.add(new Person("A", "G"));
    names.add(new Person("B", "H"));
    names.add(new Person("C", "J"));

    Iterator iter1 = names.iterator();
    while (iter1.hasNext()) {
      System.out.println(iter1.next());
    }
    Collections.sort(names, new PersonComparator());
    Iterator iter2 = names.iterator();
    while (iter2.hasNext()) {
      System.out.println(iter2.next());
    }
  }
}

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

What are the best practices for SQLite on Android?

Having had some issues, I think I have understood why I have been going wrong.

I had written a database wrapper class which included a close() which called the helper close as a mirror of open() which called getWriteableDatabase and then have migrated to a ContentProvider. The model for ContentProvider does not use SQLiteDatabase.close() which I think is a big clue as the code does use getWriteableDatabase In some instances I was still doing direct access (screen validation queries in the main so I migrated to a getWriteableDatabase/rawQuery model.

I use a singleton and there is the slightly ominous comment in the close documentation

Close any open database object

(my bolding).

So I have had intermittent crashes where I use background threads to access the database and they run at the same time as foreground.

So I think close() forces the database to close regardless of any other threads holding references - so close() itself is not simply undoing the matching getWriteableDatabase but force closing any open requests. Most of the time this is not a problem as the code is single threading, but in multi-threaded cases there is always the chance of opening and closing out of sync.

Having read comments elsewhere that explains that the SqLiteDatabaseHelper code instance counts, then the only time you want a close is where you want the situation where you want to do a backup copy, and you want to force all connections to be closed and force SqLite to write away any cached stuff that might be loitering about - in other words stop all application database activity, close just in case the Helper has lost track, do any file level activity (backup/restore) then start all over again.

Although it sounds like a good idea to try and close in a controlled fashion, the reality is that Android reserves the right to trash your VM so any closing is reducing the risk of cached updates not being written, but it cannot be guaranteed if the device is stressed, and if you have correctly freed your cursors and references to databases (which should not be static members) then the helper will have closed the database anyway.

So my take is that the approach is:

Use getWriteableDatabase to open from a singleton wrapper. (I used a derived application class to provide the application context from a static to resolve the need for a context).

Never directly call close.

Never store the resultant database in any object that does not have an obvious scope and rely on reference counting to trigger an implicit close().

If doing file level handling, bring all database activity to a halt and then call close just in case there is a runaway thread on the assumption that you write proper transactions so the runaway thread will fail and the closed database will at least have proper transactions rather than potentially a file level copy of a partial transaction.

Unable to start MySQL server

Try manually start the service from Windows services, Start -> cmd.exe -> services.msc. Also try to configure the MySQL server to run on another port and try starting it again. Change the my.ini file to change the port number.

How to force div to appear below not next to another?

what u can also do i place an extra "dummy" div before your last div.

Make it 1 px heigh and the width as much needed to cover the container div/body

This will make the last div appear under it, starting from the left.

Cannot read property 'length' of null (javascript)

I tried this:

if(capital !== null){ 
//Capital has something 
}

How to access environment variable values?

A performance-driven approach - calling environ is expensive, so it's better to call it once and save it to a dictionary. Full example:

from os import environ


# Slower
print(environ["USER"], environ["NAME"])

# Faster
env_dict = dict(environ)
print(env_dict["USER"], env_dict["NAME"])

P.S- if you worry about exposing private environment variables, then sanitize env_dict after the assignment.

java: run a function after a specific number of seconds

public static Timer t;

public synchronized void startPollingTimer() {
        if (t == null) {
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                   //Do your work
                }
            };

            t = new Timer();
            t.scheduleAtFixedRate(task, 0, 1000);
        }
    }

Working with TIFFs (import, export) in Python using numpy

In case of image stacks, I find it easier to use scikit-image to read, and matplotlib to show or save. I have handled 16-bit TIFF image stacks with the following code.

from skimage import io
import matplotlib.pyplot as plt

# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(mol,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)

php check if array contains all array values from another array

Look at array_intersect().

$containsSearch = count(array_intersect($search_this, $all)) == count($search_this);

Append text to textarea with javascript

Give this a try:

<!DOCTYPE html>
<html>
<head>
    <title>List Test</title>
    <style>
        li:hover {
            cursor: hand; cursor: pointer;
        }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").click(function(){
                $('#alltext').append($(this).text());
            });
        });
    </script>
</head>
<body>

    <h2>List items</h2>
    <ol>
        <li>Hello</li>
        <li>World</li>
        <li>Earthlings</li>
    </ol>
    <form>
        <textarea id="alltext"></textarea>
    </form>

</body>
</html>

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • Twitter Bootstrap add active class to li

    You don't really need any JavaScript with Bootstrap:

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

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

    Hope this helps.

    How to increment a variable on a for loop in jinja template?

    Here's my solution:

    Put all the counters in a dictionary:

    {% set counter = {
        'counter1': 0,
        'counter2': 0,
        'etc': 0,
        } %}
    

    Define a macro to increment them easily:

    {% macro increment(dct, key, inc=1)%}
        {% if dct.update({key: dct[key] + inc}) %} {% endif %}
    {% endmacro %}
    

    Now, whenever you want to increment the 'counter1' counter, just do:

    {{ increment(counter, 'counter1') }}
    

    Full width layout with twitter bootstrap

    In Bootstrap 3, columns are specified using percentages. (In Bootstrap 2, this was only the case if a column/span was within a .row-fluid element, but that's no longer necessary and that class no longer exists.) If you use a .container, then @Michael is absolutely right that you'll be stuck with a fixed-width layout. However, you should be in good shape if you just avoid using a .container element.

    <body>
      <div class="row">
        <div class="col-lg-4">...</div>
        <div class="col-lg-8">...</div>
      </div>
    </body>
    

    The margin for the body is already 0, so you should be able to get up right to the edge. (Columns still have a 15px padding on both sides, so you may have to account for that in your design, but this shouldn't stop you, and you can always customize this when you download Bootstrap.)

    How to save image in database using C#

    My personal preference is not to save the images to a database as such. Save the image somewhere in the file system and save a reference in the database.

    In PHP, how do you change the key of an array element?

    Easy stuff:

    this function will accept the target $hash and $replacements is also a hash containing newkey=>oldkey associations.

    This function will preserve original order, but could be problematic for very large (like above 10k records) arrays regarding performance & memory.

    function keyRename(array $hash, array $replacements) {
        $new=array();
        foreach($hash as $k=>$v)
        {
            if($ok=array_search($k,$replacements))
                $k=$ok;
            $new[$k]=$v;
        }
        return $new;    
    }
    

    this alternative function would do the same, with far better performance & memory usage, at the cost of loosing original order (which should not be a problem since it is hashtable!)

    function keyRename(array $hash, array $replacements) {
    
        foreach($hash as $k=>$v)
            if($ok=array_search($k,$replacements))
            {
              $hash[$ok]=$v;
              unset($hash[$k]);
            }
    
        return $hash;       
    }
    

    Round a floating-point number down to the nearest integer?

    Simple

    print int(x)
    

    will work as well.

    Sorting options elements alphabetically using jQuery

    Accepted answer is not the best in all cases because sometimes you want to perserve classes of options and different arguments (for example data-foo).

    My solution is:

    var sel = $('#select_id');
    var selected = sel.val(); // cache selected value, before reordering
    var opts_list = sel.find('option');
    opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
    sel.html('').append(opts_list);
    sel.val(selected); // set cached selected value
    

    //For ie11 or those who get a blank options, replace html('') empty()

    #1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

    After the long time research i have found the solution for above:

    1. Firstly you change the wp-config.php> Database DB_CHARSET default to "utf8"

    2. Click the "Export" tab for the database

    3. Click the "Custom" radio button

    4. Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.

    5. Scroll to the bottom and click go

    Then you are on.

    git stash -> merge stashed change with current changes

    tl;dr

    Run git add first.


    I just discovered that if your uncommitted changes are added to the index (i.e. "staged", using git add ...), then git stash apply (and, presumably, git stash pop) will actually do a proper merge. If there are no conflicts, you're golden. If not, resolve them as usual with git mergetool, or manually with an editor.

    To be clear, this is the process I'm talking about:

    mkdir test-repo && cd test-repo && git init
    echo test > test.txt
    git add test.txt && git commit -m "Initial version"
    
    # here's the interesting part:
    
    # make a local change and stash it:
    echo test2 > test.txt
    git stash
    
    # make a different local change:
    echo test3 > test.txt
    
    # try to apply the previous changes:
    git stash apply
    # git complains "Cannot apply to a dirty working tree, please stage your changes"
    
    # add "test3" changes to the index, then re-try the stash:
    git add test.txt
    git stash apply
    # git says: "Auto-merging test.txt"
    # git says: "CONFLICT (content): Merge conflict in test.txt"
    

    ... which is probably what you're looking for.

    Find all elements with a certain attribute value in jquery

    You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:

    <div id="abc_1"></div>
    <div id="abc_2"></div>
    <div id="xyz_3"></div>
    <div id="xyz_4"></div>...
    

    You can use the code:

    var abc = $('div[id^=abc]')
    

    This will return a DOM array of divs which have id starting with abc:

    <div id="abc_1"></div>
    <div id="abc_2"></div>
    

    Here is the demo: http://jsfiddle.net/mCuWS/

    How can I list all commits that changed a specific file?

    Use git log --all <filename> to view the commits influencing <filename> in all branches.

    call a static method inside a class?

    Let's assume this is your class:

    class Test
    {
        private $baz = 1;
    
        public function foo() { ... }
    
        public function bar() 
        {
            printf("baz = %d\n", $this->baz);
        }
    
        public static function staticMethod() { echo "static method\n"; }
    }
    

    From within the foo() method, let's look at the different options:

    $this->staticMethod();
    

    So that calls staticMethod() as an instance method, right? It does not. This is because the method is declared as public static the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.

    $this::staticMethod();
    

    Since PHP 5.3 you can use $var::method() to mean <class-of-$var>::; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:

    self::staticMethod();
    

    Now, before you start thinking that the :: is the static call operator, let me give you another example:

    self::bar();
    

    This will print baz = 1, which means that $this->bar() and self::bar() do exactly the same thing; that's because :: is just a scope resolution operator. It's there to make parent::, self:: and static:: work and give you access to static variables; how a method is called depends on its signature and how the caller was called.

    To see all of this in action, see this 3v4l.org output.

    Creating a node class in Java

    Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

    public class ItemLinkedList {
        private ItemInfoNode head;
        private ItemInfoNode tail;
        private int size = 0;
    
        public int getSize() {
            return size;
        }
    
        public void addBack(ItemInfo info) {
            size++;
            if (head == null) {
                head = new ItemInfoNode(info, null, null);
                tail = head;
            } else {
                ItemInfoNode node = new ItemInfoNode(info, null, tail);
                this.tail.next =node;
                this.tail = node;
            }
        }
    
        public void addFront(ItemInfo info) {
            size++;
            if (head == null) {
                head = new ItemInfoNode(info, null, null);
                tail = head;
            } else {
                ItemInfoNode node = new ItemInfoNode(info, head, null);
                this.head.prev = node;
                this.head = node;
            }
        }
    
        public ItemInfo removeBack() {
            ItemInfo result = null;
            if (head != null) {
                size--;
                result = tail.info;
                if (tail.prev != null) {
                    tail.prev.next = null;
                    tail = tail.prev;
                } else {
                    head = null;
                    tail = null;
                }
            }
            return result;
        }
    
        public ItemInfo removeFront() {
            ItemInfo result = null;
            if (head != null) {
                size--;
                result = head.info;
                if (head.next != null) {
                    head.next.prev = null;
                    head = head.next;
                } else {
                    head = null;
                    tail = null;
                }
            }
            return result;
        }
    
        public class ItemInfoNode {
    
            private ItemInfoNode next;
            private ItemInfoNode prev;
            private ItemInfo info;
    
            public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
                this.info = info;
                this.next = next;
                this.prev = prev;
            }
    
            public void setInfo(ItemInfo info) {
                this.info = info;
            }
    
            public void setNext(ItemInfoNode node) {
                next = node;
            }
    
            public void setPrev(ItemInfoNode node) {
                prev = node;
            }
    
            public ItemInfo getInfo() {
                return info;
            }
    
            public ItemInfoNode getNext() {
                return next;
            }
    
            public ItemInfoNode getPrev() {
                return prev;
            }
        }
    }
    

    EDIT:

    Declare ItemInfo as this:

    public class ItemInfo {
        private String name;
        private String rfdNumber;
        private double price;
        private String originalPosition;
    
        public ItemInfo(){
        }
    
        public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
            this.name = name;
            this.rfdNumber = rfdNumber;
            this.price = price;
            this.originalPosition = originalPosition;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getRfdNumber() {
            return rfdNumber;
        }
    
        public void setRfdNumber(String rfdNumber) {
            this.rfdNumber = rfdNumber;
        }
    
        public double getPrice() {
            return price;
        }
    
        public void setPrice(double price) {
            this.price = price;
        }
    
        public String getOriginalPosition() {
            return originalPosition;
        }
    
        public void setOriginalPosition(String originalPosition) {
            this.originalPosition = originalPosition;
        }
    }
    

    Then, You can use your nodes inside the linked list like this:

    public static void main(String[] args) {
        ItemLinkedList list = new ItemLinkedList();
        for (int i = 1; i <= 10; i++) {
            list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
    
        }
        while (list.size() > 0){
            System.out.println(list.removeFront().getName());
        }
    }
    

    How to find locked rows in Oracle

    you can find the locked tables in oralce by querying with following query

        select
       c.owner,
       c.object_name,
       c.object_type,
       b.sid,
       b.serial#,
       b.status,
       b.osuser,
       b.machine
    from
       v$locked_object a ,
       v$session b,
       dba_objects c
    where
       b.sid = a.session_id
    and
       a.object_id = c.object_id;
    

    Searching multiple files for multiple words

    If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:

    1. Find What = text1*.*text2
    2. Filters : .
    3. Search mode = Regular Expression
    4. Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

    Check if EditText is empty.

    You could call this function for each of the edit texts:

    public boolean isEmpty(EditText editText) {
        boolean isEmptyResult = false;
        if (editText.getText().length() == 0) {
            isEmptyResult = true;
        }
        return isEmptyResult;
    }
    

    Intellij IDEA Java classes not auto compiling on save

    I had the same issue. I was using the "Power save mode", which prevents from compiling incrementally and showing compilation errors.

    Triangle Draw Method

    there is no command directly to draw Triangle. For Drawing of triangle we have to use the concept of lines here.

    i.e, g.drawLines(Coordinates of points)

    Word-wrap in an HTML table

    Check out this demo

    _x000D_
    _x000D_
       <table style="width: 100%;">_x000D_
        <tr>_x000D_
            <td><div style="word-break:break-all;">LongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWordLongWord</div>_x000D_
            </td>_x000D_
            <td>_x000D_
                <span style="display: inline;">Foo</span>_x000D_
            </td>_x000D_
        </tr>_x000D_
    </table>
    _x000D_
    _x000D_
    _x000D_

    Here is the link to read

    CodeIgniter - accessing $config variable in view

    $this->config->item('config_var') did not work for my case.

    I could only use the config_item('config_var'); to echo variables in the view

    Check if number is decimal

    i use this:

    function is_decimal ($price){
      $value= trim($price); // trim space keys
      $value= is_numeric($value); // validate numeric and numeric string, e.g., 12.00, 1e00, 123; but not -123
      $value= preg_match('/^\d$/', $value); // only allow any digit e.g., 0,1,2,3,4,5,6,7,8,9. This will eliminate the numeric string, e.g., 1e00
      $value= round($value, 2); // to a specified number of decimal places.e.g., 1.12345=> 1.12
    
      return $value;
    }
    

    How to configure socket connect timeout

    I worked with Unity and had some problem with the BeginConnect and other async methods from socket.

    There is something than I don't understand but the code samples before doesn't work for me.

    So I wrote this piece of code to make it work. I test it on an adhoc network with android and pc, also in local on my computer. Hope it can help.

    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    using System;
    using System.Diagnostics;
    
    class ConnexionParameter : Guardian
    {
        public TcpClient client;
        public string address;
        public int port;
        public Thread principale;
        public Thread thisthread = null;
        public int timeout;
    
        private EventWaitHandle wh = new AutoResetEvent(false);
    
        public ConnexionParameter(TcpClient client, string address, int port, int timeout, Thread principale)
        {
            this.client = client;
            this.address = address;
            this.port = port;
            this.principale = principale;
            this.timeout = timeout;
            thisthread = new Thread(Connect);
        }
    
    
        public void Connect()
        {
            WatchDog.Start(timeout, this);
            try
            {
                client.Connect(IPAddress.Parse(address), port);
    
            }
            catch (Exception)
            {
                UnityEngine.Debug.LogWarning("Unable to connect service (Training mode? Or not running?)");
            }
            OnTimeOver();
            //principale.Resume();
        }
    
        public bool IsConnected = true;
        public void OnTimeOver()
        {
            try
            {
                if (!client.Connected)
                {
                        /*there is the trick. The abort method from thread doesn't
     make the connection stop immediately(I think it's because it rise an exception
     that make time to stop). Instead I close the socket while it's trying to
     connect , that make the connection method return faster*/
                    IsConnected = false;
    
                    client.Close();
                }
                wh.Set();
    
            }
            catch(Exception)
            {
                UnityEngine.Debug.LogWarning("Connexion already closed, or forcing connexion thread to end. Ignore.");
            }
        }
    
    
        public void Start()
        {
    
            thisthread.Start();
            wh.WaitOne();
            //principale.Suspend();
        }
    
        public bool Get()
        {
            Start();
            return IsConnected;
        }
    }
    
    
    public static class Connexion
    {
    
    
        public static bool Connect(this TcpClient client, string address, int port, int timeout)
        {
            ConnexionParameter cp = new ConnexionParameter(client, address, port, timeout, Thread.CurrentThread);
            return cp.Get();
        }
    
    //http://stackoverflow.com/questions/19653588/timeout-at-acceptsocket
        public static Socket AcceptSocket(this TcpListener tcpListener, int timeoutms, int pollInterval = 10)
        {
            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutms);
            var stopWatch = new Stopwatch();
            stopWatch.Start();
            while (stopWatch.Elapsed < timeout)
            {
                if (tcpListener.Pending())
                    return tcpListener.AcceptSocket();
    
                Thread.Sleep(pollInterval);
            }
            return null;
        }
    
    
    }
    

    and there a very simple watchdog on C# to make it work:

    using System.Threading;
    
    public interface Guardian
    {
        void OnTimeOver();
    }
    
    public class WatchDog {
    
        int m_iMs;
        Guardian m_guardian;
    
        public WatchDog(int a_iMs, Guardian a_guardian)
        {
            m_iMs = a_iMs;
            m_guardian = a_guardian;
            Thread thread = new Thread(body);
            thread.Start(this);
        }
    
    
        private void body(object o)
        {
            WatchDog watchdog = (WatchDog)o;
            Thread.Sleep(watchdog.m_iMs);
            watchdog.m_guardian.OnTimeOver();
        }
    
        public static void Start(int a_iMs, Guardian a_guardian)
        {
            new WatchDog(a_iMs, a_guardian);
        }
    }
    

    Jersey stopped working with InjectionManagerFactory not found

    Choose which DI to inject stuff into Jersey:

    Spring 4:

    <dependency>
      <groupId>org.glassfish.jersey.ext</groupId>
      <artifactId>jersey-spring4</artifactId>
    </dependency>
    

    Spring 3:

    <dependency>
      <groupId>org.glassfish.jersey.ext</groupId>
      <artifactId>jersey-spring3</artifactId>
    </dependency>
    

    HK2:

    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
    </dependency>
    

    Is null check needed before calling instanceof?

    No, a null check is not needed before using instanceof.

    The expression x instanceof SomeClass is false if x is null.

    From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":

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

    So if the operand is null, the result is false.

    How do I choose grid and block dimensions for CUDA kernels?

    The answers above point out how the block size can impact performance and suggest a common heuristic for its choice based on occupancy maximization. Without wanting to provide the criterion to choose the block size, it would be worth mentioning that CUDA 6.5 (now in Release Candidate version) includes several new runtime functions to aid in occupancy calculations and launch configuration, see

    CUDA Pro Tip: Occupancy API Simplifies Launch Configuration

    One of the useful functions is cudaOccupancyMaxPotentialBlockSize which heuristically calculates a block size that achieves the maximum occupancy. The values provided by that function could be then used as the starting point of a manual optimization of the launch parameters. Below is a little example.

    #include <stdio.h>
    
    /************************/
    /* TEST KERNEL FUNCTION */
    /************************/
    __global__ void MyKernel(int *a, int *b, int *c, int N) 
    { 
        int idx = threadIdx.x + blockIdx.x * blockDim.x; 
    
        if (idx < N) { c[idx] = a[idx] + b[idx]; } 
    } 
    
    /********/
    /* MAIN */
    /********/
    void main() 
    { 
        const int N = 1000000;
    
        int blockSize;      // The launch configurator returned block size 
        int minGridSize;    // The minimum grid size needed to achieve the maximum occupancy for a full device launch 
        int gridSize;       // The actual grid size needed, based on input size 
    
        int* h_vec1 = (int*) malloc(N*sizeof(int));
        int* h_vec2 = (int*) malloc(N*sizeof(int));
        int* h_vec3 = (int*) malloc(N*sizeof(int));
        int* h_vec4 = (int*) malloc(N*sizeof(int));
    
        int* d_vec1; cudaMalloc((void**)&d_vec1, N*sizeof(int));
        int* d_vec2; cudaMalloc((void**)&d_vec2, N*sizeof(int));
        int* d_vec3; cudaMalloc((void**)&d_vec3, N*sizeof(int));
    
        for (int i=0; i<N; i++) {
            h_vec1[i] = 10;
            h_vec2[i] = 20;
            h_vec4[i] = h_vec1[i] + h_vec2[i];
        }
    
        cudaMemcpy(d_vec1, h_vec1, N*sizeof(int), cudaMemcpyHostToDevice);
        cudaMemcpy(d_vec2, h_vec2, N*sizeof(int), cudaMemcpyHostToDevice);
    
        float time;
        cudaEvent_t start, stop;
        cudaEventCreate(&start);
        cudaEventCreate(&stop);
        cudaEventRecord(start, 0);
    
        cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize, MyKernel, 0, N); 
    
        // Round up according to array size 
        gridSize = (N + blockSize - 1) / blockSize; 
    
        cudaEventRecord(stop, 0);
        cudaEventSynchronize(stop);
        cudaEventElapsedTime(&time, start, stop);
        printf("Occupancy calculator elapsed time:  %3.3f ms \n", time);
    
        cudaEventRecord(start, 0);
    
        MyKernel<<<gridSize, blockSize>>>(d_vec1, d_vec2, d_vec3, N); 
    
        cudaEventRecord(stop, 0);
        cudaEventSynchronize(stop);
        cudaEventElapsedTime(&time, start, stop);
        printf("Kernel elapsed time:  %3.3f ms \n", time);
    
        printf("Blocksize %i\n", blockSize);
    
        cudaMemcpy(h_vec3, d_vec3, N*sizeof(int), cudaMemcpyDeviceToHost);
    
        for (int i=0; i<N; i++) {
            if (h_vec3[i] != h_vec4[i]) { printf("Error at i = %i! Host = %i; Device = %i\n", i, h_vec4[i], h_vec3[i]); return; };
        }
    
        printf("Test passed\n");
    
    }
    

    EDIT

    The cudaOccupancyMaxPotentialBlockSize is defined in the cuda_runtime.h file and is defined as follows:

    template<class T>
    __inline__ __host__ CUDART_DEVICE cudaError_t cudaOccupancyMaxPotentialBlockSize(
        int    *minGridSize,
        int    *blockSize,
        T       func,
        size_t  dynamicSMemSize = 0,
        int     blockSizeLimit = 0)
    {
        return cudaOccupancyMaxPotentialBlockSizeVariableSMem(minGridSize, blockSize, func, __cudaOccupancyB2DHelper(dynamicSMemSize), blockSizeLimit);
    }
    

    The meanings for the parameters is the following

    minGridSize     = Suggested min grid size to achieve a full machine launch.
    blockSize       = Suggested block size to achieve maximum occupancy.
    func            = Kernel function.
    dynamicSMemSize = Size of dynamically allocated shared memory. Of course, it is known at runtime before any kernel launch. The size of the statically allocated shared memory is not needed as it is inferred by the properties of func.
    blockSizeLimit  = Maximum size for each block. In the case of 1D kernels, it can coincide with the number of input elements.
    

    Note that, as of CUDA 6.5, one needs to compute one's own 2D/3D block dimensions from the 1D block size suggested by the API.

    Note also that the CUDA driver API contains functionally equivalent APIs for occupancy calculation, so it is possible to use cuOccupancyMaxPotentialBlockSize in driver API code in the same way shown for the runtime API in the example above.

    Should switch statements always contain a default clause?

    Switch cases should almost always have a default case.

    Reasons to use a default

    1.To 'catch' an unexpected value

    switch(type)
    {
        case 1:
            //something
        case 2:
            //something else
        default:
            // unknown type! based on the language,
            // there should probably be some error-handling
            // here, maybe an exception
    }
    

    2. To handle 'default' actions, where the cases are for special behavior.

    You see this a LOT in menu-driven programs and bash shell scripts. You might also see this when a variable is declared outside the switch-case but not initialized, and each case initializes it to something different. Here the default needs to initialize it too so that down the line code that accesses the variable doesn't raise an error.

    3. To show someone reading your code that you've covered that case.

    variable = (variable == "value") ? 1 : 2;
    switch(variable)
    {
        case 1:
            // something
        case 2:
            // something else
        default:
            // will NOT execute because of the line preceding the switch.
    }
    

    This was an over-simplified example, but the point is that someone reading the code shouldn't wonder why variable cannot be something other than 1 or 2.


    The only case I can think of to NOT use default is when the switch is checking something where its rather obvious every other alternative can be happily ignored

    switch(keystroke)
    {
        case 'w':
            // move up
        case 'a':
            // move left
        case 's':
            // move down
        case 'd':
            // move right
        // no default really required here
    }
    

    Rename a column in MySQL

    From MySQL 8.0 you could use

    ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;
    

    ALTER TABLE Syntax:

    RENAME COLUMN:

    • Can change a column name but not its definition.

    • More convenient than CHANGE to rename a column without changing its definition.

    DBFiddle Demo

    How do I automatically play a Youtube video (IFrame API) muted?

    Try this its working fine

    _x000D_
    _x000D_
    <html><body style='margin:0px;padding:0px;'>_x000D_
            <script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>_x000D_
                    var player;_x000D_
            function onYouTubeIframeAPIReady()_x000D_
            {player=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}_x000D_
            function onPlayerReady(event){player.mute();player.setVolume(0);player.playVideo();}_x000D_
            </script>_x000D_
            <iframe id='playerId' type='text/html' width='1280' height='720'_x000D_
            src='https://www.youtube.com/embed/R52bof3tvZs?enablejsapi=1&rel=0&playsinline=1&autoplay=1&showinfo=0&autohide=1&controls=0&modestbranding=1' frameborder='0'>_x000D_
            </body></html>
    _x000D_
    _x000D_
    _x000D_

    What is the inclusive range of float and double in Java?

    Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

    You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

    How do I get a value of a <span> using jQuery?

         $('span id').text(); worked with me
    

    How to get C# Enum description from value?

    Update

    The Unconstrained Melody library is no longer maintained; Support was dropped in favour of Enums.NET.

    In Enums.NET you'd use:

    string description = ((MyEnum)value).AsString(EnumFormat.Description);
    

    Original post

    I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use:

    string description = Enums.GetDescription((MyEnum)value);
    

    This:

    • Ensures (with generic type constraints) that the value really is an enum value
    • Avoids the boxing in your current solution
    • Caches all the descriptions to avoid using reflection on every call
    • Has a bunch of other methods, including the ability to parse the value from the description

    I realise the core answer was just the cast from an int to MyEnum, but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :)

    Convert from enum ordinal to enum type

    Every enum has name(), which gives a string with the name of enum member.

    Given enum Suit{Heart, Spade, Club, Diamond}, Suit.Heart.name() will give Heart.

    Every enum has a valueOf() method, which takes an enum type and a string, to perform the reverse operation:

    Enum.valueOf(Suit.class, "Heart") returns Suit.Heart.

    Why anyone would use ordinals is beyond me. It may be nanoseconds faster, but it is not safe, if the enum members change, as another developer may not be aware some code is relying on ordinal values (especially in the JSP page cited in the question, network and database overhead completely dominates the time, not using an integer over a string).

    Why does my favicon not show up?

    Try adding the profile attribute to your head tag and use "image/x-icon" for the type attribute:

    <head profile="http://www.w3.org/2005/10/profile">
    <link rel="icon" type="image/x-icon" href="img/favicon.ico">
    

    If the above code doesn't work, try using the full icon path for the href attribute:

    <head profile="http://www.w3.org/2005/10/profile">
    <link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">
    

    Get value from text area

    Vanilla JS

    document.getElementById("textareaID").value
    

    jQuery

    $("#textareaID").val()
    

    Cannot do the other way round (it's always good to know what you're doing)

    document.getElementById("textareaID").value() // --> TypeError: Property 'value' of object #<HTMLTextAreaElement> is not a function
    

    jQuery:

    $("#textareaID").value // --> undefined
    

    Compress files while reading data from STDIN

    Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.

    cat test.csv | gzip > test.csv.gz
    

    cat test.csv will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.

    How to load external scripts dynamically in Angular?

    Hi you can use Renderer2 and elementRef with just a few lines of code:

    constructor(private readonly elementRef: ElementRef,
              private renderer: Renderer2) {
    }
    ngOnInit() {
     const script = this.renderer.createElement('script');
     script.src = 'http://iknow.com/this/does/not/work/either/file.js';
     script.onload = () => {
       console.log('script loaded');
       initFile();
     };
     this.renderer.appendChild(this.elementRef.nativeElement, script);
    }
    

    the onload function can be used to call the script functions after the script is loaded, this is very useful if you have to do the calls in the ngOnInit()

    Setting format and value in input type="date"

    function getDefaultDate(curDate){
    var dt = new Date(curDate);`enter code here`
    var date = dt.getDate();
    var month = dt.getMonth();
    var year = dt.getFullYear();
    if (month.toString().length == 1) {
        month = "0" + month
    }
    if (date.toString().length == 1) {
        date = "0" + date
    }
    return year.toString() + "-" + month.toString() + "-" + date.toString();
    }
    

    In function pass your date string.

    Filter output in logcat by tagname

    Here is how I create a tag:

    private static final String TAG = SomeActivity.class.getSimpleName();
     Log.d(TAG, "some description");
    

    You could use getCannonicalName

    Here I have following TAG filters:

    • any (*) View - VERBOSE
    • any (*) Activity - VERBOSE
    • any tag starting with Xyz(*) - ERROR
    • System.out - SILENT (since I am using Log in my own code)

    Here what I type in terminal:

    $  adb logcat *View:V *Activity:V Xyz*:E System.out:S
    

    R Markdown - changing font size and font type in html output

    To change the font size, you don't need to know a lot of html for this. Open the html output with notepad ++. Control F search for "font-size". You should see a section with font sizes for the headers (h1, h2, h3,...).

    Add the following somewhere in this section.

    body {
      font-size: 16px;
    }
    

    The font size above is 16 pt font. You can change the number to whatever you want.

    Delete files older than 15 days using PowerShell

    #----- Define parameters -----#
    #----- Get current date ----#
    $Now = Get-Date
    $Days = "15" #----- define amount of days ----#
    $Targetfolder = "C:\Logs" #----- define folder where files are located ----#
    $Extension = "*.log" #----- define extension ----#
    $Lastwrite = $Now.AddDays(-$Days)
    
    #----- Get files based on lastwrite filter and specified folder ---#
    $Files = Get-Children $Targetfolder -include $Extension -Recurse | where {$_.LastwriteTime -le "$Lastwrite"}
    
    foreach ($File in $Files)
    {
        if ($File -ne $Null)
        {
            write-host "Deleting File $File" backgroundcolor "DarkRed"
            Remove-item $File.Fullname | out-null
        }
        else
            write-host "No more files to delete" -forgroundcolor "Green"
        }
    }
    

    Entityframework Join using join method and lambdas

    Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

    Nonetheless, here is the equivalent of your above query (i think, untested):

    var query = db.Categories         // source
       .Join(db.CategoryMaps,         // target
          c => c.CategoryId,          // FK
          cm => cm.ChildCategoryId,   // PK
          (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
       .Select(x => x.Category);  // select result
    

    You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

    Default nginx client_max_body_size

    The default value for client_max_body_size directive is 1 MiB.

    It can be set in http, server and location context — as in the most cases, this directive in a nested block takes precedence over the same directive in the ancestors blocks.

    Excerpt from the ngx_http_core_module documentation:

    Syntax:   client_max_body_size size;
    Default:  client_max_body_size 1m;
    Context:  http, server, location
    

    Sets the maximum allowed size of the client request body, specified in the “Content-Length” request header field. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.

    Don't forget to reload configuration by nginx -s reload or service nginx reload commands prepending with sudo (if any).

    set default schema for a sql query

    Very old question, but since google led me here I'll add a solution that I found useful:

    Step 1. Create a user for each schema you need to be able to use. E.g. "user_myschema"

    Step 2. Use EXECUTE AS to execute the SQL statements as the required schema user.

    Step 3. Use REVERT to switch back to the original user.

    Example: Let's say you have a table "mytable" present in schema "otherschema", which is not your default schema. Running "SELECT * FROM mytable" won't work.

    Create a user named "user_otherschema" and set that user's default schema to be "otherschema".

    Now you can run this script to interact with the table:

    EXECUTE AS USER = 'user_otherschema';
    SELECT * FROM mytable
    REVERT
    

    The revert statements resets current user, so you are yourself again.

    Link to EXECUTE AS documentation: https://docs.microsoft.com/en-us/sql/t-sql/statements/execute-as-transact-sql?view=sql-server-2017

    Post form data using HttpWebRequest

    Use this code:

    internal void SomeFunction() {
        Dictionary<string, string> formField = new Dictionary<string, string>();
        
        formField.Add("Name", "Henry");
        formField.Add("Age", "21");
        
        string body = GetBodyStringFromDictionary(formField);
        // output : Name=Henry&Age=21
    }
    
    internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
    {
        string body = string.Empty;
        foreach (var pair in formField)
        {
            body += $"{pair.Key}={pair.Value}&";   
        }
    
        // delete last "&"
        body = body.Substring(0, body.Length - 1);
    
        return body;
    }
    

    How to use ternary operator in razor (specifically on HTML attributes)?

    You should be able to use the @() expression syntax:

    <a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a>
    

    How do I fix twitter-bootstrap on IE?

    Just for completeness - it's worth noting that with Bootstrap 3, as per the docs, ensure the following structure in your page. It solved issues I was having with IE9 and v3.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
    <!-- content -->
    </body>
    </html>
    

    Inserting values to SQLite table in Android

    Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html

    JQuery Validate Dropdown list

    As we know jQuery validate plugin invalidates Select field when it has blank value. Why don't we set its value to blank when required.

    Yes, you can validate select field with some predefined value.

    $("#everything").validate({
        rules: {
            select_field:{
                required: {
                    depends: function(element){
                        if('none' == $('#select_field').val()){
                            //Set predefined value to blank.
                            $('#select_field').val('');
                        }
                        return true;
                    }
                }
            }
        }
    });
    

    We can set blank value for select field but in some case we can't. For Ex: using a function that generates Dropdown field for you and you don't have control over it.

    I hope it helps as it helps me.

    My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

    When setup a job in new windows you have two fields "program/script" and "Start in(Optional)". Put program name in first and program location in second. If you will not do that and your program start not in directory with exe, it will not find files that are located in it.

    CSS Selector for <input type="?"

    Yes. IE7+ supports attribute selectors:

    input[type=radio]
    input[type^=ra]
    input[type*=d]
    input[type$=io]
    

    Element input with attribute type which contains a value that is equal to, begins with, contains or ends with a certain value.

    Other safe (IE7+) selectors are:

    • Parent > child that has: p > span { font-weight: bold; }
    • Preceded by ~ element which is: span ~ span { color: blue; }

    Which for <p><span/><span/></p> would effectively give you:

    <p>
        <span style="font-weight: bold;">
        <span style="font-weight: bold; color: blue;">
    </p>
    

    Further reading: Browser CSS compatibility on quirksmode.com

    I'm surprised that everyone else thinks it can't be done. CSS attribute selectors have been here for some time already. I guess it's time we clean up our .css files.

    how to get param in method post spring mvc?

    When I want to get all the POST params I am using the code below,

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public ViewForResponseClass update(@RequestBody AClass anObject) {
        // Source..
    }
    

    I am using the @RequestBody annotation for post/put/delete http requests instead of the @RequestParam which reads the GET parameters.

    How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

    .loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

    In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
    
    In [2]: df
    Out[2]: 
              a         b         c         d         e
    0  0.669701  0.780497  0.955690  0.451573  0.232194
    1  0.952762  0.585579  0.890801  0.643251  0.556220
    2  0.900713  0.790938  0.952628  0.505775  0.582365
    3  0.994205  0.330560  0.286694  0.125061  0.575153
    
    In [5]: df.loc[df['c']>0.5,['a','d']]
    Out[5]: 
              a         d
    0  0.669701  0.451573
    1  0.952762  0.643251
    2  0.900713  0.505775
    

    And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

    In [6]: df.loc[df['c']>0.5,['a','d']].values
    Out[6]: 
    array([[ 0.66970138,  0.45157274],
           [ 0.95276167,  0.64325143],
           [ 0.90071271,  0.50577509]])
    

    How to disable a particular checkstyle rule for a particular line of code?

    In case if you are using checkstyle from qulice mvn plugin (https://github.com/teamed/qulice) you may use the following suppresion:

    // @checkstyle <Rulename> (N lines)
    ... code with violation(s)
    

    or

    
    /**
     * ...
     * @checkstyle <Rulename> (N lines)
     * ...
     */
     ... code with violation(s)
    

    Add text to Existing PDF using Python

    pdfrw will let you read in pages from an existing PDF and draw them to a reportlab canvas (similar to drawing an image). There are examples for this in the pdfrw examples/rl1 subdirectory on github. Disclaimer: I am the pdfrw author.