Programs & Examples On #Orbital mechanics

Understanding Matlab FFT example

There are some misconceptions here.

Frequencies above 500 can be represented in an FFT result of length 1000. Unfortunately these frequencies are all folded together and mixed into the first 500 FFT result bins. So normally you don't want to feed an FFT a signal containing any frequencies at or above half the sampling rate, as the FFT won't care and will just mix the high frequencies together with the low ones (aliasing) making the result pretty much useless. That's why data should be low-pass filtered before being sampled and fed to an FFT.

The FFT returns amplitudes without frequencies because the frequencies depend, not just on the length of the FFT, but also on the sample rate of the data, which isn't part of the FFT itself or it's input. You can feed the same length FFT data at any sample rate, as thus get any range of frequencies out of it.

The reason the result plots ends at 500 is that, for any real data input, the frequencies above half the length of the FFT are just mirrored repeats (complex conjugated) of the data in the first half. Since they are duplicates, most people just ignore them. Why plot duplicates? The FFT calculates the other half of the result for people who feed the FFT complex data (with both real and imaginary components), which does create two different halves.

How to check if a key exists in Json Object and get its value

JSONObject root= new JSONObject();
JSONObject container= root.getJSONObject("LabelData");

try{
//if key will not be available put it in the try catch block your program 
 will work without error 
String Video=container.getString("video");
}
catch(JsonException e){

 if key will not be there then this block will execute

 } 
 if(video!=null || !video.isEmpty){
  //get Value of video
}else{
  //other vise leave it
 }

i think this might help you

Round number to nearest integer

round(value,significantDigit) is the ordinary solution, however this does not operate as one would expect from a math perspective when round values ending in 5. If the 5 is in the digit just after the one you're rounded to, these values are only sometimes rounded up as expected (i.e. 8.005 rounding to two decimal digits gives 8.01). For certain values due to the quirks of floating point math, they are rounded down instead!

i.e.

>>> round(1.0005,3)
1.0
>>> round(2.0005,3)
2.001
>>> round(3.0005,3)
3.001
>>> round(4.0005,3)
4.0
>>> round(1.005,2)
1.0
>>> round(5.005,2)
5.0
>>> round(6.005,2)
6.0
>>> round(7.005,2)
7.0
>>> round(3.005,2)
3.0
>>> round(8.005,2)
8.01

Weird.

Assuming your intent is to do the traditional rounding for statistics in the sciences, this is a handy wrapper to get the round function working as expected needing to import extra stuff like Decimal.

>>> round(0.075,2)

0.07

>>> round(0.075+10**(-2*5),2)

0.08

Aha! So based on this we can make a function...

def roundTraditional(val,digits):
   return round(val+10**(-len(str(val))-1), digits)

Basically this adds a value guaranteed to be smaller than the least given digit of the string you're trying to use round on. By adding that small quantity it preserve's round's behavior in most cases, while now ensuring if the digit inferior to the one being rounded to is 5 it rounds up, and if it is 4 it rounds down.

The approach of using 10**(-len(val)-1) was deliberate, as it the largest small number you can add to force the shift, while also ensuring that the value you add never changes the rounding even if the decimal . is missing. I could use just 10**(-len(val)) with a condiditional if (val>1) to subtract 1 more... but it's simpler to just always subtract the 1 as that won't change much the applicable range of decimal numbers this workaround can properly handle. This approach will fail if your values reaches the limits of the type, this will fail, but for nearly the entire range of valid decimal values it should work.

You can also use the decimal library to accomplish this, but the wrapper I propose is simpler and may be preferred in some cases.


Edit: Thanks Blckknght for pointing out that the 5 fringe case occurs only for certain values. Also an earlier version of this answer wasn't explicit enough that the odd rounding behavior occurs only when the digit immediately inferior to the digit you're rounding to has a 5.

What should be in my .gitignore for an Android Studio project?

There is NO NEED to add to the source control any of the following:

.idea/
.gradle/
*.iml
build/
local.properties

So you can configure hgignore or gitignore accordingly.

The first time a developer clones the source control can go:

  1. Open Android Studio
  2. Import Project
  3. Browse for the build.gradle within the cloned repository and open it

That's all

PS: Android Studio will then, through maven, get the gradle plugin assuming that your build.gradle looks similar to this:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.12.2'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}

Android studio will generate the content of .idea folder (including the workspace.xml, which shouldn't be in source control because it is generated) and the .gradle folder.

This approach is Eclipse-friendly in the way that the source control does not really know anything about Android Studio. Android Studio just needs the build.gradle to import a project and generate the rest.

Best way to remove items from a collection

If you want to access members of the collection by one of their properties, you might consider using a Dictionary<T> or KeyedCollection<T> instead. This way you don't have to search for the item you're looking for.

Otherwise, you could at least do this:

foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
    if (spAssignment.Member.Name == shortName)
    {
        workspace.RoleAssignments.Remove(spAssignment);
        break;
    }
}

Deserializing JSON data to C# using JSON.NET

You can use:

JsonConvert.PopulateObject(json, obj);

here: json is the json string,obj is the target object. See: example

Note: PopulateObject() will not erase obj's list data, after Populate(), obj's list member will contains its original data and data from json string

How to get AM/PM from a datetime in PHP

You need to convert it to a UNIX timestamp (using strtotime) and then back into the format you require using the date function.

For example:

$currentDateTime = '08/04/2010 22:15:00';
$newDateTime = date('h:i A', strtotime($currentDateTime));

Disallow Twitter Bootstrap modal window from closing

You can set default behavior of modal popup by using of below line of code:

 $.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

with this method you can get specific range of string.you need to pass start index and after that total number of characters you want.

extension String{
    func substring(fromIndex : Int,count : Int) -> String{
        let startIndex = self.index(self.startIndex, offsetBy: fromIndex)
        let endIndex = self.index(self.startIndex, offsetBy: fromIndex + count)
        let range = startIndex..<endIndex
        return String(self[range])
    }
}

how to convert string into time format and add two hours

tl;dr

LocalDateTime.parse( 
    "2018-01-23 01:23:45".replace( " " , "T" )  
).plusHours( 2 )

java.time

The modern approach uses the java.time classes added to Java 8, Java 9, and later.

user enters in the format YYYY-MM-DD HH:MM:SS

Parse that input string into a date-time object. Your format is close to complying with standard ISO 8601 format, used by default in the java.time classes for parsing/generating strings. To fully comply, replace the SPACE in the middle with a T.

String input = "2018-01-23 01:23:45".replace( " " , "T" ) ; // Yields: 2018-01-23T01:23:45

Parse as a LocalDateTime given that your input lacks any indicator of time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( input ) ;

add two hours

The java.time classes can do the math for you.

LocalDateTime twoHoursLater = ldt.plusHours( 2 ) ;

Time Zone

Be aware that a LocalDateTime does not represent a moment, a point on the timeline. Without the context of a time zone or offset-from-UTC, it has no real meaning. The “Local” part of the name means any locality or no locality, rather than any one particular locality. Just saying "noon on Jan 21st" could mean noon in Auckland, New Zealand which happens several hours earlier than noon in Paris France.

To define an actual moment, you must specify a zone or offset.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  // Define an actual moment, a point on the timeline by giving a context with time zone.

If you know the intended time zone for certain, apply it before adding the two hours. The LocalDateTime class assumes simple generic 24-hour days when doing the math. But in various time zones on various dates, days may be 23 or 25 hours long, or may be other lengths. So, for correct results in a zoned context, add the hours to your ZonedDateTime rather than LocalDateTime.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

XPath test if node value is number

I've been dealing with 01 - which is a numeric.

string(number($v)) != string($v) makes the segregation

" app-release.apk" how to change this default generated apk name

My solution may also be of help to someone.

Tested and Works on IntelliJ 2017.3.2 with Gradle 4.4

Scenario:

I have 2 flavours in my application, and so I wanted each release to be named appropriately according to each flavor.

The code below will be placed into your module gradle build file found in:

{app-root}/app/build.gradle

Gradle code to be added to android{ } block:

android {
    // ...

    defaultConfig {
        versionCode 10
        versionName "1.2.3_build5"
    }

    buildTypes {
        // ...

        release {
            // ...

            applicationVariants.all { 
                variant.outputs.each { output ->
                    output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(output.outputFile.name, variant.flavorName + "-" + defaultConfig.versionName + "_v" + defaultConfig.versionCode + ".apk"))
                }
            }

        }
    }

    productFlavors {
        myspicyflavor {
            applicationIdSuffix ".MySpicyFlavor"
            signingConfig signingConfigs.debug
        }

        mystandardflavor {
            applicationIdSuffix ".MyStandardFlavor"
            signingConfig signingConfigs.config
        }
    }
}

The above provides the following APKs found in {app-root}/app/:

myspicyflavor-release-1.2.3_build5_v10.apk
mystandardflavor-release-1.2.3_build5_v10.apk

Hope it can be of use to someone.

For more info, see other answers mentioned in the question

ReactJS: "Uncaught SyntaxError: Unexpected token <"

The code you have is correct. JSX code needs to be compiled to JS:

http://facebook.github.io/react/jsx-compiler.html

Android turn On/Off WiFi HotSpot programmatically

I have publish unofficial api's for same, it's contains more than just hotspot turn on/off. link

For API's DOC - link.

How do you connect to multiple MySQL databases on a single webpage?

<?php
    // Sapan Mohanty
    // Skype:sapan.mohannty
    //***********************************
    $oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    $NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    mysql_select_db('OLDDBNAME', $oldData );
    mysql_select_db('NEWDBNAME', $NewData );
    $getAllTablesName    = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
    $getAllTablesNameExe = mysql_query($getAllTablesName);
    //echo mysql_error();
    while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {

        $oldDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
        $oldDataCountResult = mysql_fetch_object($oldDataCount);


        $newDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
        $newDataCountResult = mysql_fetch_object($newDataCount);

        if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
            echo "<br/><b>" . $dataTableName->table_name . "</b>";
            echo " | Old: " . $oldDataCountResult->noOfRecord;
            echo " | New: " . $newDataCountResult->noOfRecord;

            if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
                echo " | <font color='green'>*</font>";

            } else {
                echo " | <font color='red'>*</font>";
            }

            echo "<br/>----------------------------------------";

        }     

    }
    ?>

Ternary operator in AngularJS templates

For texts in angular template (userType is property of $scope, like $scope.userType):

<span>
  {{userType=='admin' ? 'Edit' : 'Show'}}
</span>

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

I resolve this problem with following function. I use Visual Studio 2019.

FILE* __cdecl __iob_func(void)
{
    FILE _iob[] = { *stdin, *stdout, *stderr };
    return _iob;
}

because stdin Macro defined function call, "*stdin" expression is cannot used global array initializer. But local array initialier is possible. sorry, I am poor at english.

How to get the number of characters in a string

There are several ways to get a string length:

package main

import (
    "bytes"
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    b := "?????"
    len1 := len([]rune(b))
    len2 := bytes.Count([]byte(b), nil) -1
    len3 := strings.Count(b, "") - 1
    len4 := utf8.RuneCountInString(b)
    fmt.Println(len1)
    fmt.Println(len2)
    fmt.Println(len3)
    fmt.Println(len4)

}

How do I horizontally center a span element inside a div

One option is to give the <a> a display of inline-block and then apply text-align: center; on the containing block (remove the float as well):

div { 
    background: red;
    overflow: hidden; 
    text-align: center;
}

span a {
    background: #222;
    color: #fff;
    display: inline-block;
    /* float:left;  remove */
    margin: 10px 10px 0 0;
    padding: 5px 10px
}

http://jsfiddle.net/Adrift/cePe3/

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

There is another case where the path to the workspace may not exist, e.g., if you have imported preferences from another workspace, then some imported workspace addresses may appear in your "open workspace" dialog; then if you didn't pay attention to those addresses, you would get the exact same error once you tried to open them.

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

I found it working for me by setting this variable directly on Azure platorm (if you use it). Just select your web app -> configuration -> application settings and add the variable and its value, then press Save button.

Android Studio SDK location

C:\Users\Max\AppData\Local\Android\sdk\

The location I found it in for Windows 8.1. I think the default SDK folder. AppData is a hidden folder, so you will not locate it unless you type it in once you get into your C:\Users\ folder.

MATLAB, Filling in the area between two sets of data, lines in one figure

You want to look at the patch() function, and sneak in points for the start and end of the horizontal line:

x = 0:.1:2*pi;
y = sin(x)+rand(size(x))/2;

x2 = [0 x 2*pi];
y2 = [.1 y .1];
patch(x2, y2, [.8 .8 .1]);

If you only want the filled in area for a part of the data, you'll need to truncate the x and y vectors to only include the points you need.

Cross-browser bookmark/add to favorites JavaScript

jQuery Version

JavaScript (modified from a script I found on someone's site - I just can't find the site again, so I can't give the person credit):

$(document).ready(function() {
  $("#bookmarkme").click(function() {
    if (window.sidebar) { // Mozilla Firefox Bookmark
      window.sidebar.addPanel(location.href,document.title,"");
    } else if(window.external) { // IE Favorite
      window.external.AddFavorite(location.href,document.title); }
    else if(window.opera && window.print) { // Opera Hotlist
      this.title=document.title;
      return true;
    }
  });
});

HTML:

<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>

IE will show an error if you don't run it off a server (it doesn't allow JavaScript bookmarks via JavaScript when viewing it as a file://...).

How do I redirect to another webpage?

# HTML Page Redirect Using jQuery/JavaScript Method

Try this example code:

function YourJavaScriptFunction()
{
    var i = $('#login').val();
    if (i == 'login')
        window.location = "Login.php";
    else
        window.location = "Logout.php";
}

If you want to give a complete URL as window.location = "www.google.co.in";.

How to remove "disabled" attribute using jQuery?

<input type="text" disabled="disabled" class="inputDisabled" value="">
?<button id="edit">Edit</button>????????????????????????????????

$("#edit").click(function(event){
    event.preventDefault();
    $('.inputDisabled').removeAttr("disabled")
});?

http://jsfiddle.net/ZwHfY/

How do you use window.postMessage across domains?

Here is an example that works on Chrome 5.0.375.125.

The page B (iframe content):

<html>
    <head></head>
    <body>
        <script>
            top.postMessage('hello', 'A');
        </script>
    </body>
</html>

Note the use of top.postMessage or parent.postMessage not window.postMessage here

The page A:

<html>
<head></head>
<body>
    <iframe src="B"></iframe>
    <script>
        window.addEventListener( "message",
          function (e) {
                if(e.origin !== 'B'){ return; } 
                alert(e.data);
          },
          false);
    </script>
</body>
</html>

A and B must be something like http://domain.com

EDIT:

From another question, it looks the domains(A and B here) must have a / for the postMessage to work properly.

Change the "No file chosen":

using label with label text changed

<input type="file" id="files" name="files" class="hidden"/>
<label for="files" id="lable_file">Select file</label>

add jquery

<script>
     $("#files").change(function(){
        $("#lable_file").html($(this).val().split("\\").splice(-1,1)[0] || "Select file");     
     });
</script>

How to use variables in a command in sed?

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

PHP Session timeout

<?php
session_start();
if($_SESSION['login'] != 'ok')
    header('location: /dashboard.php?login=0');

if(isset($_SESSION['last-activity']) && time() - $_SESSION['last-activity'] > 600) {
    // session inactive more than 10 min
    header('location: /logout.php?timeout=1');
}

$_SESSION['last-activity'] = time(); // update last activity time stamp

if(time() - $_SESSION['created'] > 600) {
    // session started more than 10 min ago
    session_regenerate_id(true); // change session id and invalidate old session
    $_SESSION['created'] = time(); // update creation time
}
?>

How to get the clicked link's href with jquery?

$(".testClick").click(function () {
         var value = $(this).attr("href");
         alert(value );     
}); 

When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.

How to properly add include directories with CMake

Two things must be done.

First add the directory to be included:

target_include_directories(test PRIVATE ${YOUR_DIRECTORY})

In case you are stuck with a very old CMake version (2.8.10 or older) without support for target_include_directories, you can also use the legacy include_directories instead:

include_directories(${YOUR_DIRECTORY})

Then you also must add the header files to the list of your source files for the current target, for instance:

set(SOURCES file.cpp file2.cpp ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)
add_executable(test ${SOURCES})

This way, the header files will appear as dependencies in the Makefile, and also for example in the generated Visual Studio project, if you generate one.

How to use those header files for several targets:

set(HEADER_FILES ${YOUR_DIRECTORY}/file1.h ${YOUR_DIRECTORY}/file2.h)

add_library(mylib libsrc.cpp ${HEADER_FILES})
target_include_directories(mylib PRIVATE ${YOUR_DIRECTORY})
add_executable(myexec execfile.cpp ${HEADER_FILES})
target_include_directories(myexec PRIVATE ${YOUR_DIRECTORY})

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Check if null Boolean is true results in exception

If you don't like extra null checks:

if (Boolean.TRUE.equals(value)) {...}

Set the value of a variable with the result of a command in a Windows batch file

To do what Jesse describes, from a Windows batch file you will need to write:

for /f "delims=" %%a in ('ver') do @set foobar=%%a 

But, I instead suggest using Cygwin on your Windows system if you are used to Unix-type scripting.

How do I remove whitespace from the end of a string in Python?

You can use strip() or split() to control the spaces values as in the following:

words = "   first  second   "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# Remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())


# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))

why windows 7 task scheduler task fails with error 2147942667

For me it was the "Start In" - I copied the values from an older server, and updated the path to the new .exe location, but I forgot to update the "start in" location - if it doesn't exist, you get this error too

Quoting @hans-passant 's comment from above, because it is valuable to debugging this issue:

Convert the error code to hex to get 0x8007010B. The 7 makes it a Windows error. Which makes 010B error code 267. "The directory name is invalid". Sure, that happens.

How to match "any character" in regular expression?

Use the pattern . to match any character once, .* to match any character zero or more times, .+ to match any character one or more times.

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

Difference between null and empty ("") Java String

"" is an actual string, albeit an empty one.

null, however, means that the String variable points to nothing.

a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

a.equals(b) returns false because "" does not equal null, obviously.

The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

a.length()

a.substring(0, 1)

and so on.

If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

b.length()


If the difference you are wondering about is == versus equals, it's this:

== compares references, like if I went

String a = new String("");
String b = new String("");
System.out.println(a==b);

That would output false because I allocated two different objects, and a and b point to different objects.

However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

Be warned, though, that Java does have a special case for Strings.

String a = "abc";
String b = "abc";
System.out.println(a==b);

You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.

rebase in progress. Cannot commit. How to proceed or stop (abort)?

  • Step 1: Keep going git rebase --continue

  • Step 2: fix CONFLICTS then git add .

  • Back to step 1, now if it says no changes .. then run git rebase --skip and go back to step 1

  • If you just want to quit rebase run git rebase --abort

  • Once all changes are done run git commit -m "rebase complete" and you are done.


Note: If you don't know what's going on and just want to go back to where the repo was, then just do:

git rebase --abort

Read about rebase: git-rebase doc

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

I was finally able to resolve the "Excel connection issue" in my case it was not a 64 bit issue like some of them had encounterd, I noticed the package worked fine when i didnt enable the package configuration, but i wanted my package to run with the configuration file, digging further into it i noticed i had selected all the properties that were available, I unchecked all and checked only the ones that I needed to store in the package configuration file. and ta dha it works :)

How do you run a command as an administrator from the Windows command line?

A batch/WSH hybrid is able to call ShellExecute to display the UAC elevation dialog...

@if (1==1) @if(1==0) @ELSE
@echo off&SETLOCAL ENABLEEXTENSIONS
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"||(
    cscript //E:JScript //nologo "%~f0"
    @goto :EOF
)
echo.Performing admin tasks...
REM call foo.exe
@goto :EOF
@end @ELSE
ShA=new ActiveXObject("Shell.Application")
ShA.ShellExecute("cmd.exe","/c \""+WScript.ScriptFullName+"\"","","runas",5);
@end

How can I list all collections in the MongoDB shell?

> show collections

will list all the collections in the currently selected DB, as stated in the command line help (help).

How to send an object from one Android Activity to another using Intents?

You'll need to serialize your object into some kind of string representation. One possible string representation is JSON, and one of the easiest ways to serialize to/from JSON in android, if you ask me, is through Google GSON.

In that case you just put the string return value from (new Gson()).toJson(myObject); and retrieve the string value and use fromJson to turn it back into your object.

If your object isn't very complex, however, it might not be worth the overhead, and you could consider passing the separate values of the object instead.

Storing data into list with class

If you want to instantiate and add in the same line, you'd have to do something like this:

lstemail.Add(new EmailData { FirstName = "JOhn", LastName = "Smith", Location = "Los Angeles" });

or just instantiate the object prior, and add it directly in:

EmailData data = new EmailData();
data.FirstName = "JOhn";
data.LastName = "Smith";
data.Location = "Los Angeles"

lstemail.Add(data);

Path of assets in CSS files in Symfony 2

The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:

  • Reference the CSS files in the web folder (after: console assets:install --symlink web)

    {% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}
    
  • Use the cssembed filter to embed images in the CSS like this.

    {% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}
    

Array.size() vs Array.length

The .size() function is available in Jquery and many other libraries.

The .length property works only when the index is an integer.

The length property will work with this type of array:

var nums = new Array();
nums[0] = 1; 
nums[1] = 2;
print(nums.length); // displays 2

The length property won't work with this type of array:

var pbook = new Array(); 
pbook["David"] = 1; 
pbook["Jennifer"] = 2;
print(pbook.length); // displays 0

So in your case you should be using the .length property.

Tool to compare directories (Windows 7)

I use WinMerge. It is free and works pretty well (works for files and directories).

Angular 2: How to write a for loop, not a foreach loop

you can use _.range([optional] start, end). It creates a new Minified list containing an interval of numbers from start (inclusive) until the end (exclusive). Here I am using lodash.js ._range() method.

Example:

CODE

var dayOfMonth = _.range(1,32);  // It creates a new list from 1 to 31.

//HTML Now, you can use it in For loop

<div *ngFor="let day of dayOfMonth">{{day}}</div>

Python Decimals format

If you have Python 2.6 or newer, use format:

'{0:.3g}'.format(num)

For Python 2.5 or older:

'%.3g'%(num)

Explanation:

{0}tells format to print the first argument -- in this case, num.

Everything after the colon (:) specifies the format_spec.

.3 sets the precision to 3.

g removes insignificant zeros. See http://en.wikipedia.org/wiki/Printf#fprintf

For example:

tests=[(1.00, '1'),
       (1.2, '1.2'),
       (1.23, '1.23'),
       (1.234, '1.23'),
       (1.2345, '1.23')]

for num, answer in tests:
    result = '{0:.3g}'.format(num)
    if result != answer:
        print('Error: {0} --> {1} != {2}'.format(num, result, answer))
        exit()
    else:
        print('{0} --> {1}'.format(num,result))

yields

1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23

Using Python 3.6 or newer, you could use f-strings:

In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'

Jquery select this + class

Maybe something like: $(".subclass", this);

How do emulators work and how are they written?

I've never done anything so fancy as to emulate a game console but I did take a course once where the assignment was to write an emulator for the machine described in Andrew Tanenbaums Structured Computer Organization. That was fun an gave me a lot of aha moments. You might want to pick that book up before diving in to writing a real emulator.

html - table row like a link

After reading this thread and some others I came up with the following solution in javascript:

function trs_makelinks(trs) {
    for (var i = 0; i < trs.length; ++i) {
        if (trs[i].getAttribute("href") != undefined) {
            var tr = trs[i];
            tr.onclick = function () { window.location.href = this.getAttribute("href"); };
            tr.onkeydown = function (e) {
                var e = e || window.event;
                if ((e.keyCode === 13) || (e.keyCode === 32)) {
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                    this.click();
                }
            };
            tr.role = "button";
            tr.tabIndex = 0;
            tr.style.cursor = "pointer";
        }
    }
}

/* It could be adapted for other tags */
trs_makelinks(document.getElementsByTagName("tr"));
trs_makelinks(document.getElementsByTagName("td"));
trs_makelinks(document.getElementsByTagName("th"));

To use it put the href in tr/td/th that you desire to be clickable like: <tr href="http://stackoverflow.com">. And make sure the script above is executed after the tr element is created (by its placement or using event handlers).

The downside is it won't totally make the TRs behave as links like with divs with display: table;, and they won't be keyboard-selectable or have status text. Edit: I made keyboard navigation work by setting onkeydown, role and tabIndex, you could remove that part if only mouse is needed. They won't show the URL in statusbar on hovering though.

You can style specifically the link TRs with "tr[href]" CSS selector.

XAMPP - Error: MySQL shutdown unexpectedly

In my case : I have just replaced

....xampp/mysql/backup files 

into

**xampp/mysql/data**

It worked for me.

add an onclick event to a div

Assign the onclick like this:

divTag.onclick = printWorking;

The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>, but this is generally not recommended.

What is the yield keyword used for in C#?

The yield keyword actually does quite a lot here.

The function returns an object that implements the IEnumerable<object> interface. If a calling function starts foreaching over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.

The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:

public void Consumer()
{
    foreach(int i in Integers())
    {
        Console.WriteLine(i.ToString());
    }
}

public IEnumerable<int> Integers()
{
    yield return 1;
    yield return 2;
    yield return 4;
    yield return 8;
    yield return 16;
    yield return 16777216;
}

When you step through the example, you'll find the first call to Integers() returns 1. The second call returns 2 and the line yield return 1 is not executed again.

Here is a real-life example:

public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
    using (var connection = CreateConnection())
    {
        using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
        {
            command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    yield return make(reader);
                }
            }
        }
    }
}

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.

Changing an AIX password via script?

In addition to the other suggestions, you can also achieve this using a HEREDOC.

In your immediate case, this might look like:

$ /usr/bin/passwd root <<EOF
test
test
EOF

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Use the ensure_ascii=False switch to json.dumps(), then encode the value to UTF-8 manually:

>>> json_string = json.dumps("??? ????", ensure_ascii=False).encode('utf8')
>>> json_string
b'"\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94"'
>>> print(json_string.decode())
"??? ????"

If you are writing to a file, just use json.dump() and leave it to the file object to encode:

with open('filename', 'w', encoding='utf8') as json_file:
    json.dump("??? ????", json_file, ensure_ascii=False)

Caveats for Python 2

For Python 2, there are some more caveats to take into account. If you are writing this to a file, you can use io.open() instead of open() to produce a file object that encodes Unicode values for you as you write, then use json.dump() instead to write to that file:

with io.open('filename', 'w', encoding='utf8') as json_file:
    json.dump(u"??? ????", json_file, ensure_ascii=False)

Do note that there is a bug in the json module where the ensure_ascii=False flag can produce a mix of unicode and str objects. The workaround for Python 2 then is:

with io.open('filename', 'w', encoding='utf8') as json_file:
    data = json.dumps(u"??? ????", ensure_ascii=False)
    # unicode(data) auto-decodes data to unicode if str
    json_file.write(unicode(data))

In Python 2, when using byte strings (type str), encoded to UTF-8, make sure to also set the encoding keyword:

>>> d={ 1: "??? ????", 2: u"??? ????" }
>>> d
{1: '\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94', 2: u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'}

>>> s=json.dumps(d, ensure_ascii=False, encoding='utf8')
>>> s
u'{"1": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4", "2": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"}'
>>> json.loads(s)['1']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> json.loads(s)['2']
u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
>>> print json.loads(s)['1']
??? ????
>>> print json.loads(s)['2']
??? ????

How to center buttons in Twitter Bootstrap 3?

It works for me try to make an independent <div>then put the button into that. just like this :

<div id="contactBtn">
            <button type="submit" class="btn btn-primary ">Send</button>
</div>

Then Go to to your CSSStyle page and do the Text-align:center like this :

#contactBtn{text-align: center;}

Return only string message from Spring MVC 3 Controller

With Spring 4, if your Controller is annotated with @RestController instead of @Controller, you don't need the @ResponseBody annotation.

The code would be

@RestController
public class FooController {

   @RequestMapping(value="/controller", method=GET)
   public String foo() {
      return "Response!";
   }

}

You can find the Javadoc for @RestController here

PHP XML how to output nice format

Tried all the answers but none worked. Maybe it's because I'm appending and removing childs before saving the XML. After a lot of googling found this comment in the php documentation. I only had to reload the resulting XML to make it work.

$outXML = $xml->saveXML(); 
$xml = new DOMDocument(); 
$xml->preserveWhiteSpace = false; 
$xml->formatOutput = true; 
$xml->loadXML($outXML); 
$outXML = $xml->saveXML(); 

QComboBox - set selected item based on the item's data

If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item.

ui->comboBox->setCurrentText("choice 2");

From the Qt 5.7 documentation

The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.

So as long as the combo box is not editable, the text specified in the function call will be selected in the combo box.

Reference: http://doc.qt.io/qt-5/qcombobox.html#currentText-prop

jQuery $("#radioButton").change(...) not firing during de-selection

The change event not firing on deselection is the desired behaviour. You should run a selector over the entire radio group rather than just the single radio button. And your radio group should have the same name (with different values)

Consider the following code:

$('input[name="job[video_need]"]').on('change', function () {
    var value;
    if ($(this).val() == 'none') {
        value = 'hide';
    } else {
        value = 'show';
    }
    $('#video-script-collapse').collapse(value);
});

I have same use case as yours i.e. to show an input box when a particular radio button is selected. If the event was fired on de-selection as well, I would get 2 events each time.

PHP DOMDocument loadHTML not encoding UTF-8 correctly

This took me a while to figure out but here's my answer.

Before using DomDocument I would use file_get_contents to retrieve urls and then process them with string functions. Perhaps not the best way but quick. After being convinced Dom was just as quick I first tried the following:

$dom = new DomDocument('1.0', 'UTF-8');
if ($dom->loadHTMLFile($url) == false) { // read the url
    // error message
}
else {
    // process
}

This failed spectacularly in preserving UTF-8 encoding despite the proper meta tags, php settings and all the rest of the remedies offered here and elsewhere. Here's what works:

$dom = new DomDocument('1.0', 'UTF-8');
$str = file_get_contents($url);
if ($dom->loadHTML(mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8')) == false) {
}

etc. Now everything's right with the world. Hope this helps.

How to play video with AVPlayerViewController (AVKit) in Swift

Swift 5+

First of all you have to define 2 variables globally inside your view controller.

var player: AVPlayer!
var playerViewController: AVPlayerViewController!

Here I'm adding player to a desired view.

@IBOutlet weak var playerView: UIView!

Then add following code to the viewDidLoad method.

let videoURL = URL(string: "videoUrl")
self.player = AVPlayer(url: videoURL!)
self.playerViewController = AVPlayerViewController()
playerViewController.player = self.player
playerViewController.view.frame = self.playerView.frame
playerViewController.player?.pause()
self.playerView.addSubview(playerViewController.view)

If you are not defining player and playerViewController globally, you won't be able to embed player.

How do I make a textbox that only accepts numbers?

This is my aproach:

  1. using linq (easy to modify filter)
  2. copy/paste proof code
  3. keeps caret position when you press a forbidden character
  4. accepts left zeroes
  5. and any size numbers

    private void numeroCuenta_TextChanged(object sender, EventArgs e)
    {
        string org = numeroCuenta.Text;
        string formated = string.Concat(org.Where(c => (c >= '0' && c <= '9')));
        if (formated != org)
        {
            int s = numeroCuenta.SelectionStart;
            if (s > 0 && formated.Length > s && org[s - 1] != formated[s - 1]) s--;
            numeroCuenta.Text = formated;
            numeroCuenta.SelectionStart = s;
        }
    }
    

How to display special characters in PHP

So I try htmlspecialchars() or htmlentities() which outputs <p>Résumé<p> and the browser renders <p>Résumé<p>.

If you've got it working where it displays Résumé with <p></p> tags around it, then just don't convert the paragraph, only your string. Then the paragraph will be rendered as HTML and your string will be displayed within.

How can I get the intersection, union, and subset of arrays in Ruby?

Utilizing the fact that you can do set operations on arrays by doing &(intersection), -(difference), and |(union).

Obviously I didn't implement the MultiSet to spec, but this should get you started:

class MultiSet
  attr_accessor :set
  def initialize(set)
    @set = set
  end
  # intersection
  def &(other)
    @set & other.set
  end
  # difference
  def -(other)
    @set - other.set
  end
  # union
  def |(other)
    @set | other.set
  end
end

x = MultiSet.new([1,1,2,2,3,4,5,6])
y = MultiSet.new([1,3,5,6])

p x - y # [2,2,4]
p x & y # [1,3,5,6]
p x | y # [1,2,3,4,5,6]

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

As others have mentioned, there can be multiple reasons for this error.

If you are using SSH with Smart Card (PIV), and adding the card to ssh-agent with
ssh-add -s /usr/lib64/pkcs11/opensc-pkcs11.so
you may get the error
sign_and_send_pubkey: signing failed: agent refused operation
from ssh if the PIV authentication has expired, or if you have removed and reinserted the PIV card.

In that case, if you try to do another ssh-add -s you will still get an error:
Could not add card "/usr/lib64/opensc-pkcs11.so": agent refused operation

According to RedHat Bug 1609055 - pkcs11 support in agent is clunky, you instead need to do

ssh-add -e /usr/lib64/opensc-pkcs11.so
ssh-add -s /usr/lib64/opensc-pkcs11.so

Angular 5 Service to read local .json file

First You have to inject HttpClient and Not HttpClientModule, second thing you have to remove .map((res:any) => res.json()) you won't need it any more because the new HttpClient will give you the body of the response by default , finally make sure that you import HttpClientModule in your AppModule :

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs';

@Injectable()
export class AppSettingsService {

   constructor(private http: HttpClient) {
        this.getJSON().subscribe(data => {
            console.log(data);
        });
    }

    public getJSON(): Observable<any> {
        return this.http.get("./assets/mydata.json");
    }
}

to add this to your Component:

@Component({
    selector: 'mycmp',
    templateUrl: 'my.component.html',
    styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
    constructor(
        private appSettingsService : AppSettingsService 
    ) { }

   ngOnInit(){
       this.appSettingsService.getJSON().subscribe(data => {
            console.log(data);
        });
   }
}

How do I convert a datetime to date?

From the documentation:

datetime.datetime.date()

Return date object with same year, month and day.

How to take last four characters from a varchar?

SUBSTR(column, LENGTH(column) - 3, 4)

LENGTH returns length of string and SUBSTR returns 4 characters from "the position length - 4"

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

I had same problem with UnicodeDecodeError and i solved it with this line. Don't know if is the best way but it worked for me.

str = str.decode('unicode_escape').encode('utf-8')

Remove Sub String by using Python

BeautifulSoup(text, features="html.parser").text 

For the people who were seeking deep info in my answer, sorry.

I'll explain it.

Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

Once done so, we just request all the text from within the HTML object.

Differences between C++ string == and compare()?

Internally, string::operator==() is using string::compare(). Please refer to: CPlusPlus - string::operator==()

I wrote a small application to compare the performance, and apparently if you compile and run your code on debug environment the string::compare() is slightly faster than string::operator==(). However if you compile and run your code in Release environment, both are pretty much the same.

FYI, I ran 1,000,000 iteration in order to come up with such conclusion.

In order to prove why in debug environment the string::compare is faster, I went to the assembly and here is the code:

DEBUG BUILD

string::operator==()

        if (str1 == str2)
00D42A34  lea         eax,[str2]  
00D42A37  push        eax  
00D42A38  lea         ecx,[str1]  
00D42A3B  push        ecx  
00D42A3C  call        std::operator==<char,std::char_traits<char>,std::allocator<char> > (0D23EECh)  
00D42A41  add         esp,8  
00D42A44  movzx       edx,al  
00D42A47  test        edx,edx  
00D42A49  je          Algorithm::PerformanceTest::stringComparison_usingEqualOperator1+0C4h (0D42A54h)  

string::compare()

            if (str1.compare(str2) == 0)
00D424D4  lea         eax,[str2]  
00D424D7  push        eax  
00D424D8  lea         ecx,[str1]  
00D424DB  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0D23582h)  
00D424E0  test        eax,eax  
00D424E2  jne         Algorithm::PerformanceTest::stringComparison_usingCompare1+0BDh (0D424EDh)

You can see that in string::operator==(), it has to perform extra operations (add esp, 8 and movzx edx,al)

RELEASE BUILD

string::operator==()

        if (str1 == str2)
008533F0  cmp         dword ptr [ebp-14h],10h  
008533F4  lea         eax,[str2]  
008533F7  push        dword ptr [ebp-18h]  
008533FA  cmovae      eax,dword ptr [str2]  
008533FE  push        eax  
008533FF  push        dword ptr [ebp-30h]  
00853402  push        ecx  
00853403  lea         ecx,[str1]  
00853406  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)  

string::compare()

            if (str1.compare(str2) == 0)
    00853830  cmp         dword ptr [ebp-14h],10h  
    00853834  lea         eax,[str2]  
    00853837  push        dword ptr [ebp-18h]  
    0085383A  cmovae      eax,dword ptr [str2]  
    0085383E  push        eax  
    0085383F  push        dword ptr [ebp-30h]  
    00853842  push        ecx  
00853843  lea         ecx,[str1]  
00853846  call        std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)

Both assembly code are very similar as the compiler perform optimization.

Finally, in my opinion, the performance gain is negligible, hence I would really leave it to the developer to decide on which one is the preferred one as both achieve the same outcome (especially when it is release build).

How to use not contains() in xpath?

I need to select every production with a category that doesn't contain "Business"

Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as

//production[category[not(contains(., 'Business'))]]

rather than

//production[not(contains(category, 'Business'))]

The latter selects every production whose first category child doesn't contain "Business". The two XPath expressions will behave differently when a production has no category children, or more than one.

It doesn't make any difference in practice as long as every <production> has exactly one <category> child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

In this particular case (assuming that the Class#forName() didn't throw an exception; your code is namely continuing with running instead of throwing the exception), this SQLException means that Driver#acceptsURL() has returned false for any of the loaded drivers.

And indeed, your JDBC URL is wrong:

String url = "'jdbc:mysql://localhost:3306/mysql";

Remove the singlequote:

String url = "jdbc:mysql://localhost:3306/mysql";

See also:

Directory.GetFiles of certain extension

I would have done using just single line like

List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
      .Where(file => new string[] { ".jpg", ".gif", ".png" }
      .Contains(Path.GetExtension(file)))
      .ToList();

jQuery and AJAX response header

 var geturl;
  geturl = $.ajax({
    type: "GET",
    url: 'http://....',
    success: function () {
      alert("done!"+ geturl.getAllResponseHeaders());
    }
  });

What are enums and why are they useful?

Java lets you restrict variable to having one of only a few predefined values - in other words, one value from an enumerated list. Using enums can help to reduce bug's in your code. Here is an example of enums outside a class:

enums coffeesize{BIG , HUGE , OVERWHELMING }; 
//This semicolon is optional.

This restricts coffeesize to having either: BIG , HUGE , or OVERWHELMING as a variable.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Determine the number of NA values in a column

You can use this to count number of NA or blanks in every column

colSums(is.na(data_set_name)|data_set_name == '')

Best way to check if object exists in Entity Framework?

Why not do it?

var result= ctx.table.Where(x => x.UserName == "Value").FirstOrDefault();

if(result?.field == value)
{
  // Match!
}

Using the "animated circle" in an ImageView while loading stuff

Simply put this block of xml in your activity layout file:

<RelativeLayout
    android:id="@+id/loadingPanel"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="true" />
</RelativeLayout>

And when you finish loading, call this one line:

findViewById(R.id.loadingPanel).setVisibility(View.GONE);

The result (and it spins too):

enter image description here

Which version of Python do I have installed?

In [1]: import sys

In [2]: sys.version
2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]

In [3]: sys.version_info
sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)

In [4]: sys.version_info >= (2,7)
Out[4]: True

In [5]: sys.version_info >= (3,)
Out[5]: False

AngularJS event on window innerWidth size change

We could do it with jQuery:

$(window).resize(function(){
    alert(window.innerWidth);

    $scope.$apply(function(){
       //do something to update current scope based on the new innerWidth and let angular update the view.
    });
});

Be aware that when you bind an event handler inside scopes that could be recreated (like ng-repeat scopes, directive scopes,..), you should unbind your event handler when the scope is destroyed. If you don't do this, everytime when the scope is recreated (the controller is rerun), there will be 1 more handler added causing unexpected behavior and leaking.

In this case, you may need to identify your attached handler:

  $(window).on("resize.doResize", function (){
      alert(window.innerWidth);

      $scope.$apply(function(){
          //do something to update current scope based on the new innerWidth and let angular update the view.
      });
  });

  $scope.$on("$destroy",function (){
      $(window).off("resize.doResize"); //remove the handler added earlier
  });

In this example, I'm using event namespace from jQuery. You could do it differently according to your requirements.

Improvement: If your event handler takes a bit long time to process, to avoid the problem that the user may keep resizing the window, causing the event handlers to be run many times, we could consider throttling the function. If you use underscore, you can try:

$(window).on("resize.doResize", _.throttle(function (){
    alert(window.innerWidth);

    $scope.$apply(function(){
        //do something to update current scope based on the new innerWidth and let angular update the view.
    });
},100));

or debouncing the function:

$(window).on("resize.doResize", _.debounce(function (){
     alert(window.innerWidth);

     $scope.$apply(function(){
         //do something to update current scope based on the new innerWidth and let angular update the view.
     });
},100));

Difference Between throttling and debouncing a function

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

To differentiate the routes, try adding a constraint that id must be numeric:

RouteTable.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         constraints: new { id = @"\d+" }, // Only matches if "id" is one or more digits.
         defaults: new { id = System.Web.Http.RouteParameter.Optional }
         );  

MySQL, Concatenate two columns

You can use php built in CONCAT() for this.

SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;

change filed name as your requirement

then the result is

enter image description here

and if you want to concat same filed using other field which same then

SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1 

then this is output enter image description here

How to add new item to hash

It's as simple as:

irb(main):001:0> hash = {:item1 => 1}
=> {:item1=>1}
irb(main):002:0> hash[:item2] = 2
=> 2
irb(main):003:0> hash
=> {:item1=>1, :item2=>2}

Kendo grid date column not formatting

This is how you do it using ASP.NET:

add .Format("{0:dd/MM/yyyy HH:mm:ss}"); 

    @(Html.Kendo().Grid<AlphaStatic.Domain.ViewModels.AttributeHistoryViewModel>()
            .Name("grid")
            .Columns(columns =>
            {

                columns.Bound(c => c.AttributeName);
                columns.Bound(c => c.UpdatedDate).Format("{0:dd/MM/yyyy HH:mm:ss}");   
            })
            .HtmlAttributes(new { @class = ".big-grid" })
            .Resizable(x => x.Columns(true))
            .Sortable()
            .Filterable()    
            .DataSource(dataSource => dataSource
                .Ajax()
                .Batch(true)
                .ServerOperation(false)
                        .Model(model =>
                        {
                            model.Id(c => c.Id);
                        })       
               .Read(read => read.Action("Read_AttributeHistory", "Attribute",  new { attributeId = attributeId })))
            )

Adding hours to JavaScript Date object?

If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:

_x000D_
_x000D_
//JS
function addHoursToDate(date, hours) {
  return new Date(new Date(date).setHours(date.getHours() + hours));
}

//TS
function addHoursToDate(date: Date, hours: number): Date {
  return new Date(new Date(date).setHours(date.getHours() + hours));
}

let myDate = new Date();

console.log(myDate)
console.log(addHoursToDate(myDate,2))
_x000D_
_x000D_
_x000D_

Difference between two lists

        List<int> list1 = new List<int>();
        List<int> list2 = new List<int>();
        List<int> listDifference = new List<int>();

        foreach (var item1 in list1)
        {
            foreach (var item2 in list2)
            {
                if (item1 != item2)
                    listDifference.Add(item1);
            }
        }

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

There are two ways to achieve that:

  • Use -rpath linker option:

gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib

  • Use LD_LIBRARY_PATH environment variable - put this line in your ~/.bashrc file:

    export LD_LIBRARY_PATH=/home/user/.usr/lib

This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.

For a quick test, you can also do (in bash at least):

LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out

which has the advantage of not changing your library path for everything else.

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

Set the display.max_colwidth option to None (or -1 before version 1.0):

pd.set_option('display.max_colwidth', None)

set_option docs

For example, in iPython, we see that the information is truncated to 50 characters. Anything in excess is ellipsized:

Truncated result

If you set the display.max_colwidth option, the information will be displayed fully:

Non-truncated result

How to do a non-greedy match in grep?

My grep that works after trying out stuff in this thread:

echo "hi how are you " | grep -shoP ".*? "

Just make sure you append a space to each one of your lines

(Mine was a line by line search to spit out words)

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

There is way to do that ;)

Thanks to "http://it.toolbox.com/wiki/index.php/Use_curl_from_PHP_-_processing_response_headers":

<?php

    /**
     * Facebook user photo downloader
     */

    class sfFacebookPhoto {

        private $useragent = 'Loximi sfFacebookPhoto PHP5 (cURL)';
        private $curl = null;
        private $response_meta_info = array();
        private $header = array(
                "Accept-Encoding: gzip,deflate",
                "Accept-Charset: utf-8;q=0.7,*;q=0.7",
                "Connection: close"
            );

        public function __construct() {
            $this->curl = curl_init();
            register_shutdown_function(array($this, 'shutdown'));
        }

        /**
         * Get the real URL for the picture to use after
         */
        public function getRealUrl($photoLink) {
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, false);
            curl_setopt($this->curl, CURLOPT_HEADER, false);
            curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
            curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
            curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->curl, CURLOPT_URL, $photoLink);

            //This assumes your code is into a class method, and
            //uses $this->readHeader as the callback function.
            curl_setopt($this->curl, CURLOPT_HEADERFUNCTION, array(&$this, 'readHeader'));
            $response = curl_exec($this->curl);
            if (!curl_errno($this->curl)) {
                $info = curl_getinfo($this->curl);
                var_dump($info);
                if ($info["http_code"] == 302) {
                    $headers = $this->getHeaders();
                    if (isset($headers['fileUrl'])) {
                        return $headers['fileUrl'];
                    }
                }
            }
            return false;
        }


        /**
         * Download Facebook user photo
         *
         */
        public function download($fileName) {
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($this->curl, CURLOPT_HEADER, false);
            curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
            curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
            curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->curl, CURLOPT_URL, $fileName);
            $response = curl_exec($this->curl);
            $return = false;
            if (!curl_errno($this->curl)) {
                $parts = explode('.', $fileName);
                $ext = array_pop($parts);
                $return = sfConfig::get('sf_upload_dir') . '/tmp/' . uniqid('fbphoto') . '.' . $ext;
                file_put_contents($return, $response);
            }
            return $return;
        }

        /**
         * cURL callback function for reading and processing headers.
         * Override this for your needs.
         *
         * @param object $ch
         * @param string $header
         * @return integer
         */
        private function readHeader($ch, $header) {

            //Extracting example data: filename from header field Content-Disposition
            $filename = $this->extractCustomHeader('Location: ', '\n', $header);
            if ($filename) {
                $this->response_meta_info['fileUrl'] = trim($filename);
            }
            return strlen($header);
        }

        private function extractCustomHeader($start, $end, $header) {
            $pattern = '/'. $start .'(.*?)'. $end .'/';
            if (preg_match($pattern, $header, $result)) {
                return $result[1];
            }
            else {
                return false;
            }
        }

        public function getHeaders() {
            return $this->response_meta_info;
        }

        /**
         * Cleanup resources
         */
        public function shutdown() {
            if($this->curl) {
                curl_close($this->curl);
            }
        }
    }

Want to download a Git repository, what do I need (windows machine)?

I don't want to start a "What's the best unix command line under Windows" war, but have you thought of Cygwin? Git is in the Cygwin package repository.

And you get a lot of beneficial side-effects! (:-)

Could not find a version that satisfies the requirement tensorflow

In case you are using Docker, make sure you have

FROM python:x.y.z

instead of

FROM python:x.y.z-alpine.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

This error is related to web.config file. When web.config is not proper or using some features which is not available in IIS, then this issue will come. In my case, I forgot to install URLRewrite module and was referencing it in web.config. It took some time to find the root cause. I started removing sections one by one and checked, only then i was able to find out the actual issue.

Which port we can use to run IIS other than 80?

Also remember, when running on alternate ports, you need to specify the port on the URL:

http://www.example.com:8080

There may be firewalls or proxy servers to consider depending on your environment.

matrix multiplication algorithm time complexity

The standard way of multiplying an m-by-n matrix by an n-by-p matrix has complexity O(mnp). If all of those are "n" to you, it's O(n^3), not O(n^2). EDIT: it will not be O(n^2) in the general case. But there are faster algorithms for particular types of matrices -- if you know more you may be able to do better.

Limit file format when using <input type="file">?

You can use "accept" attribute as a filter in the file select box. Using "accept" help you filter input files base on their "suffix" or their "meme type"

1.Filter based on suffix: Here "accept" attribute just allow to select files with .jpeg extension.

<input type="file" accept=".jpeg" />

2.Filter based on "file type" Here "accept" attribute just allow to select file with "image/jpeg" type.

<input type="file" accept="image/jpeg" />

Important: We can change or delete the extension of a file, without changing the meme type. For example it is possible to have a file without extension, but the type of this file can be "image/jpeg". So this file can not pass the accept=".jpeg" filter. but it can pass accept="image/jpeg".

3.We can use * to select all kind of a file type. For example below code allow to select all kind of images. for example "image/png" or "image/jpeg" or ... . All of them are allowed.

<input type="file" accept="image/*" /> 

4.We can use cama ( , ) as an "or operator" in select attribute. For example to allow all kind of images or pdf files we can use this code:

<input type="file" accept="image/* , application/pdf" />

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

You can use the following time conversion within SQL like this:

--Convert Time to Integer (Minutes)
DECLARE @timeNow datetime = '14:47'
SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108))

--Convert Minutes to Time
DECLARE @intTime int = (SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108)))
SELECT DATEADD(minute, @intTime, '')

Result: 887 <- Time in minutes and 1900-01-01 14:47:00.000 <-- Minutes to time

Regex for Comma delimited list

I suggest you to do in the following way:

(\d+)(,\s*\d+)*

which would work for a list containing 1 or more elements.

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

I just killed the Oracle processes and re-initiate JBoss. All was fine :)

How to loop over a Class attributes in Java?

Here is a solution which sorts the properties alphabetically and prints them all together with their values:

public void logProperties() throws IllegalArgumentException, IllegalAccessException {
  Class<?> aClass = this.getClass();
  Field[] declaredFields = aClass.getDeclaredFields();
  Map<String, String> logEntries = new HashMap<>();

  for (Field field : declaredFields) {
    field.setAccessible(true);

    Object[] arguments = new Object[]{
      field.getName(),
      field.getType().getSimpleName(),
      String.valueOf(field.get(this))
    };

    String template = "- Property: {0} (Type: {1}, Value: {2})";
    String logMessage = System.getProperty("line.separator")
            + MessageFormat.format(template, arguments);

    logEntries.put(field.getName(), logMessage);
  }

  SortedSet<String> sortedLog = new TreeSet<>(logEntries.keySet());

  StringBuilder sb = new StringBuilder("Class properties:");

  Iterator<String> it = sortedLog.iterator();
  while (it.hasNext()) {
    String key = it.next();
    sb.append(logEntries.get(key));
  }

  System.out.println(sb.toString());
}

Javascript / Chrome - How to copy an object from the webkit inspector as code

So,. I had this issue,. except I got [object object]

I'm sure you could do this with recursion but this worked for me:

Here is what I did in my console:

var object_that_is_not_shallow = $("all_obects_with_this_class_name");
var str = '';
object_that_is_not_shallow.map(function(_,e){
    str += $(e).html();
});
copy(str);

Then paste into your editor.

How do I remove diacritics (accents) from a string in .NET?

This works fine in java.

It basically converts all accented characters into their deAccented counterparts followed by their combining diacritics. Now you can use a regex to strip off the diacritics.

import java.text.Normalizer;
import java.util.regex.Pattern;

public String deAccent(String str) {
    String nfdNormalizedString = Normalizer.normalize(str, Normalizer.Form.NFD); 
    Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
    return pattern.matcher(nfdNormalizedString).replaceAll("");
}

jQuery change event on dropdown

You should've kept that DOM ready function

$(function() {
    $("#projectKey").change(function() {
        alert( $('option:selected', this).text() );
    });
});

The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body> tag

Removing App ID from Developer Connection

Delete application IDs is allowed. Make sure you deleted all certificates, APNS certs and provisioning profiles associated with your application. Then go to Identitifies --> App IDs, select the application ID, Edit and Delete button should be enabled.

What exactly is Python's file.flush() doing?

It flushes the internal buffer, which is supposed to cause the OS to write out the buffer to the file.[1] Python uses the OS's default buffering unless you configure it do otherwise.

But sometimes the OS still chooses not to cooperate. Especially with wonderful things like write-delays in Windows/NTFS. Basically the internal buffer is flushed, but the OS buffer is still holding on to it. So you have to tell the OS to write it to disk with os.fsync() in those cases.

[1] http://docs.python.org/library/stdtypes.html

Installing NumPy and SciPy on 64-bit Windows (with Pip)

Follow these steps:

  1. Open CMD as administrator
  2. Enter this command : cd..
  3. cd..
  4. cd Program Files\Python38\Scripts
  5. Download the package you want and put it in Python38\Scripts folder.
  6. pip install packagename.whl
  7. Done

You can write your python version instead of "38"

How to add a list item to an existing unordered list?

This is another one

$("#header ul li").last().html('<li> Menu 5 </li>');

How to filter Android logcat by application?

According to http://developer.android.com/tools/debugging/debugging-log.html:

Here's an example of a filter expression that suppresses all log messages except those with the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above:

adb logcat ActivityManager:I MyApp:D *:S

The final element in the above expression, *:S, sets the priority level for all tags to "silent", thus ensuring only log messages with "View" and "MyApp" are displayed.

  • V — Verbose (lowest priority)
  • D — Debug
  • I — Info
  • W — Warning
  • E — Error
  • F — Fatal
  • S — Silent (highest priority, on which nothing is ever printed)

Multiline strings in VB.NET

I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value

Why not inherit from List<T>?

It depends on the context

When you consider your team as a list of players, you are projecting the "idea" of a foot ball team down to one aspect: You reduce the "team" to the people you see on the field. This projection is only correct in a certain context. In a different context, this might be completely wrong. Imagine you want to become a sponsor of the team. So you have to talk to the managers of the team. In this context the team is projected to the list of its managers. And these two lists usually don't overlap very much. Other contexts are the current versus the former players, etc.

Unclear semantics

So the problem with considering a team as a list of its players is that its semantic depends on the context and that it cannot be extended when the context changes. Additionally it is hard to express, which context you are using.

Classes are extensible

When you using a class with only one member (e.g. IList activePlayers), you can use the name of the member (and additionally its comment) to make the context clear. When there are additional contexts, you just add an additional member.

Classes are more complex

In some cases it might be overkill to create an extra class. Each class definition must be loaded through the classloader and will be cached by the virtual machine. This costs you runtime performance and memory. When you have a very specific context it might be OK to consider a football team as a list of players. But in this case, you should really just use a IList , not a class derived from it.

Conclusion / Considerations

When you have a very specific context, it is OK to consider a team as a list of players. For example inside a method it is completely OK to write:

IList<Player> footballTeam = ...

When using F#, it can even be OK to create a type abbreviation:

type FootballTeam = IList<Player>

But when the context is broader or even unclear, you should not do this. This is especially the case when you create a new class whose context in which it may be used in the future is not clear. A warning sign is when you start to add additional attributes to your class (name of the team, coach, etc.). This is a clear sign that the context where the class will be used is not fixed and will change in the future. In this case you cannot consider the team as a list of players, but you should model the list of the (currently active, not injured, etc.) players as an attribute of the team.

What does the 'standalone' directive mean in XML?

standalone describes if the current XML document depends on an external markup declaration.

W3C describes its purpose in "Extensible Markup Language (XML) 1.0 (Fifth Edition)":

Convert NSArray to NSString in Objective-C

I recently found a really good tutorial on Objective-C Strings:

http://ios-blog.co.uk/tutorials/objective-c-strings-a-guide-for-beginners/

And I thought that this might be of interest:

If you want to split the string into an array use a method called componentsSeparatedByString to achieve this:

NSString *yourString = @"This is a test string";
    NSArray *yourWords = [myString componentsSeparatedByString:@" "];

    // yourWords is now: [@"This", @"is", @"a", @"test", @"string"]

if you need to split on a set of several different characters, use NSString’s componentsSeparatedByCharactersInSet:

NSString *yourString = @"Foo-bar/iOS-Blog";
NSArray *yourWords = [myString componentsSeparatedByCharactersInSet:
                  [NSCharacterSet characterSetWithCharactersInString:@"-/"]
                ];

// yourWords is now: [@"Foo", @"bar", @"iOS", @"Blog"]

Note however that the separator string can’t be blank. If you need to separate a string into its individual characters, just loop through the length of the string and convert each char into a new string:

NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
    NSString *ichar  = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
    [characters addObject:ichar];
}

Check if input is number or letter javascript

Use Regular Expression to match for only letters. It's also good to have knowledge about, if you ever need to do something more complicated, like make sure it's a certain count of numbers.

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    var regex=/^[a-zA-Z]+$/;
    if (!x.match(regex))
    {
        alert("Must input string");
        return false;
    }
}

Even better would be to deny anything but numbers:

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    var regex=/^[0-9]+$/;
    if (x.match(regex))
    {
        alert("Must input numbers");
        return false;
    }
}

Make UINavigationBar transparent

Another Way That worked for me is to Subclass UINavigationBar And leave the drawRect Method empty !!

@IBDesignable class MONavigationBar: UINavigationBar {


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
    // Drawing code
}}

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

How can I create an executable JAR with dependencies using Maven?

This is the best way i found:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
      <archive>
        <manifest>
        <addClasspath>true</addClasspath>
        <mainClass>com.myDomain.etc.MainClassName</mainClass>
        <classpathPrefix>dependency-jars/</classpathPrefix>
        </manifest>
      </archive>
    </configuration>
  </plugin>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.5.1</version>
    <executions>
      <execution>
        <id>copy-dependencies</id>
        <phase>package</phase>
        <goals>
            <goal>copy-dependencies</goal>
        </goals>
        <configuration>
            <outputDirectory>
               ${project.build.directory}/dependency-jars/
            </outputDirectory>
        </configuration>
      </execution>
    </executions>
  </plugin>

With this configuration, all dependencies will be located in /dependency-jars. My application has no Main class, just context ones, but one of my dependencies do have a Main class (com.myDomain.etc.MainClassName) that starts the JMX server, and receives a start or a stop parameter. So with this i was able to start my application like this:

java -jar ./lib/TestApp-1.0-SNAPSHOT.jar start

I wait it be useful for you all.

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

Like thousands of people, I'm looking for this question:
Can run multiple queries simultaneously, and if there was one error, none would run I went to this page everywhere
But although the friends here gave good answers, these answers were not good for my problem
So I wrote a function that works well and has almost no problem with sql Injection.
It might be helpful for those who are looking for similar questions so I put them here to use

function arrayOfQuerys($arrayQuery)
{
    $mx = true;
    $conn->beginTransaction();
    try {
        foreach ($arrayQuery AS $item) {
            $stmt = $conn->prepare($item["query"]);
            $stmt->execute($item["params"]);
            $result = $stmt->rowCount();
            if($result == 0)
                $mx = false;
         }
         if($mx == true)
             $conn->commit();
         else
             $conn->rollBack();
    } catch (Exception $e) {
        $conn->rollBack();
        echo "Failed: " . $e->getMessage();
    }
    return $mx;
}

for use(example):

 $arrayQuery = Array(
    Array(
        "query" => "UPDATE test SET title = ? WHERE test.id = ?",
        "params" => Array("aa1", 1)
    ),
    Array(
        "query" => "UPDATE test SET title = ? WHERE test.id = ?",
        "params" => Array("bb1", 2)
    )
);
arrayOfQuerys($arrayQuery);

and my connection:

    try {
        $options = array(
            //For updates where newvalue = oldvalue PDOStatement::rowCount()   returns zero. You can use this:
            PDO::MYSQL_ATTR_FOUND_ROWS => true
        );
        $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password, $options);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo "Error connecting to SQL Server: " . $e->getMessage();
    }

Note:
This solution helps you to run multiple statement together,
If an incorrect a statement occurs, it does not execute any other statement

SQL Inner-join with 3 tables?

SELECT 
A.P_NAME AS [INDIVIDUAL NAME],B.F_DETAIL AS [INDIVIDUAL FEATURE],C.PL_PLACE AS [INDIVIDUAL LOCATION]
FROM 
[dbo].[PEOPLE] A
INNER JOIN 
[dbo].[FEATURE] B ON A.P_FEATURE = B.F_ID
INNER JOIN 
[dbo].[PEOPLE_LOCATION] C ON A.P_LOCATION = C.PL_ID

How can I give an imageview click effect like a button on Android?

You can Override setPressed in the ImageView and do the color filtering there, instead of creating onTouchEvent listeners:

@Override
public void setPressed(boolean pressed) {
    super.setPressed(pressed);

    if(getDrawable() == null)
        return;

    if(pressed) {
        getDrawable().setColorFilter(0x44000000, PorterDuff.Mode.SRC_ATOP);
        invalidate();
    }
    else {
        getDrawable().clearColorFilter();
        invalidate();
    }
}

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

How can I disable an <option> in a <select> based on its value in JavaScript?

For some reason other answers are unnecessarily complex, it's easy to do it in one line in pure JavaScript:

Array.prototype.find.call(selectElement.options, o => o.value === optionValue).disabled = true;

or

selectElement.querySelector('option[value="'+optionValue.replace(/["\\]/g, '\\$&')+'"]').disabled = true;

The performance depends on the number of the options (the more the options, the slower the first one) and whether you can omit the escaping (the replace call) from the second one. Also the first one uses Array.find and arrow functions that are not available in IE11.

Install dependencies globally and locally using package.json

New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies section of your package.json. Anytime you use something from scripts in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.

For example:

npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally

Then in package.json:

// devDependencies has mocha and babel now

"scripts": {
  "test": "mocha",
  "build": "babel -d lib src",
  "prepublish": "babel -d lib src"
}

Then at your command prompt you can run:

npm run build # finds babel
npm test # finds mocha

npm publish # will run babel first

But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:

"scripts": {
  "preinstall": "npm i -g themodule"
}

So actually my npm install executes npm install again .. which is weird but seems to work.

Note: you might have issues if you are using the most common setup for npm where global Node package installs required sudo. One option is to change your npm configuration so this isn't necessary:

npm config set prefix ~/npm, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH to your ~/.bashrc.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I had similar issue and no errors shown in Compilation. I have tried to clean and rebuild without any success. I managed to find the issue by using Invalidate Caches/Restart from file Menu, after the restart I managed to see the compilation error.

enter image description here

What is the best java image processing library/approach?

I'm not a Java guy, but OpenCV is great for my needs. Not sure if it fits yours. Here's a Java port, I think: http://docs.opencv.org/2.4/doc/tutorials/introduction/desktop_java/java_dev_intro.html

How to select data of a table from another database in SQL Server?

You need sp_addlinkedserver()

http://msdn.microsoft.com/en-us/library/ms190479.aspx

Example:

exec sp_addlinkedserver @server = 'test'

then

select * from [server].[database].[schema].[table]

In your example:

select * from [test].[testdb].[dbo].[table]

How can I limit the visible options in an HTML <select> dropdown?

the size attribute matters, if the size=5 then first 5 items will be shown and for others you need to scroll down..

<select name="numbers" size="5">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
</select>

Can I find events bound on an element with jQuery?

You can now simply get a list of event listeners bound to an object by using the javascript function getEventListeners().

For example type the following in the dev tools console:

// Get all event listners bound to the document object
getEventListeners(document);

Auto line-wrapping in SVG text

The textPath may be good for some case.

<svg width="200" height="200"
    xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
 <defs>
  <!-- define lines for text lies on -->
  <path id="path1" d="M10,30 H190 M10,60 H190 M10,90 H190 M10,120 H190"></path>
 </defs>
 <use xlink:href="#path1" x="0" y="35" stroke="blue" stroke-width="1" />
 <text transform="translate(0,35)" fill="red" font-size="20">
  <textPath xlink:href="#path1">This is a long long long text ......</textPath>
 </text>
</svg>

Replacing some characters in a string with another character

Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _:

$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN

Notice that the +(pattern) pattern requires extended pattern matching, turned on with

shopt -s extglob

Alternatively, with the -s ("squeeze") option of tr:

$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN

Write a file on iOS

Swift

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as! String
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
}

func loadFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as! String
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String = String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding, error: nil)!
    println(content)
}

Swift 2

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    do{
        try content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding)
    }catch _ {

    }

}

func loadFile()->String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] 
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String
    do{
       content = try String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding)
    }catch _{
        content=""
    }
    return content;
}

Swift 3

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    do{
        try content.write(toFile: fileName, atomically: false, encoding: String.Encoding.utf8)
    }catch _ {

    }

}

func loadFile()->String {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String
    do{
        content = try String(contentsOfFile: fileName, encoding: String.Encoding.utf8)
    } catch _{
        content=""
    }
    return content;
}

How to check if a Ruby object is a Boolean

There is no Boolean class in Ruby, the only way to check is to do what you're doing (comparing the object against true and false or the class of the object against TrueClass and FalseClass). Can't think of why you would need this functionality though, can you explain? :)

If you really need this functionality however, you can hack it in:

module Boolean; end
class TrueClass; include Boolean; end
class FalseClass; include Boolean; end

true.is_a?(Boolean) #=> true
false.is_a?(Boolean) #=> true

Relative frequencies / proportions with dplyr

Here is a general function implementing Henrik's solution on dplyr 0.7.1.

freq_table <- function(x, 
                       group_var, 
                       prop_var) {
  group_var <- enquo(group_var)
  prop_var  <- enquo(prop_var)
  x %>% 
    group_by(!!group_var, !!prop_var) %>% 
    summarise(n = n()) %>% 
    mutate(freq = n /sum(n)) %>% 
    ungroup
}

How to update attributes without validation

Yo can use:

a.update_column :state, a.state

Check: http://apidock.com/rails/ActiveRecord/Persistence/update_column

Updates a single attribute of an object, without calling save.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

How to POST the data from a modal form of Bootstrap?

I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.

<form name="paymentitrform" id="paymentitrform" class="payment"
                    method="post"
                    action="abc.php">
          <input name="email" value="" placeholder="email" />
          <input type="hidden" name="planamount" id="planamount" value="0">
                                <input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
                                    name="planform">

                </form>

You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button

    function form_submit() {
        document.getElementById("paymentitrform").submit();
   }  

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Use This code ..to change action bar background color. open "res/values/themes.xml" (if not present, create it) and add

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- the theme applied to the application or activity -->
<style name="CustomActionBarTheme"
       parent="@android:style/Theme.Holo.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
</style>
 <!-- ActionBar styles -->
<style name="MyActionBar"
       parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
    <item name="android:background">@drawable/actionbar_background</item>
</style>

Note : this code works for android 3.0 and higher versions only

CASCADE DELETE just once

I wrote a (recursive) function to delete any row based on its primary key. I wrote this because I did not want to create my constraints as "on delete cascade". I wanted to be able to delete complex sets of data (as a DBA) but not allow my programmers to be able to cascade delete without thinking through all of the repercussions. I'm still testing out this function, so there may be bugs in it -- but please don't try it if your DB has multi column primary (and thus foreign) keys. Also, the keys all have to be able to be represented in string form, but it could be written in a way that doesn't have that restriction. I use this function VERY SPARINGLY anyway, I value my data too much to enable the cascading constraints on everything. Basically this function is passed in the schema, table name, and primary value (in string form), and it will start by finding any foreign keys on that table and makes sure data doesn't exist-- if it does, it recursively calls itsself on the found data. It uses an array of data already marked for deletion to prevent infinite loops. Please test it out and let me know how it works for you. Note: It's a little slow. I call it like so: select delete_cascade('public','my_table','1');

create or replace function delete_cascade(p_schema varchar, p_table varchar, p_key varchar, p_recursion varchar[] default null)
 returns integer as $$
declare
    rx record;
    rd record;
    v_sql varchar;
    v_recursion_key varchar;
    recnum integer;
    v_primary_key varchar;
    v_rows integer;
begin
    recnum := 0;
    select ccu.column_name into v_primary_key
        from
        information_schema.table_constraints  tc
        join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
        and tc.constraint_type='PRIMARY KEY'
        and tc.table_name=p_table
        and tc.table_schema=p_schema;

    for rx in (
        select kcu.table_name as foreign_table_name, 
        kcu.column_name as foreign_column_name, 
        kcu.table_schema foreign_table_schema,
        kcu2.column_name as foreign_table_primary_key
        from information_schema.constraint_column_usage ccu
        join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema 
        join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
        join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
        join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
        where ccu.table_name=p_table  and ccu.table_schema=p_schema
        and TC.CONSTRAINT_TYPE='FOREIGN KEY'
        and tc2.constraint_type='PRIMARY KEY'
)
    loop
        v_sql := 'select '||rx.foreign_table_primary_key||' as key from '||rx.foreign_table_schema||'.'||rx.foreign_table_name||'
            where '||rx.foreign_column_name||'='||quote_literal(p_key)||' for update';
        --raise notice '%',v_sql;
        --found a foreign key, now find the primary keys for any data that exists in any of those tables.
        for rd in execute v_sql
        loop
            v_recursion_key=rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name||'='||rd.key;
            if (v_recursion_key = any (p_recursion)) then
                --raise notice 'Avoiding infinite loop';
            else
                --raise notice 'Recursing to %,%',rx.foreign_table_name, rd.key;
                recnum:= recnum +delete_cascade(rx.foreign_table_schema::varchar, rx.foreign_table_name::varchar, rd.key::varchar, p_recursion||v_recursion_key);
            end if;
        end loop;
    end loop;
    begin
    --actually delete original record.
    v_sql := 'delete from '||p_schema||'.'||p_table||' where '||v_primary_key||'='||quote_literal(p_key);
    execute v_sql;
    get diagnostics v_rows= row_count;
    --raise notice 'Deleting %.% %=%',p_schema,p_table,v_primary_key,p_key;
    recnum:= recnum +v_rows;
    exception when others then recnum=0;
    end;

    return recnum;
end;
$$
language PLPGSQL;

Get operating system info

If you want very few info like a class in your html for common browsers for instance, you could use:

function get_browser()
{
    $browser = '';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
    elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];

    return $browser;
}

which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.

How do I make a list of data frames?

I consider myself a complete newbie, but I think I have an extremely simple answer to one of the original subquestions that has not been stated here: accessing the data frames, or parts of it.

Let's start by creating the list with data frames as was stated above:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))

d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))

my.list <- list(d1, d2)

Then, if you want to access a specific value in one of the data frames, you can do so by using the double brackets sequentially. The first set gets you into the data frame, and the second set gets you to the specific coordinates:

my.list[[1]][[3,2]]

[1] 6

Why are there two ways to unstage a file in Git?

Let's say you stage a whole directory via git add <folder>, but you want to exclude a file from the staged list (i.e. the list that generates when running git status) and keep the modifications within the excluded file (you were working on something and it's not ready for commit, but you don't want to lose your work...). You could simply use:

git reset <file>

When you run git status, you will see that whatever file(s) you reset are unstaged and the rest of the files you added are still in the staged list.

How can I display a JavaScript object?

Simply use

JSON.stringify(obj)

Example

var args_string = JSON.stringify(obj);
console.log(args_string);

Or

alert(args_string);

Also, note in javascript functions are considered as objects.

As an extra note :

Actually you can assign new property like this and access it console.log or display it in alert

foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);

Java 8 Iterable.forEach() vs foreach loop

I feel that I need to extend my comment a bit...

About paradigm\style

That's probably the most notable aspect. FP became popular due to what you can get avoiding side-effects. I won't delve deep into what pros\cons you can get from this, since this is not related to the question.

However, I will say that the iteration using Iterable.forEach is inspired by FP and rather result of bringing more FP to Java (ironically, I'd say that there is no much use for forEach in pure FP, since it does nothing except introducing side-effects).

In the end I would say that it is rather a matter of taste\style\paradigm you are currently writing in.

About parallelism.

From performance point of view there is no promised notable benefits from using Iterable.forEach over foreach(...).

According to official docs on Iterable.forEach :

Performs the given action on the contents of the Iterable, in the order elements occur when iterating, until all elements have been processed or the action throws an exception.

... i.e. docs pretty much clear that there will be no implicit parallelism. Adding one would be LSP violation.

Now, there are "parallell collections" that are promised in Java 8, but to work with those you need to me more explicit and put some extra care to use them (see mschenk74's answer for example).

BTW: in this case Stream.forEach will be used, and it doesn't guarantee that actual work will be done in parallell (depends on underlying collection).

UPDATE: might be not that obvious and a little stretched at a glance but there is another facet of style and readability perspective.

First of all - plain old forloops are plain and old. Everybody already knows them.

Second, and more important - you probably want to use Iterable.forEach only with one-liner lambdas. If "body" gets heavier - they tend to be not-that readable. You have 2 options from here - use inner classes (yuck) or use plain old forloop. People often gets annoyed when they see the same things (iteratins over collections) being done various vays/styles in the same codebase, and this seems to be the case.

Again, this might or might not be an issue. Depends on people working on code.

$date + 1 year?

I prefer the OO approach:

$date = new \DateTimeImmutable('today'); //'today' gives midnight, leave blank for current time.
$futureDate = $date->add(\DateInterval::createFromDateString('+1 Year'))

Use DateTimeImmutable otherwise you will modify the original date too! more on DateTimeImmutable: http://php.net/manual/en/class.datetimeimmutable.php


If you just want from todays date then you can always do:

new \DateTimeImmutable('-1 Month');

HTML5 Video autoplay on iPhone

iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.

Why is list initialization (using curly braces) better than the alternatives?

There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:

  • If the object I'm creating conceptually holds the values I'm passing in the constructor (e.g. containers, POD structs, atomics, smart pointers etc.), then I'm using the braces.
  • If the constructor resembles a normal function call (it performs some more or less complex operations that are parametrized by the arguments) then I'm using the normal function call syntax.
  • For default initialization I always use curly braces.
    For one, that way I'm always sure that the object gets initialized irrespective of whether it e.g. is a "real" class with a default constructor that would get called anyway or a builtin / POD type. Second it is - in most cases - consistent with the first rule, as a default initialized object often represents an "empty" object.

In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).

It e.g. fits nicely with standard library-types like std::vector:

vector<int> a{10,20};   //Curly braces -> fills the vector with the arguments

vector<int> b(10,20);   //Parentheses -> uses arguments to parametrize some functionality,                          
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.

vector<int> d{};      //empty braces -> default constructs vector, which is equivalent
                      //to a vector that is filled with zero elements

Play local (hard-drive) video file with HTML5 video tag?

Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4

<div id="videoDiv">
     <video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
    </div>
<!--End videoDiv-->

Not an ideal solution but worked for me.

How to use Visual Studio C++ Compiler?

In Visual Studio, you can't just open a .cpp file and expect it to run. You must create a project first, or open the .cpp in some existing project.

In your case, there is no project, so there is no project to build.

Go to File --> New --> Project --> Visual C++ --> Win32 Console Application. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".

Then, You can add .cpp files you created outside the Visual Studio by right clicking in the Solution explorer on folder icon "Source" and Add->Existing Item.

Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.

Then you can press ctrl+F5 to compile without debugging and can see output on console window.

How to get Rails.logger printing to the console/stdout when running rspec?

A solution that I like, because it keeps rspec output separate from actual rails log output, is to do the following:

  • Open a second terminal window or tab, and arrange it so that you can see both the main terminal you're running rspec on as well as the new one.
  • Run a tail command in the second window so you see the rails log in the test environment. By default this can be like $ tail -f $RAILS_APP_DIR/logs/test.log or tail -f $RAILS_APP_DIR\logs\test.log for Window users
  • Run your rspec suites

If you are running a multi-pane terminal like iTerm, this becomes even more fun and you have rspec and the test.log output side by side.

Fatal error: Out of memory, but I do have plenty of memory (PHP)

I had a similar problem with PHP:

1) Check your error logs. Eliminate EVERY error before continuing. 2) Consider modifying your apache configuration to eliminate unused modules - this will reduce the footprint needed by PHP - here's a great link for this - it's specific to Wordpress but should still be very useful http://thethemefoundry.com/blog/optimize-apache-wordpress/

To give you an idea of the kind of bug I found, I had some code that was trying to post content to Facebook, Facebook then modified their API so this broke, I also used a 'content expirator' which basically meant that it kept retrying to post this content to Facebook and leaving loads of objects lying in memory.

How to change a package name in Eclipse?

"AndroidManifest" file not changed for me and i change package name manually.

nginx: send all requests to a single html page

This worked for me:

location / {
    alias /path/to/my/indexfile/;
    try_files $uri /index.html;
}

This allowed me to create a catch-all URL for a javascript single-page app. All static files like css, fonts, and javascript built by npm run build will be found if they are in the same directory as index.html.

If the static files were in another directory, for some reason, you'd also need something like:

# Static pages generated by "npm run build"
location ~ ^/css/|^/fonts/|^/semantic/|^/static/ {
    alias /path/to/my/staticfiles/;
}

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

(updated on 3-29-2019 to use the https instead of ssh, so you don't need to use ssh keys)

It seems like for BitBucket, you do have to create a repo online first. Using the instructions from Atlassian, simply create a new BitBucket repository, copy the repository url to the clipboard, and then add that repository as a new remote to your local repository (full steps below):

Get Repo URL

  1. in your BitBucket repo, choose "Clone" on the top-right
  2. choose "HTTPS" instead of "SSH" in the top-right of the dialog
  3. it should show your repo url in the form git clone <repository url>

Add Remote Using CLI

  1. cd /path/to/my/repo
  2. git remote add origin https://bitbucket.org/<username>/<reponame>.git
  3. git push -u origin --all

Add Remote Using SourceTree

  1. Repository>Add Remote...
  2. Paste the BitBucket repository url (https://bitbucket.org/<username>/<reponame>.git)

Old Method: Creating & Registering SSH Keys

(this method is if you use the ssh url instead of the https url, which looks like ssh://[email protected]/<username>/<reponame>.git. I recommend just using https)

BitBucket is great for private repos, but you'll need to set up an ssh key to authorize your computer to work with your BitBucket account. Luckily Sourcetree makes it relatively simple:

Creating a Key In SourceTree:

  1. In Tools>Options, make sure SSH Client: is set to PuTTY/Plink under the General tab
  2. Select Tools>Create or Import SSH Keys
  3. In the popup window, click Generate and move your mouse around to give randomness to the key generator
  4. You should get something like whats shown in the screenshot below. Copy the public key (highlighted in blue) to your clipboard

    putty

  5. Click Save private Key and Save public key to save your keys to wherever you choose (e.g. to <Home Dir>/putty/ssk-key.ppk and <Home Dir>/putty/ssh-key.pub respectively) before moving on to the next section

Registering The Key In BitBucket

  1. Log in to your BitBucket account, and on the top right, click your profile picture and click Settings
  2. Go to the SSH Keys tab on the left sidebar
  3. Click Add SSH Key, give it a name, and paste the public key you copied in step 4 of the previous section

That's it! You should now be able to push/pull to your BitBucket private repos. Your keys aren't just for Git either, many services use ssh keys to identify users, and the best part is you only need one. If you ever lose your keys (e.g. when changing computers), just follow the steps to create and register a new one.

Sidenote: Creating SSH Keys using CLI

Just follow this tutorial

How do I pass environment variables to Docker containers?

You can pass environment variables to your containers with the -e flag.

An example from a startup script:

sudo docker run -d -t -i -e REDIS_NAMESPACE='staging' \ 
-e POSTGRES_ENV_POSTGRES_PASSWORD='foo' \
-e POSTGRES_ENV_POSTGRES_USER='bar' \
-e POSTGRES_ENV_DB_NAME='mysite_staging' \
-e POSTGRES_PORT_5432_TCP_ADDR='docker-db-1.hidden.us-east-1.rds.amazonaws.com' \
-e SITE_URL='staging.mysite.com' \
-p 80:80 \
--link redis:redis \  
--name container_name dockerhub_id/image_name

Or, if you don't want to have the value on the command-line where it will be displayed by ps, etc., -e can pull in the value from the current environment if you just give it without the =:

sudo PASSWORD='foo' docker run  [...] -e PASSWORD [...]

If you have many environment variables and especially if they're meant to be secret, you can use an env-file:

$ docker run --env-file ./env.list ubuntu bash

The --env-file flag takes a filename as an argument and expects each line to be in the VAR=VAL format, mimicking the argument passed to --env. Comment lines need only be prefixed with #

How to generate unique id in MySQL?

crypt() as suggested and store salt in some configuration file, Start salt from 1 and if you find duplicate move to next value 2. You can use 2 chars, but that will give you enough combination for salt.

You can generate string from openssl_random_pseudo_bytes(8). So this should give random and short string (11 char) when run with crypt().

Remove salt from result and there will be only 11 chars that should be enough random for 100+ millions if you change salt on every fail of random.

How can I change the color of pagination dots of UIPageControl?

pageControl.pageIndicatorTintColor = [UIColor redColor];
pageControl.currentPageIndicatorTintColor = [UIColor redColor];

works for iOS6

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

I had the same problem today. My persistence.xml was in the wrong location. I had to put it in the following path:

project/src/main/resources/META-INF/persistence.xml

How to make PyCharm always show line numbers

PyCharm Version 3.4.1(For all files in the project):

File -> Preferences -> Editor (IDE Settings) -> Appearance -> mark 'Show line numbers'

PyCharm Version 3.4.1(only for existing file in the project):

View -> Active Editor -> Show Line Numbers

image

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

How to detect idle time in JavaScript elegantly?

I know it a relatively old question, but I had the same issue and I found a quite good solution.

I used: jquery.idle and I only needed to do:

$(document).idle({
  onIdle: function(){
    alert('You did nothing for 5 seconds');
  },
  idle: 5000
})

See JsFiddle demo.

(Just for Info: see this for back-end event tracking Leads browserload)

How to Auto-start an Android Application?

Edit your AndroidManifest.xml to add RECEIVE_BOOT_COMPLETED permission

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Edit your AndroidManifest.xml application-part for below Permission

<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

Now write below in Activity.

public class BootUpReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MyActivity.class);  
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);  
    }
}

how to use LIKE with column name

...
WHERE table1.x LIKE table2.y + '%'

Get all files and directories in specific path fast

There is a long history of the .NET file enumeration methods being slow. The issue is there is not an instantaneous way of enumerating large directory structures. Even the accepted answer here has its issues with GC allocations.

The best I've been able to do is wrapped up in my library and exposed as the FindFile (source) class in the CSharpTest.Net.IO namespace. This class can enumerate files and folders without unneeded GC allocations and string marshalling.

The usage is simple enough, and the RaiseOnAccessDenied property will skip the directories and files the user does not have access to:

    private static long SizeOf(string directory)
    {
        var fcounter = new CSharpTest.Net.IO.FindFile(directory, "*", true, true, true);
        fcounter.RaiseOnAccessDenied = false;

        long size = 0, total = 0;
        fcounter.FileFound +=
            (o, e) =>
            {
                if (!e.IsDirectory)
                {
                    Interlocked.Increment(ref total);
                    size += e.Length;
                }
            };

        Stopwatch sw = Stopwatch.StartNew();
        fcounter.Find();
        Console.WriteLine("Enumerated {0:n0} files totaling {1:n0} bytes in {2:n3} seconds.",
                          total, size, sw.Elapsed.TotalSeconds);
        return size;
    }

For my local C:\ drive this outputs the following:

Enumerated 810,046 files totaling 307,707,792,662 bytes in 232.876 seconds.

Your mileage may vary by drive speed, but this is the fastest method I've found of enumerating files in managed code. The event parameter is a mutating class of type FindFile.FileFoundEventArgs so be sure you do not keep a reference to it as it's values will change for each event raised.

Failed to load resource: net::ERR_INSECURE_RESPONSE

If you're developing, and you're developing with a Windows machine, simply add localhost as a Trusted Site.

And yes, per DarrylGriffiths' comment, although it may look like you're adding an Internet Explorer setting...

I believe those are Windows rather than IE settings. Although MS tend to assume that they're only IE (hence the alert next to "Enable Protected Mode" that it requries restarted IE)...

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

if you get an error as Parameter 'element' implicitly has an 'any' type.Vetur(7006) in vueJs

with the error:

 exportColumns.forEach(element=> {
      if (element.command !== undefined) {
        let d = element.command.findIndex(x => x.name === "destroy");

you can fixed it by defining thoes variables as any as follow.

corrected code:

exportColumns.forEach((element: any) => {
      if (element.command !== undefined) {
        let d = element.command.findIndex((x: any) => x.name === "destroy");

2D character array initialization in C

C strings are enclosed in double quotes:

const char *options[2][100];

options[0][0] = "test1";
options[1][0] = "test2";

Re-reading your question and comments though I'm guessing that what you really want to do is this:

const char *options[2] = { "test1", "test2" };

Can I use DIV class and ID together in CSS?

Of course you can.

Your HTML there is just fine. To style the elements with css you can use the following approaches:

#y {
    ...
}

.x {
    ...
}

#y.x {
    ...
}

Also you can add as many classes as you wish to your element

<div id="id" class="classA classB classC ...">
</div>

And you can style that element using a selector with any combination of the classes and id. For example:

#id.classA.classB.classC {
     ...
}

#id.classC {
}

How do I request a file but not save it with Wget?

Curl does that by default without any parameters or flags, I would use it for your purposes:

curl $url > /dev/null 2>&1

Curl is more about streams and wget is more about copying sites based on this comparison.

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

Convert from MySQL datetime to another format with PHP

Depending on your MySQL datetime configuration. Typically: 2011-12-31 07:55:13 format. This very simple function should do the magic:

function datetime()
{
    return date( 'Y-m-d H:i:s', time());
}

echo datetime(); // display example: 2011-12-31 07:55:13

Or a bit more advance to match the question.

function datetime($date_string = false)
{
    if (!$date_string)
    {
        $date_string = time();
    }
    return date("Y-m-d H:i:s", strtotime($date_string));
}

Using Sockets to send and receive data

    //Client

    import java.io.*;
    import java.net.*;

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

        String hostname = "localhost";
        int port = 6789;

        // declaration section:
        // clientSocket: our client socket
        // os: output stream
        // is: input stream

            Socket clientSocket = null;  
            DataOutputStream os = null;
            BufferedReader is = null;

        // Initialization section:
        // Try to open a socket on the given port
        // Try to open input and output streams

            try {
                clientSocket = new Socket(hostname, port);
                os = new DataOutputStream(clientSocket.getOutputStream());
                is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: " + hostname);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: " + hostname);
            }

        // If everything has been initialized then we want to write some data
        // to the socket we have opened a connection to on the given port

        if (clientSocket == null || os == null || is == null) {
            System.err.println( "Something is wrong. One variable is null." );
            return;
        }

        try {
            while ( true ) {
            System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String keyboardInput = br.readLine();
            os.writeBytes( keyboardInput + "\n" );

            int n = Integer.parseInt( keyboardInput );
            if ( n == 0 || n == -1 ) {
                break;
            }

            String responseLine = is.readLine();
            System.out.println("Server returns its square as: " + responseLine);
            }

            // clean up:
            // close the output stream
            // close the input stream
            // close the socket

            os.close();
            is.close();
            clientSocket.close();   
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
        }           
    }





//Server




import java.io.*;
import java.net.*;

public class Server1 {
    public static void main(String args[]) {
    int port = 6789;
    Server1 server = new Server1( port );
    server.startServer();
    }

    // declare a server socket and a client socket for the server

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int port;

    public Server1( int port ) {
    this.port = port;
    }

    public void stopServer() {
    System.out.println( "Server cleaning up." );
    System.exit(0);
    }

    public void startServer() {
    // Try to open a server socket on the given port
    // Note that we can't choose a port less than 1024 if we are not
    // privileged users (root)

        try {
        echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
        System.out.println(e);
        }   

    System.out.println( "Waiting for connections. Only one connection is allowed." );

    // Create a socket object from the ServerSocket to listen and accept connections.
    // Use Server1Connection to process the connection.

    while ( true ) {
        try {
        clientSocket = echoServer.accept();
        Server1Connection oneconnection = new Server1Connection(clientSocket, this);
        oneconnection.run();
        }   
        catch (IOException e) {
        System.out.println(e);
        }
    }
    }
}

class Server1Connection {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    Server1 server;

    public Server1Connection(Socket clientSocket, Server1 server) {
    this.clientSocket = clientSocket;
    this.server = server;
    System.out.println( "Connection established with: " + clientSocket );
    try {
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        os = new PrintStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.out.println(e);
    }
    }

    public void run() {
        String line;
    try {
        boolean serverStop = false;

            while (true) {
                line = is.readLine();
        System.out.println( "Received " + line );
                int n = Integer.parseInt(line);
        if ( n == -1 ) {
            serverStop = true;
            break;
        }
        if ( n == 0 ) break;
                os.println("" + n*n ); 
            }

        System.out.println( "Connection closed." );
            is.close();
            os.close();
            clientSocket.close();

        if ( serverStop ) server.stopServer();
    } catch (IOException e) {
        System.out.println(e);
    }
    }
}

Where is svcutil.exe in Windows 7?

If you are using vs 2010 then you can get it in

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools

How to customize an end time for a YouTube video?

I tried the method of @mystic11 ( https://stackoverflow.com/a/11422551/506073 ) and got redirected around. Here is a working example URL:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3

If the version=3 parameter is omitted, the video starts at the correct place but runs all the way to the end. From the documentation for the end parameter I am guessing version=3 asks for the AS3 player to be used. See:

end (supported players: AS3, HTML5)

Additional Experiments

Autoplay

Autoplay of the clipped video portion works:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1

Looping

Adding looping as per the documentation unfortunately starts the second and subsequent iterations at the beginning of the video: http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&loop=1&playlist=WA8sLsM3McU

To do this properly, you probably need to set enablejsapi=1 and use the javascript API.

FYI, the above video looped: http://www.infinitelooper.com/?v=WA8sLsM3McU&p=n#/15;19

Remove Branding and Related Videos

To get rid of the Youtube logo and the list of videos to click on to at the end of playing the video you want to watch, add these (&modestBranding=1&rel=0) parameters:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1&modestBranding=1&rel=0

Remove the uploader info with showinfo=0:

http://youtube.googleapis.com/v/WA8sLsM3McU?start=15&end=20&version=3&autoplay=1&modestBranding=1&rel=0&showinfo=0

This eliminates the thin strip with video title, up and down thumbs, and info icon at the top of the video. The final version produced is fairly clean and doesn't have the downside of giving your viewers an exit into unproductive clicking around Youtube at the end of watching the video portion that you wanted them to see.

Calculate age based on date of birth

Got this script from net (thanks to coffeecupweb)

<?php
/**
 * Simple PHP age Calculator
 * 
 * Calculate and returns age based on the date provided by the user.
 * @param   date of birth('Format:yyyy-mm-dd').
 * @return  age based on date of birth
 */
function ageCalculator($dob){
    if(!empty($dob)){
        $birthdate = new DateTime($dob);
        $today   = new DateTime('today');
        $age = $birthdate->diff($today)->y;
        return $age;
    }else{
        return 0;
    }
}
$dob = '1992-03-18';
echo ageCalculator($dob);
?>

Automated testing for REST Api

I collaborated with one of my coworkers to start the PyRestTest framework for this reason: https://github.com/svanoort/pyresttest

Although you can work with the tests in Python, the normal test format is in YAML.

Sample test suite for a basic REST app -- verifies that APIs respond correctly, checking HTTP status codes, though you can make it examine response bodies as well:

---
- config:
    - testset: "Tests using test app"

- test: # create entity
    - name: "Basic get"
    - url: "/api/person/"
- test: # create entity
    - name: "Get single person"
    - url: "/api/person/1/"
- test: # create entity
    - name: "Get single person"
    - url: "/api/person/1/"
    - method: 'DELETE'
- test: # create entity by PUT
    - name: "Create/update person"
    - url: "/api/person/1/"
    - method: "PUT"
    - body: '{"first_name": "Gaius","id": 1,"last_name": "Baltar","login": "gbaltar"}'
    - headers: {'Content-Type': 'application/json'}
- test: # create entity by POST
    - name: "Create person"
    - url: "/api/person/"
    - method: "POST"
    - body: '{"first_name": "Willim","last_name": "Adama","login": "theadmiral"}'
    - headers: {Content-Type: application/json}

How do I launch the Android emulator from the command line?

I am late, here but want to share so may be it help some one and me too when ever needed later :) , So below is the way to open emulator from command line with one command using bash script. I am using MX Linux but process is same on all operating systems

1- First Check the installed emulators

emulator -list-avds

it will result like below

emulator -list-avds
Nexus_4_API_28
Pixel_2_API_28

2- open any plain text or code editor and create a new file and write as below

#!/bin/sh
emulator -avd Nexus_4_API_28

Nexus_4_API_28 is the emulator that i want to open you write yours which you got from first step

save this file with .sh extension

3- Then, change the permissions on the file to make it executable:

chmod u+x emu.sh

4- Now open the emulator just executing this bash script file with following command

./emu.sh

enter image description here

Break a previous commit into multiple commits

I think that the best way i use git rebase -i. I created a video to show the steps to split a commit: https://www.youtube.com/watch?v=3EzOz7e1ADI

ggplot with 2 y axes on each side and different scales

For me the tricky part was figuring out the transformation function between the two axis. I used myCurveFit for that.

> dput(combined_80_8192 %>% filter (time > 270, time < 280))
structure(list(run = c(268L, 268L, 268L, 268L, 268L, 268L, 268L, 
268L, 268L, 268L, 263L, 263L, 263L, 263L, 263L, 263L, 263L, 263L, 
263L, 263L, 269L, 269L, 269L, 269L, 269L, 269L, 269L, 269L, 269L, 
269L, 261L, 261L, 261L, 261L, 261L, 261L, 261L, 261L, 261L, 261L, 
267L, 267L, 267L, 267L, 267L, 267L, 267L, 267L, 267L, 267L, 265L, 
265L, 265L, 265L, 265L, 265L, 265L, 265L, 265L, 265L, 266L, 266L, 
266L, 266L, 266L, 266L, 266L, 266L, 266L, 266L, 262L, 262L, 262L, 
262L, 262L, 262L, 262L, 262L, 262L, 262L, 264L, 264L, 264L, 264L, 
264L, 264L, 264L, 264L, 264L, 264L, 260L, 260L, 260L, 260L, 260L, 
260L, 260L, 260L, 260L, 260L), repetition = c(8L, 8L, 8L, 8L, 
8L, 8L, 8L, 8L, 8L, 8L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 5L, 5L, 
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 
6L, 6L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 
4L, 4L, 4L, 4L, 4L, 4L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L
), module = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "scenario.node[0].nicVLCTail.phyVLC", class = "factor"), 
    configname = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L), .Label = "Road-Vlc", class = "factor"), packetByteLength = c(8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 
    8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L, 8192L
    ), numVehicles = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L
    ), dDistance = c(80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L, 
    80L, 80L, 80L, 80L, 80L, 80L, 80L, 80L), time = c(270.166006903445, 
    271.173853699836, 272.175873251122, 273.177524313334, 274.182946177105, 
    275.188959464989, 276.189675339937, 277.198250244799, 278.204619457189, 
    279.212562800009, 270.164199199177, 271.168527215152, 272.173072994958, 
    273.179210429715, 274.184351047337, 275.18980754378, 276.194816792995, 
    277.198598277809, 278.202398083519, 279.210634593917, 270.210674322891, 
    271.212395107473, 272.218871923292, 273.219060500457, 274.220486359614, 
    275.22401452372, 276.229646658839, 277.231060448138, 278.240407241942, 
    279.2437126347, 270.283554249858, 271.293168593832, 272.298574288769, 
    273.304413221348, 274.306272082517, 275.309023049011, 276.317805897347, 
    277.324403550028, 278.332855848701, 279.334046374594, 270.118608539613, 
    271.127947700074, 272.133887145863, 273.135726000491, 274.135994529981, 
    275.136563912708, 276.140120735361, 277.144298344151, 278.146885137621, 
    279.147552358659, 270.206015567272, 271.214618077209, 272.216566814903, 
    273.225435592582, 274.234014573683, 275.242949179958, 276.248417809711, 
    277.248800670023, 278.249750333404, 279.252926560188, 270.217182684494, 
    271.218357511397, 272.224698488895, 273.231112784327, 274.238740508457, 
    275.242715184122, 276.249053562718, 277.250325509798, 278.258488063493, 
    279.261141590137, 270.282904173953, 271.284689544638, 272.294220723234, 
    273.299749415592, 274.30628880553, 275.312075103126, 276.31579134717, 
    277.321905523606, 278.326305136748, 279.333056502253, 270.258991527456, 
    271.260224091407, 272.270076810133, 273.27052037648, 274.274119348094, 
    275.280808254502, 276.286353887245, 277.287064312339, 278.294444793276, 
    279.296772014594, 270.333066283904, 271.33877455992, 272.345842319903, 
    273.350858180493, 274.353972278505, 275.360454510107, 276.365088896161, 
    277.369166956941, 278.372571708911, 279.38017503079), distanceToTx = c(80.255266401689, 
    80.156059067023, 79.98823695539, 79.826647129071, 79.76678667135, 
    79.788239825292, 79.734539327997, 79.74766421514, 79.801243848241, 
    79.765920888341, 80.255266401689, 80.15850240049, 79.98823695539, 
    79.826647129071, 79.76678667135, 79.788239825292, 79.735078924078, 
    79.74766421514, 79.801243848241, 79.764622734914, 80.251248121732, 
    80.146436869316, 79.984682320466, 79.82292012342, 79.761908518748, 
    79.796988776281, 79.736920997657, 79.745038376718, 79.802638836686, 
    79.770029970452, 80.243475525691, 80.127918207499, 79.978303140866, 
    79.816259117883, 79.749322030693, 79.809916018889, 79.744456560867, 
    79.738655068783, 79.788697533211, 79.784288359619, 80.260412958482, 
    80.168426829066, 79.992034911214, 79.830845773284, 79.7756751763, 
    79.778156038931, 79.732399593756, 79.752769548846, 79.799967731078, 
    79.757585110481, 80.251248121732, 80.146436869316, 79.984682320466, 
    79.822062073459, 79.75884601899, 79.801590491435, 79.738335109094, 
    79.74347007248, 79.803215965043, 79.771471198955, 80.250257298678, 
    80.146436869316, 79.983831684476, 79.822062073459, 79.75884601899, 
    79.801590491435, 79.738335109094, 79.74347007248, 79.803849157574, 
    79.771471198955, 80.243475525691, 80.130180105198, 79.978303140866, 
    79.816881283718, 79.749322030693, 79.80984572883, 79.744456560867, 
    79.738655068783, 79.790548644175, 79.784288359619, 80.246349000313, 
    80.137056554491, 79.980581246037, 79.818924707937, 79.753176142361, 
    79.808777040341, 79.741609845588, 79.740770913572, 79.796316397253, 
    79.777593733292, 80.238796415443, 80.119021911134, 79.974810568944, 
    79.814065350562, 79.743657315504, 79.810146783217, 79.749945098869, 
    79.737122584544, 79.781650522348, 79.791554933936), headerNoError = c(0.99999999989702, 
    0.9999999999981, 0.99999999999946, 0.9999999928026, 0.99999873265475, 
    0.77080141574964, 0.99007491438593, 0.99994396605059, 0.45588747062284, 
    0.93484381262491, 0.99999999989702, 0.99999999999816, 0.99999999999946, 
    0.9999999928026, 0.99999873265475, 0.77080141574964, 0.99008458785106, 
    0.99994396605059, 0.45588747062284, 0.93480223051707, 0.99999999989735, 
    0.99999999999789, 0.99999999999946, 0.99999999287551, 0.99999876302649, 
    0.46903147501117, 0.98835168988253, 0.99994427085086, 0.45235035271542, 
    0.93496741877335, 0.99999999989803, 0.99999999999781, 0.99999999999948, 
    0.99999999318224, 0.99994254156311, 0.46891362282273, 0.93382613917348, 
    0.99994594904099, 0.93002915596843, 0.93569767251247, 0.99999999989658, 
    0.99999999998074, 0.99999999999946, 0.99999999272802, 0.99999871586781, 
    0.76935240919896, 0.99002587758346, 0.99999881589732, 0.46179415706093, 
    0.93417422376389, 0.99999999989735, 0.99999999999789, 0.99999999999946, 
    0.99999999289347, 0.99999876940486, 0.46930769326427, 0.98837353639905, 
    0.99994447154714, 0.16313586712094, 0.93500824170148, 0.99999999989744, 
    0.99999999999789, 0.99999999999946, 0.99999999289347, 0.99999876940486, 
    0.46930769326427, 0.98837353639905, 0.99994447154714, 0.16330039178981, 
    0.93500824170148, 0.99999999989803, 0.99999999999781, 0.99999999999948, 
    0.99999999316541, 0.99994254156311, 0.46794586553266, 0.93382613917348, 
    0.99994594904099, 0.9303627789484, 0.93569767251247, 0.99999999989778, 
    0.9999999999978, 0.99999999999948, 0.99999999311433, 0.99999878195152, 
    0.47101897739483, 0.93368891853679, 0.99994556595217, 0.7571113417265, 
    0.93553999975802, 0.99999999998191, 0.99999999999784, 0.99999999999971, 
    0.99999891129658, 0.99994309267792, 0.46510628979591, 0.93442584181035, 
    0.99894450514543, 0.99890078483692, 0.76933812306423), receivedPower_dbm = c(-93.023492290586, 
    -92.388378035287, -92.205716340607, -93.816400586752, -95.023489422885, 
    -100.86308557253, -98.464763536915, -96.175707680373, -102.06189538385, 
    -99.716653422746, -93.023492290586, -92.384760627397, -92.205716340607, 
    -93.816400586752, -95.023489422885, -100.86308557253, -98.464201120719, 
    -96.175707680373, -102.06189538385, -99.717150021506, -93.022927803442, 
    -92.404017215549, -92.204561341714, -93.814319484729, -95.016990717792, 
    -102.01669022332, -98.558088145955, -96.173817001483, -102.07406915124, 
    -99.71517574876, -93.021813165972, -92.409586309743, -92.20229160243, 
    -93.805335867418, -96.184419849593, -102.01709540787, -99.728735187547, 
    -96.163233028048, -99.772547164798, -99.706399753853, -93.024204617071, 
    -92.745813384859, -92.206884754512, -93.818508150122, -95.027018807793, 
    -100.87000577258, -98.467607232407, -95.005311380324, -102.04157607608, 
    -99.724619517, -93.022927803442, -92.404017215549, -92.204561341714, 
    -93.813803344588, -95.015606885523, -102.0157405687, -98.556982278361, 
    -96.172566862738, -103.21871579865, -99.714687230796, -93.022787428238, 
    -92.404017215549, -92.204274688493, -93.813803344588, -95.015606885523, 
    -102.0157405687, -98.556982278361, -96.172566862738, -103.21784988098, 
    -99.714687230796, -93.021813165972, -92.409950613665, -92.20229160243, 
    -93.805838770576, -96.184419849593, -102.02042267497, -99.728735187547, 
    -96.163233028048, -99.768774335378, -99.706399753853, -93.022228914406, 
    -92.411048503835, -92.203136463155, -93.807357409082, -95.012865008237, 
    -102.00985717796, -99.730352912911, -96.165675535906, -100.92744056572, 
    -99.708301333236, -92.735781110993, -92.408137395049, -92.119533319039, 
    -94.982938427575, -96.181073124017, -102.03018610927, -99.721633629806, 
    -97.32940323644, -97.347613268692, -100.87007386786), snr = c(49.848348091678, 
    57.698190927109, 60.17669971462, 41.529809724535, 31.452202106925, 
    8.1976890851341, 14.240447804094, 24.122884195464, 6.2202875499406, 
    10.674183333671, 49.848348091678, 57.746270018264, 60.17669971462, 
    41.529809724535, 31.452202106925, 8.1976890851341, 14.242292077376, 
    24.122884195464, 6.2202875499406, 10.672962852322, 49.854827699773, 
    57.49079026127, 60.192705735317, 41.549715223147, 31.499301851462, 
    6.2853718719014, 13.937702343688, 24.133388256416, 6.2028757927148, 
    10.677815810561, 49.867624820879, 57.417115267867, 60.224172277442, 
    41.635752021705, 24.074540962859, 6.2847854917092, 10.644529778044, 
    24.19227425387, 10.537686730745, 10.699414795917, 49.84017267426, 
    53.139646558768, 60.160512118809, 41.509660845114, 31.42665220053, 
    8.1846370024428, 14.231126423354, 31.584125885363, 6.2494585568733, 
    10.654622041348, 49.854827699773, 57.49079026127, 60.192705735317, 
    41.55465351989, 31.509340361646, 6.2867464196657, 13.941251828322, 
    24.140336174865, 4.765718874642, 10.679016976694, 49.856439162736, 
    57.49079026127, 60.196678846453, 41.55465351989, 31.509340361646, 
    6.2867464196657, 13.941251828322, 24.140336174865, 4.7666691818074, 
    10.679016976694, 49.867624820879, 57.412299088098, 60.224172277442, 
    41.630930975211, 24.074540962859, 6.279972363168, 10.644529778044, 
    24.19227425387, 10.546845071479, 10.699414795917, 49.862851240855, 
    57.397787176282, 60.212457625018, 41.61637603957, 31.529239767749, 
    6.2952688513108, 10.640565481982, 24.178672145334, 8.0771089950663, 
    10.694731030907, 53.262541905639, 57.43627424514, 61.382796189332, 
    31.747253311549, 24.093100244121, 6.2658701281075, 10.661949889074, 
    18.495227442305, 18.417839037171, 8.1845086722809), frameId = c(15051, 
    15106, 15165, 15220, 15279, 15330, 15385, 15452, 15511, 15566, 
    15019, 15074, 15129, 15184, 15239, 15298, 15353, 15412, 15471, 
    15526, 14947, 14994, 15057, 15112, 15171, 15226, 15281, 15332, 
    15391, 15442, 14971, 15030, 15085, 15144, 15203, 15262, 15321, 
    15380, 15435, 15490, 14915, 14978, 15033, 15092, 15147, 15198, 
    15257, 15312, 15371, 15430, 14975, 15034, 15089, 15140, 15195, 
    15254, 15313, 15368, 15427, 15478, 14987, 15046, 15105, 15160, 
    15215, 15274, 15329, 15384, 15447, 15506, 14943, 15002, 15061, 
    15116, 15171, 15230, 15285, 15344, 15399, 15454, 14971, 15026, 
    15081, 15136, 15195, 15258, 15313, 15368, 15423, 15478, 15039, 
    15094, 15149, 15204, 15263, 15314, 15369, 15428, 15487, 15546
    ), packetOkSinr = c(0.99999999314881, 0.9999999998736, 0.99999999996428, 
    0.99999952114066, 0.99991568416005, 3.00628034688444e-08, 
    0.51497487795954, 0.99627877136019, 0, 0.011303253101957, 
    0.99999999314881, 0.99999999987726, 0.99999999996428, 0.99999952114066, 
    0.99991568416005, 3.00628034688444e-08, 0.51530974419663, 
    0.99627877136019, 0, 0.011269851265775, 0.9999999931708, 
    0.99999999985986, 0.99999999996428, 0.99999952599145, 0.99991770469509, 
    0, 0.45861812482641, 0.99629897628155, 0, 0.011403119534097, 
    0.99999999321568, 0.99999999985437, 0.99999999996519, 0.99999954639936, 
    0.99618434878558, 0, 0.010513119213425, 0.99641022914441, 
    0.00801687746446111, 0.012011103529927, 0.9999999931195, 
    0.99999999871861, 0.99999999996428, 0.99999951617905, 0.99991456738049, 
    2.6525298291169e-08, 0.51328066587104, 0.9999212220316, 0, 
    0.010777054258914, 0.9999999931708, 0.99999999985986, 0.99999999996428, 
    0.99999952718674, 0.99991812902805, 0, 0.45929307038653, 
    0.99631228046814, 0, 0.011436292559188, 0.99999999317629, 
    0.99999999985986, 0.99999999996428, 0.99999952718674, 0.99991812902805, 
    0, 0.45929307038653, 0.99631228046814, 0, 0.011436292559188, 
    0.99999999321568, 0.99999999985437, 0.99999999996519, 0.99999954527918, 
    0.99618434878558, 0, 0.010513119213425, 0.99641022914441, 
    0.00821047996950475, 0.012011103529927, 0.99999999319919, 
    0.99999999985345, 0.99999999996519, 0.99999954188106, 0.99991896371849, 
    0, 0.010410830482692, 0.996384831822, 9.12484388049251e-09, 
    0.011877185067536, 0.99999999879646, 0.9999999998562, 0.99999999998077, 
    0.99992756868677, 0.9962208785486, 0, 0.010971897073662, 
    0.93214999078663, 0.92943956665979, 2.64925478221656e-08), 
    snir = c(49.848348091678, 57.698190927109, 60.17669971462, 
    41.529809724535, 31.452202106925, 8.1976890851341, 14.240447804094, 
    24.122884195464, 6.2202875499406, 10.674183333671, 49.848348091678, 
    57.746270018264, 60.17669971462, 41.529809724535, 31.452202106925, 
    8.1976890851341, 14.242292077376, 24.122884195464, 6.2202875499406, 
    10.672962852322, 49.854827699773, 57.49079026127, 60.192705735317, 
    41.549715223147, 31.499301851462, 6.2853718719014, 13.937702343688, 
    24.133388256416, 6.2028757927148, 10.677815810561, 49.867624820879, 
    57.417115267867, 60.224172277442, 41.635752021705, 24.074540962859, 
    6.2847854917092, 10.644529778044, 24.19227425387, 10.537686730745, 
    10.699414795917, 49.84017267426, 53.139646558768, 60.160512118809, 
    41.509660845114, 31.42665220053, 8.1846370024428, 14.231126423354, 
    31.584125885363, 6.2494585568733, 10.654622041348, 49.854827699773, 
    57.49079026127, 60.192705735317, 41.55465351989, 31.509340361646, 
    6.2867464196657, 13.941251828322, 24.140336174865, 4.765718874642, 
    10.679016976694, 49.856439162736, 57.49079026127, 60.196678846453, 
    41.55465351989, 31.509340361646, 6.2867464196657, 13.941251828322, 
    24.140336174865, 4.7666691818074, 10.679016976694, 49.867624820879, 
    57.412299088098, 60.224172277442, 41.630930975211, 24.074540962859, 
    6.279972363168, 10.644529778044, 24.19227425387, 10.546845071479, 
    10.699414795917, 49.862851240855, 57.397787176282, 60.212457625018, 
    41.61637603957, 31.529239767749, 6.2952688513108, 10.640565481982, 
    24.178672145334, 8.0771089950663, 10.694731030907, 53.262541905639, 
    57.43627424514, 61.382796189332, 31.747253311549, 24.093100244121, 
    6.2658701281075, 10.661949889074, 18.495227442305, 18.417839037171, 
    8.1845086722809), ookSnirBer = c(8.8808636558081e-24, 3.2219795637026e-27, 
    2.6468895519653e-28, 3.9807779074715e-20, 1.0849324265615e-15, 
    2.5705217057696e-05, 4.7313805615763e-08, 1.8800438086075e-12, 
    0.00021005320203921, 1.9147343768384e-06, 8.8808636558081e-24, 
    3.0694773489537e-27, 2.6468895519653e-28, 3.9807779074715e-20, 
    1.0849324265615e-15, 2.5705217057696e-05, 4.7223753038869e-08, 
    1.8800438086075e-12, 0.00021005320203921, 1.9171738578051e-06, 
    8.8229427230445e-24, 3.9715925056443e-27, 2.6045198111088e-28, 
    3.9014083702734e-20, 1.0342658440386e-15, 0.00019591630514278, 
    6.4692014108683e-08, 1.8600094209271e-12, 0.0002140067535655, 
    1.9074922485477e-06, 8.7096574467175e-24, 4.2779443633862e-27, 
    2.5231916788231e-28, 3.5761615214425e-20, 1.9750692814982e-12, 
    0.0001960392878411, 1.9748966344895e-06, 1.7515881895994e-12, 
    2.2078334799411e-06, 1.8649940680806e-06, 8.954486301678e-24, 
    3.2021085732779e-25, 2.690441113724e-28, 4.0627628846548e-20, 
    1.1134484878561e-15, 2.6061691733331e-05, 4.777159157954e-08, 
    9.4891388749738e-16, 0.00020359398491544, 1.9542110660398e-06, 
    8.8229427230445e-24, 3.9715925056443e-27, 2.6045198111088e-28, 
    3.8819641115984e-20, 1.0237769828158e-15, 0.00019562832342849, 
    6.4455095380046e-08, 1.8468752030971e-12, 0.0010099091367628, 
    1.9051035165106e-06, 8.8085966897635e-24, 3.9715925056443e-27, 
    2.594108048185e-28, 3.8819641115984e-20, 1.0237769828158e-15, 
    0.00019562832342849, 6.4455095380046e-08, 1.8468752030971e-12, 
    0.0010088638355194, 1.9051035165106e-06, 8.7096574467175e-24, 
    4.2987746909572e-27, 2.5231916788231e-28, 3.593647329558e-20, 
    1.9750692814982e-12, 0.00019705170257492, 1.9748966344895e-06, 
    1.7515881895994e-12, 2.1868296425817e-06, 1.8649940680806e-06, 
    8.7517439682173e-24, 4.3621551072316e-27, 2.553168170837e-28, 
    3.6469582463164e-20, 1.0032983660212e-15, 0.00019385229409318, 
    1.9830820164805e-06, 1.7760568361323e-12, 2.919419915209e-05, 
    1.8741284335866e-06, 2.8285944348148e-25, 4.1960751547207e-27, 
    7.8468215407139e-29, 8.0407329049747e-16, 1.9380328071065e-12, 
    0.00020004849911333, 1.9393279417733e-06, 5.9354475879597e-10, 
    6.4258355913627e-10, 2.6065221215415e-05), ookSnrBer = c(8.8808636558081e-24, 
    3.2219795637026e-27, 2.6468895519653e-28, 3.9807779074715e-20, 
    1.0849324265615e-15, 2.5705217057696e-05, 4.7313805615763e-08, 
    1.8800438086075e-12, 0.00021005320203921, 1.9147343768384e-06, 
    8.8808636558081e-24, 3.0694773489537e-27, 2.6468895519653e-28, 
    3.9807779074715e-20, 1.0849324265615e-15, 2.5705217057696e-05, 
    4.7223753038869e-08, 1.8800438086075e-12, 0.00021005320203921, 
    1.9171738578051e-06, 8.8229427230445e-24, 3.9715925056443e-27, 
    2.6045198111088e-28, 3.9014083702734e-20, 1.0342658440386e-15, 
    0.00019591630514278, 6.4692014108683e-08, 1.8600094209271e-12, 
    0.0002140067535655, 1.9074922485477e-06, 8.7096574467175e-24, 
    4.2779443633862e-27, 2.5231916788231e-28, 3.5761615214425e-20, 
    1.9750692814982e-12, 0.0001960392878411, 1.9748966344895e-06, 
    1.7515881895994e-12, 2.2078334799411e-06, 1.8649940680806e-06, 
    8.954486301678e-24, 3.2021085732779e-25, 2.690441113724e-28, 
    4.0627628846548e-20, 1.1134484878561e-15, 2.6061691733331e-05, 
    4.777159157954e-08, 9.4891388749738e-16, 0.00020359398491544, 
    1.9542110660398e-06, 8.8229427230445e-24, 3.9715925056443e-27, 
    2.6045198111088e-28, 3.8819641115984e-20, 1.0237769828158e-15, 
    0.00019562832342849, 6.4455095380046e-08, 1.8468752030971e-12, 
    0.0010099091367628, 1.9051035165106e-06, 8.8085966897635e-24, 
    3.9715925056443e-27, 2.594108048185e-28, 3.8819641115984e-20, 
    1.0237769828158e-15, 0.00019562832342849, 6.4455095380046e-08, 
    1.8468752030971e-12, 0.0010088638355194, 1.9051035165106e-06, 
    8.7096574467175e-24, 4.2987746909572e-27, 2.5231916788231e-28, 
    3.593647329558e-20, 1.9750692814982e-12, 0.00019705170257492, 
    1.9748966344895e-06, 1.7515881895994e-12, 2.1868296425817e-06, 
    1.8649940680806e-06, 8.7517439682173e-24, 4.3621551072316e-27, 
    2.553168170837e-28, 3.6469582463164e-20, 1.0032983660212e-15, 
    0.00019385229409318, 1.9830820164805e-06, 1.7760568361323e-12, 
    2.919419915209e-05, 1.8741284335866e-06, 2.8285944348148e-25, 
    4.1960751547207e-27, 7.8468215407139e-29, 8.0407329049747e-16, 
    1.9380328071065e-12, 0.00020004849911333, 1.9393279417733e-06, 
    5.9354475879597e-10, 6.4258355913627e-10, 2.6065221215415e-05
    )), class = "data.frame", row.names = c(NA, -100L), .Names = c("run", 
"repetition", "module", "configname", "packetByteLength", "numVehicles", 
"dDistance", "time", "distanceToTx", "headerNoError", "receivedPower_dbm", 
"snr", "frameId", "packetOkSinr", "snir", "ookSnirBer", "ookSnrBer"
))

Finding the transformation function

  1. y1 --> y2 This function is used to transform the data of the secondary y axis to be "normalized" according to the first y axis

enter image description here

transformation function: f(y1) = 0.025*x + 2.75


  1. y2 --> y1 This function is used to transform the break points of the first y axis to the values of the second y axis. Note that the axis are swapped now.

enter image description here

transformation function: f(y1) = 40*x - 110


Plotting

Note how the transformation functions are used in the ggplot call to transform the data "on-the-fly"

ggplot(data=combined_80_8192 %>% filter (time > 270, time < 280), aes(x=time) ) +
  stat_summary(aes(y=receivedPower_dbm ), fun.y=mean, geom="line", colour="black") +
  stat_summary(aes(y=packetOkSinr*40 - 110 ), fun.y=mean, geom="line", colour="black", position = position_dodge(width=10)) +
  scale_x_continuous() +
  scale_y_continuous(breaks = seq(-0,-110,-10), "y_first", sec.axis=sec_axis(~.*0.025+2.75, name="y_second") ) 

The first stat_summary call is the one that sets the base for the first y axis. The second stat_summary call is called to transform the data. Remember that all of the data will take as base the first y axis. So that data needs to be normalized for the first y axis. To do that I use the transformation function on the data: y=packetOkSinr*40 - 110

Now to transform the second axis I use the opposite function within the scale_y_continuous call: sec.axis=sec_axis(~.*0.025+2.75, name="y_second").

enter image description here

Can I get "&&" or "-and" to work in PowerShell?

Use:

if (start-process filename1.exe) {} else {start-process filename2.exe}

It's a little longer than "&&", but it accomplishes the same thing without scripting and is not too hard to remember.

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

How to escape "&" in XML?

use &amp; in place of &

change to

<string name="magazine">Newspaper &amp; Magazines</string>

Typescript: React event types

For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState here's my solution:

const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);

const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
    setAnchorElement(event.currentTarget);
};

How to use XPath contains() here?

This is a new answer to an old question about a common misconception about contains() in XPath...

Summary: contains() means contains a substring, not contains a node.

Detailed Explanation

This XPath is often misinterpreted:

//ul[contains(li, 'Model')]

Wrong interpretation: Select those ul elements that contain an li element with Model in it.

This is wrong because

  1. contains(x,y) expects x to be a string, and
  2. the XPath rule for converting multiple elements to a string is this:

    A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.

Right interpretation: Select those ul elements whose first li child has a string-value that contains a Model substring.

Examples

XML

<r>
  <ul id="one">
    <li>Model A</li>
    <li>Foo</li>
  </ul>
  <ul id="two">
    <li>Foo</li>
    <li>Model A</li>
  </ul>
</r> 

XPaths

  • //ul[contains(li, 'Model')] selects the one ul element.

    Note: The two ul element is not selected because the string-value of the first li child of the two ul is Foo, which does not contain the Model substring.

  • //ul[li[contains(.,'Model')]] selects the one and two ul elements.

    Note: Both ul elements are selected because contains() is applied to each li individually. (Thus, the tricky multiple-element-to-string conversion rule is avoided.) Both ul elements do have an li child whose string value contains the Model substring -- position of the li element no longer matters.

See also

ReferenceError: $ is not defined

Add jQuery library before your script which uses $ or jQuery so that $ can be identified in scripts.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

ConcurrentHashMap vs Synchronized HashMap

Both are synchronized version of HashMap, with difference in their core functionality and their internal structure.

ConcurrentHashMap consist of internal segments which can be viewed as independent HashMaps Conceptually. All such segments can be locked by separate threads in high concurrent executions. So, multiple threads can get/put key-value pairs from ConcurrentHashMap without blocking/waiting for each other. This is implemented for higher throughput.

whereas

Collections.synchronizedMap(), we get a synchronized version of HashMap and it is accessed in blocking manner. This means if multiple threads try to access synchronizedMap at same time, they will be allowed to get/put key-value pairs one at a time in synchronized manner.

How to sum the values of a JavaScript object?

We can iterate object using in keyword and can perform any arithmetic operation.

_x000D_
_x000D_
// input
const sample = {
    'a': 1,
    'b': 2,
    'c': 3
};

// var
let sum = 0;

// object iteration
for (key in sample) {
    //sum
    sum += (+sample[key]);
}
// result
console.log("sum:=>", sum);
_x000D_
_x000D_
_x000D_

c++ exception : throwing std::string

Yes. std::exception is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?

boost has an excellent document on good style for exceptions and error handling. It's worth a read.

Node.js - SyntaxError: Unexpected token import

In case that you still can't use "import" here is how I handled it: Just translate it to a node friendly require. Example:

import { parse } from 'node-html-parser';

Is the same as:

const parse = require('node-html-parser').parse;

Custom HTTP headers : naming conventions

The format for HTTP headers is defined in the HTTP specification. I'm going to talk about HTTP 1.1, for which the specification is RFC 2616. In section 4.2, 'Message Headers', the general structure of a header is defined:

   message-header = field-name ":" [ field-value ]
   field-name     = token
   field-value    = *( field-content | LWS )
   field-content  = <the OCTETs making up the field-value
                    and consisting of either *TEXT or combinations
                    of token, separators, and quoted-string>

This definition rests on two main pillars, token and TEXT. Both are defined in section 2.2, 'Basic Rules'. Token is:

   token          = 1*<any CHAR except CTLs or separators>

In turn resting on CHAR, CTL and separators:

   CHAR           = <any US-ASCII character (octets 0 - 127)>

   CTL            = <any US-ASCII control character
                    (octets 0 - 31) and DEL (127)>

   separators     = "(" | ")" | "<" | ">" | "@"
                  | "," | ";" | ":" | "\" | <">
                  | "/" | "[" | "]" | "?" | "="
                  | "{" | "}" | SP | HT

TEXT is:

   TEXT           = <any OCTET except CTLs,
                    but including LWS>

Where LWS is linear white space, whose definition i won't reproduce, and OCTET is:

   OCTET          = <any 8-bit sequence of data>

There is a note accompanying the definition:

The TEXT rule is only used for descriptive field contents and values
that are not intended to be interpreted by the message parser. Words
of *TEXT MAY contain characters from character sets other than ISO-
8859-1 [22] only when encoded according to the rules of RFC 2047
[14].

So, two conclusions. Firstly, it's clear that the header name must be composed from a subset of ASCII characters - alphanumerics, some punctuation, not a lot else. Secondly, there is nothing in the definition of a header value that restricts it to ASCII or excludes 8-bit characters: it's explicitly composed of octets, with only control characters barred (note that CR and LF are considered controls). Furthermore, the comment on the TEXT production implies that the octets are to be interpreted as being in ISO-8859-1, and that there is an encoding mechanism (which is horrible, incidentally) for representing characters outside that encoding.

So, to respond to @BalusC in particular, it's quite clear that according to the specification, header values are in ISO-8859-1. I've sent high-8859-1 characters (specifically, some accented vowels as used in French) in a header out of Tomcat, and had them interpreted correctly by Firefox, so to some extent, this works in practice as well as in theory (although this was a Location header, which contains a URL, and these characters are not legal in URLs, so this was actually illegal, but under a different rule!).

That said, i wouldn't rely on ISO-8859-1 working across all servers, proxies, and clients, so i would stick to ASCII as a matter of defensive programming.

window.onload vs document.onload

Add Event Listener

<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", function(event) {
      // - Code to execute when all DOM content is loaded. 
      // - including fonts, images, etc.
  });
</script>


Update March 2017

1 Vanilla JavaScript

window.addEventListener('load', function() {
    console.log('All assets are loaded')
})


2 jQuery

$(window).on('load', function() {
    console.log('All assets are loaded')
})


Good Luck.