Programs & Examples On #Querydsl

Querydsl is a framework which enables the construction of type-safe SQL-like queries for multiple backends including JPA, MongoDB and SQL in Java.

How do I update an entity using spring-data-jpa?

public void updateLaserDataByHumanId(String replacement, String humanId) {
    List<LaserData> laserDataByHumanId = laserDataRepository.findByHumanId(humanId);
    laserDataByHumanId.stream()
            .map(en -> en.setHumanId(replacement))
            .collect(Collectors.toList())
            .forEach(en -> laserDataRepository.save(en));
}

Efficient way of having a function only execute once in a loop

Here's an explicit way to code this up, where the state of which functions have been called is kept locally (so global state is avoided). I don't much like the non-explicit forms suggested in other answers: it's too surprising to see f() and for this not to mean that f() gets called.

This works by using dict.pop which looks up a key in a dict, removes the key from the dict, and takes a default value to use in case the key isn't found.

def do_nothing(*args, *kwargs):
    pass

# A list of all the functions you want to run just once.
actions = [
    my_function,
    other_function
]
actions = dict((action, action) for action in actions)

while True:
    if some_condition:
        actions.pop(my_function, do_nothing)()
    if some_other_condition:
        actions.pop(other_function, do_nothing)()

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

How can I force a hard reload in Chrome for Android

In chrome,simply tick "Desktop site" and then remove tick!!

Progress during large file copy (Copy-Item & Write-Progress?)

i found none of the examples above met my needs, i wanted to copy a directory with sub directories, the problem is my source directory had too many files so i quickly hit the BITS file limit (i had > 1500 file) also the total directory size was quite large.

i found a function using robocopy that was a good starting point at https://keithga.wordpress.com/2014/06/23/copy-itemwithprogress/, however i found it wasn't quite robust enough, it didn't handle trailing slashes, spaces gracefully and did not stop the copy when the script was halted.

Here is my refined version:

function Copy-ItemWithProgress
{
    <#
    .SYNOPSIS
    RoboCopy with PowerShell progress.

    .DESCRIPTION
    Performs file copy with RoboCopy. Output from RoboCopy is captured,
    parsed, and returned as Powershell native status and progress.

    .PARAMETER Source
    Directory to copy files from, this should not contain trailing slashes

    .PARAMETER Destination
    DIrectory to copy files to, this should not contain trailing slahes

    .PARAMETER FilesToCopy
    A wildcard expresion of which files to copy, defaults to *.*

    .PARAMETER RobocopyArgs
    List of arguments passed directly to Robocopy.
    Must not conflict with defaults: /ndl /TEE /Bytes /NC /nfl /Log

    .PARAMETER ProgressID
    When specified (>=0) will use this identifier for the progress bar

    .PARAMETER ParentProgressID
    When specified (>= 0) will use this identifier as the parent ID for progress bars
    so that they appear nested which allows for usage in more complex scripts.

    .OUTPUTS
    Returns an object with the status of final copy.
    REMINDER: Any error level below 8 can be considered a success by RoboCopy.

    .EXAMPLE
    C:\PS> .\Copy-ItemWithProgress c:\Src d:\Dest

    Copy the contents of the c:\Src directory to a directory d:\Dest
    Without the /e or /mir switch, only files from the root of c:\src are copied.

    .EXAMPLE
    C:\PS> .\Copy-ItemWithProgress '"c:\Src Files"' d:\Dest /mir /xf *.log -Verbose

    Copy the contents of the 'c:\Name with Space' directory to a directory d:\Dest
    /mir and /XF parameters are passed to robocopy, and script is run verbose

    .LINK
    https://keithga.wordpress.com/2014/06/23/copy-itemwithprogress

    .NOTES
    By Keith S. Garner ([email protected]) - 6/23/2014
    With inspiration by Trevor Sullivan @pcgeek86
    Tweaked by Justin Marshall - 02/20/2020

    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$Source,
        [Parameter(Mandatory=$true)]
        [string]$Destination,
        [Parameter(Mandatory=$false)]
        [string]$FilesToCopy="*.*",
        [Parameter(Mandatory = $true,ValueFromRemainingArguments=$true)] 
        [string[]] $RobocopyArgs,
        [int]$ParentProgressID=-1,
        [int]$ProgressID=-1
    )

    #handle spaces and trailing slashes
    $SourceDir = '"{0}"' -f ($Source -replace "\\+$","")
    $TargetDir = '"{0}"' -f ($Destination -replace "\\+$","")


    $ScanLog  = [IO.Path]::GetTempFileName()
    $RoboLog  = [IO.Path]::GetTempFileName()
    $ScanArgs = @($SourceDir,$TargetDir,$FilesToCopy) + $RobocopyArgs + "/ndl /TEE /bytes /Log:$ScanLog /nfl /L".Split(" ")
    $RoboArgs = @($SourceDir,$TargetDir,$FilesToCopy) + $RobocopyArgs + "/ndl /TEE /bytes /Log:$RoboLog /NC".Split(" ")

    # Launch Robocopy Processes
    write-verbose ("Robocopy Scan:`n" + ($ScanArgs -join " "))
    write-verbose ("Robocopy Full:`n" + ($RoboArgs -join " "))
    $ScanRun = start-process robocopy -PassThru -WindowStyle Hidden -ArgumentList $ScanArgs
    try
    {
        $RoboRun = start-process robocopy -PassThru -WindowStyle Hidden -ArgumentList $RoboArgs
        try
        {
            # Parse Robocopy "Scan" pass
            $ScanRun.WaitForExit()
            $LogData = get-content $ScanLog
            if ($ScanRun.ExitCode -ge 8)
            {
                $LogData|out-string|Write-Error
                throw "Robocopy $($ScanRun.ExitCode)"
            }
            $FileSize = [regex]::Match($LogData[-4],".+:\s+(\d+)\s+(\d+)").Groups[2].Value
            write-verbose ("Robocopy Bytes: $FileSize `n" +($LogData -join "`n"))
            #determine progress parameters
            $ProgressParms=@{}
            if ($ParentProgressID -ge 0) {
                $ProgressParms['ParentID']=$ParentProgressID
            }
            if ($ProgressID -ge 0) {
                $ProgressParms['ID']=$ProgressID
            } else {
                $ProgressParms['ID']=$RoboRun.Id
            }
            # Monitor Full RoboCopy
            while (!$RoboRun.HasExited)
            {
                $LogData = get-content $RoboLog
                $Files = $LogData -match "^\s*(\d+)\s+(\S+)"
                if ($null -ne $Files )
                {
                    $copied = ($Files[0..($Files.Length-2)] | ForEach-Object {$_.Split("`t")[-2]} | Measure-Object -sum).Sum
                    if ($LogData[-1] -match "(100|\d?\d\.\d)\%")
                    {
                        write-progress Copy -ParentID $ProgressParms['ID'] -percentComplete $LogData[-1].Trim("% `t") $LogData[-1]
                        $Copied += $Files[-1].Split("`t")[-2] /100 * ($LogData[-1].Trim("% `t"))
                    }
                    else
                    {
                        write-progress Copy -ParentID $ProgressParms['ID'] -Complete
                    }
                    write-progress ROBOCOPY  -PercentComplete ($Copied/$FileSize*100) $Files[-1].Split("`t")[-1] @ProgressParms
                }
            }
        } finally {
            if (!$RoboRun.HasExited) {Write-Warning "Terminating copy process with ID $($RoboRun.Id)..."; $RoboRun.Kill() ; }
            $RoboRun.WaitForExit()
            # Parse full RoboCopy pass results, and cleanup
            (get-content $RoboLog)[-11..-2] | out-string | Write-Verbose
            remove-item $RoboLog
            write-output ([PSCustomObject]@{ ExitCode = $RoboRun.ExitCode })

        }
    } finally {
        if (!$ScanRun.HasExited) {Write-Warning "Terminating scan process with ID $($ScanRun.Id)..."; $ScanRun.Kill() }
        $ScanRun.WaitForExit()

        remove-item $ScanLog
    }
}

How to set image for bar button with swift?

Only two Lines of code required for this

Swift 3.0

let closeButtonImage = UIImage(named: "ic_close_white")
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: closeButtonImage, style: .plain, target: self, action:  #selector(ResetPasswordViewController.barButtonDidTap(_:)))

func barButtonDidTap(_ sender: UIBarButtonItem) 
{

}

Error: Cannot find module html

I think you might need to declare a view engine.

If you want to use a view/template engine:

app.set('view engine', 'ejs');

or

app.set('view engine', 'jade');

But to render plain-html, see this post: Render basic HTML view?.

Call an overridden method from super class in typescript

If you want a super class to call a function from a subclass, the cleanest way is to define an abstract pattern, in this manner you explicitly know the method exists somewhere and must be overridden by a subclass.

This is as an example, normally you do not call a sub method within the constructor as the sub instance is not initialized yet… (reason why you have an "undefined" in your question's example)

abstract class A {
    // The abstract method the subclass will have to call
    protected abstract doStuff():void;

    constructor(){
     alert("Super class A constructed, calling now 'doStuff'")
     this.doStuff();
    }
}

class B extends A{

    // Define here the abstract method
    protected doStuff()
    {
        alert("Submethod called");
    }
}

var b = new B();

Test it Here

And if like @Max you really want to avoid implementing the abstract method everywhere, just get rid of it. I don't recommend this approach because you might forget you are overriding the method.

abstract class A {
    constructor() {
        alert("Super class A constructed, calling now 'doStuff'")
        this.doStuff();
    }

    // The fallback method the subclass will call if not overridden
    protected doStuff(): void {
        alert("Default doStuff");
    };
}

class B extends A {
    // Override doStuff()
    protected doStuff() {
        alert("Submethod called");
    }
}

class C extends A {
    // No doStuff() overriding, fallback on A.doStuff()
}

var b = new B();
var c = new C();

Try it Here

How to read one single line of csv data in Python?

To print a range of line, in this case from line 4 to 7

import csv

with open('california_housing_test.csv') as csv_file:
    data = csv.reader(csv_file)
    for row in list(data)[4:7]:
        print(row)

How remove border around image in css?

Thank for the answers,

The border is removed for Internet Explorer, but this there for Firefox.

So, I added this class to the img:

.clearBorder{border:none;}

And it worked!

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

just delete the settings.xml and try againn to setup smartgitHg

Excel "External table is not in the expected format."

I know this is a very old post, but I can give my contribution too, on how I managed to resolve this issue.

I also use "Microsoft.ACE.OLEDB.12.0" as a Provider. When my code tried to read the XLSX file, it received the error "External table is not in the expected format." However, when I kept the file open in Excel and then the code tried to read it ... it worked.

SOLUTION: I use Office 365 with company documents and in my case, the solution was very simple, I just needed to disable the sensitivity of the document, setting it to "public". Detail: Even after saving as "public" the green check still remained marked in "Internal Use", but the problem remained solved after that.

enter image description here

WebSocket with SSL

To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.

for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.

In firefox, this can be done from 'about:preferences' and searching for 'Certificates'

What is the difference between YAML and JSON?

If you don't need any features which YAML has and JSON doesn't, I would prefer JSON because it is very simple and is widely supported (has a lot of libraries in many languages). YAML is more complex and has less support. I don't think the parsing speed or memory use will be very much different, and maybe not a big part of your program's performance.

Html.ActionLink as a button or an image, not a link

I like to use Url.Action() and Url.Content() like this:

<a href='@Url.Action("MyAction", "MyController")'>
    <img src='@Url.Content("~/Content/Images/MyLinkImage.png")' />
</a>

Strictly speaking, the Url.Content is only needed for pathing is not really part of the answer to your question.

Thanks to @BrianLegg for pointing out that this should use the new Razor view syntax. Example has been updated accordingly.

Replace a value in a data frame based on a conditional (`if`) statement

another useful way to replace values

library(plyr)
junk$nm <- revalue(junk$nm, c("B"="b"))

Cannot read property 'style' of undefined -- Uncaught Type Error

It's currently working, I've just changed the operator > in order to work in the snippet, take a look:

_x000D_
_x000D_
window.onload = function() {_x000D_
_x000D_
  if (window.location.href.indexOf("test") <= -1) {_x000D_
    var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
    search_span[0].style.color = "blue";_x000D_
    search_span[0].style.fontWeight = "bold";_x000D_
    search_span[0].style.fontSize = "40px";_x000D_
_x000D_
  }_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
_x000D_
_x000D_

How do I check my gcc C++ compiler version for my Eclipse?

#include <stdio.h>

int main() {

  printf("gcc version: %d.%d.%d\n",__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__);
  return 0;
}

Is there a simple way to remove unused dependencies from a maven pom.xml?

As others have said, you can use the dependency:analyze goal to find which dependencies are used and declared, used and undeclared, or unused and declared. You may also find dependency:analyze-dep-mgt useful to look for mismatches in your dependencyManagement section.

You can simply remove unwanted direct dependencies from your POM, but if they are introduced by third-party jars, you can use the <exclusions> tags in a dependency to exclude the third-party jars (see the section titled Dependency Exclusions for details and some discussion). Here is an example excluding commons-logging from the Spring dependency:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring</artifactId>
  <version>2.5.5</version>
  <exclusions>
    <exclusion>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </exclusion>
  </exclusions> 
</dependency>

How to get row count in sqlite using Android?

Change your getTaskCount Method to this:

public int getTaskCount(long tasklist_id){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?", new String[] { String.valueOf(tasklist_id) });
    cursor.moveToFirst();
    int count= cursor.getInt(0);
    cursor.close();
    return count;
}

Then, update the click handler accordingly:

public void onItemClick(AdapterView<?> arg0, android.view.View v, int position, long id) {
    db = new TodoTask_Database(getApplicationContext());

    // Get task list id
    int tasklistid = adapter.getItem(position).getTaskListId();

    if(db.getTaskCount(tasklistid) > 0) {    
        System.out.println(c);
        Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
        taskListID.putExtra("TaskList_ID", tasklistid);
        startActivity(taskListID);
    } else {
        Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
        startActivity(addTask);
    }
}

Reset select value to default

For those who are working with Bootstrap-select, you might want to use this:

$('#mySelect').selectpicker('render');

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

Can you do a partial checkout with Subversion?

Or do a non-recursive checkout of /trunk, then just do a manual update on the 3 directories you need.

Python 101: Can't open file: No such file or directory

From your question, you are running python2.7 and Cygwin.

Python should be installed for windows, which from your question it seems it is. If "which python" prints out /usr/bin/python , then from the bash prompt you are running the cygwin version.

Set the Python Environmental variables appropriately , for instance in my case:

PY_HOME=C:\opt\Python27
PYTHONPATH=C:\opt\Python27;c:\opt\Python27\Lib

In that case run cygwin setup and uninstall everything python. After that run "which pydoc", if it shows

/usr/bin/pydoc

Replace /usr/bin/pydoc with

#! /bin/bash
 /cygdrive/c/WINDOWS/system32/cmd /c %PYTHONHOME%\Scripts\\pydoc.bat

Then add this to $PY_HOME/Scripts/pydoc.bat

rem wrapper for pydoc on Win32
@python c:\opt\Python27\Lib\pydoc.py %*

Now when you type in the cygwin bash prompt you should see:

$ pydoc
 pydoc - the Python documentation tool

 pydoc.py <name> ...
   Show text documentation on something.  <name> 
   may be the name of a Python keyword, topic,
   function, module, or package, or a dotted
   reference to a class or function within a
   module or module in a package.
...

Critical t values in R

Josh's comments are spot on. If you are not super familiar with critical values I'd suggest playing with qt, reading the manual (?qt) in conjunction with looking at a look up table (LINK). When I first moved from SPSS to R I created a function that made critical t value look up pretty easy (I'd never use this now as it takes too much time and with the p values that are generally provided in the output it's a moot point). Here's the code for that:

critical.t <- function(){
    cat("\n","\bEnter Alpha Level","\n")
    alpha<-scan(n=1,what = double(0),quiet=T)
    cat("\n","\b1 Tailed or 2 Tailed:\nEnter either 1 or 2","\n")
    tt <- scan(n=1,what = double(0),quiet=T)
    cat("\n","\bEnter Number of Observations","\n")
    n <- scan(n=1,what = double(0),quiet=T)
    cat("\n\nCritical Value =",qt(1-(alpha/tt), n-2), "\n")
}

critical.t()

Array of PHP Objects

Yes, its possible to have array of objects in PHP.

class MyObject {
  private $property;

  public function  __construct($property) {
    $this->Property = $property;
  }
}
$ListOfObjects[] = new myObject(1); 
$ListOfObjects[] = new myObject(2); 
$ListOfObjects[] = new myObject(3); 
$ListOfObjects[] = new myObject(4); 

print "<pre>";
print_r($ListOfObjects);
print "</pre>";

Understanding React-Redux and mapStateToProps()

Here's an outline/boilerplate for describing the behavior of mapStateToProps:

(This is a vastly simplified implementation of what a Redux container does.)

class MyComponentContainer extends Component {
  mapStateToProps(state) {
    // this function is specific to this particular container
    return state.foo.bar;
  }

  render() {
    // This is how you get the current state from Redux,
    // and would be identical, no mater what mapStateToProps does
    const { state } = this.context.store.getState();

    const props = this.mapStateToProps(state);

    return <MyComponent {...this.props} {...props} />;
  }
}

and next

function buildReduxContainer(ChildComponentClass, mapStateToProps) {
  return class Container extends Component {
    render() {
      const { state } = this.context.store.getState();

      const props = mapStateToProps(state);

      return <ChildComponentClass {...this.props} {...props} />;
    }
  }
}

Could not resolve Spring property placeholder

make sure your properties file exist in classpath directory but not in sub folder of your classpath directory. if it is exist in sub folder then write as below classpath:subfolder/idm.properties

Show data on mouseover of circle

You can pass in the data to be used in the mouseover like this- the mouseover event uses a function with your previously entered data as an argument (and the index as a second argument) so you don't need to use enter() a second time.

vis.selectAll("circle")
.data(datafiltered).enter().append("svg:circle")
.attr("cx", function(d) { return x(d.x);})
.attr("cy", function(d) {return y(d.y)})
.attr("fill", "red").attr("r", 15)
.on("mouseover", function(d,i) {
    d3.select(this).append("text")
        .text( d.x)
        .attr("x", x(d.x))
        .attr("y", y(d.y)); 
});

Duplicating a MySQL table, indices, and data

Go to phpMyAdmin and select your original table then select "Operations" tab in the "Copy table to (database.table)" area. Select the database where you want to copy and add a name for your new table.

copy table - phyMyAdmin Screenshot

How do you cache an image in Javascript

I have a similar answer for asynchronous preloading images via JS. Loading them dynamically is the same as loading them normally. they will cache.

as for caching, you can't control the browser but you can set it via server. if you need to load a really fresh resource on demand, you can use the cache buster technique to force load a fresh resource.

JS strings "+" vs concat method

You can try with this code (Same case)

chaine1 + chaine2; 

I suggest you also (I prefer this) the string.concat method

When to use virtual destructors?

Declare destructors virtual in polymorphic base classes. This is Item 7 in Scott Meyers' Effective C++. Meyers goes on to summarize that if a class has any virtual function, it should have a virtual destructor, and that classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors.

Why is char[] preferred over String for passwords?

Strings are immutable. That means once you've created the String, if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before garbage collection kicks in.

With an array, you can explicitly wipe the data after you're done with it. You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.

So yes, this is a security concern - but even using char[] only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.

As noted in the comments, it's possible that arrays being moved by the garbage collector will leave stray copies of the data in memory. I believe this is implementation-specific - the garbage collector may clear all memory as it goes, to avoid this sort of thing. Even if it does, there's still the time during which the char[] contains the actual characters as an attack window.

How to implement a Navbar Dropdown Hover in Bootstrap v4?

I think this simply just work with bootstrap 4, i adding in inline but you always can bind event from script.

  <a 
onmouseover="$('#navbarDropdownMenuLink').dropdown('toggle')"
class="nav-link dropdown-toggle" 
href="http://example.com" 
id="navbarDropdownMenuLink" 
data-toggle="dropdown" 
aria-haspopup="true" 
aria-expanded="false">
      Dropdown link
    </a>

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

How to create an array of object literals in a loop?

In the same idea of Nick Riggs but I create a constructor, and a push a new object in the array by using it. It avoid the repetition of the keys of the class:

var arr = [];
var columnDefs = function(key, sortable, resizeable){
    this.key = key; 
    this.sortable = sortable; 
    this.resizeable = resizeable;
    };

for (var i = 0; i < len; i++) {
    arr.push((new columnDefs(oFullResponse.results[i].label,true,true)));
}

SQL Server: IF EXISTS ; ELSE

Try this:

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

Hashing with SHA1 Algorithm in C#

You can "compute the value for the specified byte array" using ComputeHash:

var hash = sha1.ComputeHash(temp);

If you want to analyse the result in string representation, then you will need to format the bytes using the {0:X2} format specifier.

Is there a way to specify which pytest tests to run from a file?

Specifying tests / selecting tests

Pytest supports several ways to run and select tests from the command-line.

Run tests in a module

pytest test_mod.py

Run tests in a directory

pytest testing/

Run tests by keyword expressions

pytest -k "MyClass and not method"

This will run tests which contain names that match the given string expression, which can include Python operators that use filenames, class names and function names as variables. The example above will run TestMyClass.test_something but not TestMyClass.test_method_simple.

Run tests by node ids

Each collected test is assigned a unique nodeid which consist of the module filename followed by specifiers like class names, function names and parameters from parametrization, separated by :: characters.

To run a specific test within a module:

pytest test_mod.py::test_func

Another example specifying a test method in the command line:

pytest test_mod.py::TestClass::test_method

Run tests by marker expressions

pytest -m slow

Will run all tests which are decorated with the @pytest.mark.slow decorator.

For more information see marks.

Run tests from packages

pytest --pyargs pkg.testing

This will import pkg.testing and use its filesystem location to find and run tests from.

Source: https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests

How to render a PDF file in Android

you can use a simple method by import

implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

and the XML code is

<com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.github.barteksc.pdfviewer.PDFView>

and just declare and add a file to an asset folder and just assign the name

   PDFView  pdfView=findViewById(R.id.pdfv);       
    pdfView.fromAsset("agl.pdf").load();

Asynchronous method call in Python?

It's not in the language core, but a very mature library that does what you want is Twisted. It introduces the Deferred object, which you can attach callbacks or error handlers ("errbacks") to. A Deferred is basically a "promise" that a function will have a result eventually.

Disable submit button ONLY after submit

This is the edited script, hope it helps,

   <script type="text/javascript">
        $(function(){
            $("#yourFormId").on('submit', function(){
                return false;
                $(".submitBtn").attr("disabled",true); //disable the submit here
                //send the form data via ajax which will not relaod the page and disable the submit button
                $.ajax({
                   url      : //your url to submit the form,
                   data     : { $("#yourFormId").serializeArray() }, //your data to send here 
                   type     : 'POST',
                   success  : function(resp){
                        alert(resp);    //or whatever 
                   },
                   error    : function(resp){

                   }
                });
            })
        });
    </script>

How to determine the first and last iteration in a foreach loop?

With Keys and Values this works as well:

foreach ($array as $key => $value) {
    if ($value === end($array)) {
        echo "LAST ELEMENT!";
    }
}

Database, Table and Column Naming Conventions?

Late answer here, but in short:

  1. Plural table names: My preference is plural
  2. Singular column names: Yes
  3. Prefix tables or columns:
  • Tables: *Usually* no prefixes is best.
  • Columns: No.
  1. Use any case in naming items: PascalCase for both tables and columns.

Elaboration:

(1) What you must do. There are very few things that you must do a certain way, every time, but there are a few.

  • Name your primary keys using "[singularOfTableName]ID" format. That is, whether your table name is Customer or Customers, the primary key should be CustomerID.
  • Further, foreign keys must be named consistently in different tables. It should be legal to beat up someone who does not do this. I would submit that while defined foreign key constraints are often important, consistent foreign key naming is always important
  • You database must have internal conventions. Even though in later sections you'll see me being very flexible, within a database naming must be very consistent . Whether your table for customers is called Customers or Customer is less important than that you do it the same way throughout the same database. And you can flip a coin to determine how to use underscores, but then you must keep using them the same way. If you don't do this, you are a bad person who should have low self-esteem.

(2) What you should probably do.

  • Fields representing the same kind of data on different tables should be named the same. Don't have Zip on one table and ZipCode on another.
  • To separate words in your table or column names, use PascalCasing. Using camelCasing would not be intrinsically problematic, but that's not the convention and it would look funny. I'll address underscores in a moment. (You may not use ALLCAPS as in the olden days. OBNOXIOUSTABLE.ANNOYING_COLUMN was okay in DB2 20 years ago, but not now.)
  • Don't artifically shorten or abbreviate words. It is better for a name to be long and clear than short and confusing. Ultra-short names is a holdover from darker, more savage times. Cus_AddRef. What on earth is that? Custodial Addressee Reference? Customer Additional Refund? Custom Address Referral?

(3) What you should consider.

  • I really think you should have plural names for tables; some think singular. Read the arguments elsewhere. Column names should be singular however. Even if you use plural table names, tables that represent combinations of other tables might be in the singular. For example, if you have a Promotions and an Items table, a table representing an item being a part of a promotion could be Promotions_Items, but it could also legitimately be Promotion_Items I think (reflecting the one-to-many relationship).
  • Use underscores consistently and for a particular purpose. Just general tables names should be clear enough with PascalCasing; you don't need underscores to separate words. Save underscores either (a) to indicate an associative table or (b) for prefixing, which I'll address in the next bullet.
  • Prefixing is neither good or bad. It usually is not best. In your first db or two, I would not suggest using prefixes for general thematic grouping of tables. Tables end up not fitting your categories easily, and it can actually make it harder to find tables. With experience, you can plan and apply a prefixing scheme that does more good than harm. I worked in a db once where data tables began with tbl, config tables with ctbl, views with vew, proc's sp, and udf's fn, and a few others; it was meticulously, consistently applied so it worked out okay. The only time you NEED prefixes is when you have really separate solutions that for some reason reside in the same db; prefixing them can be very helpful in grouping the tables. Prefixing is also okay for special situations, like for temporary tables that you want to stand out.
  • Very seldom (if ever) would you want to prefix columns.

Change a column type from Date to DateTime during ROR migration

First in your terminal:

rails g migration change_date_format_in_my_table

Then in your migration file:

For Rails >= 3.2:

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
    change_column :my_table, :my_column, :datetime
  end

  def down
    change_column :my_table, :my_column, :date
  end
end

Find out the history of SQL queries

For recent SQL:

select * from v$sql

For history:

select * from dba_hist_sqltext

What version of MongoDB is installed on Ubuntu

In the terminal just enter the traditional command:

mongod --version

Python 3 - Encode/Decode vs Bytes/Str

To add to Lennart Regebro's answer There is even the third way that can be used:

encoded3 = str.encode(original, 'utf-8')
print(encoded3)

Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.


A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.

Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.

In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".

The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.

SQL server stored procedure return a table

You can use an out parameter instead of the return value if you want both a result set and a return value

CREATE PROCEDURE proc_name 
@param int out
AS
BEGIN
    SET @param = value
SELECT ... FROM [Table] WHERE Condition
END
GO

Java - How to create a custom dialog box?

Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

The ideas provided above are good. For fast access (in case you would like to make a real time application) you could try the following:

//suppose you read an image from a file that is gray scale
Mat image = imread("Your path", CV_8UC1);
//...do some processing
uint8_t *myData = image.data;
int width = image.cols;
int height = image.rows;
int _stride = image.step;//in case cols != strides
for(int i = 0; i < height; i++)
{
    for(int j = 0; j < width; j++)
    {
        uint8_t val = myData[ i * _stride + j];
        //do whatever you want with your value
    }
}

Pointer access is much faster than the Mat.at<> accessing. Hope it helps!

Select objects based on value of variable in object using jq

To obtain a stream of just the names:

$ jq '.[] | select(.location=="Stockholm") | .name' json

produces:

"Donald"
"Walt"

To obtain a stream of corresponding (key name, "name" attribute) pairs, consider:

$ jq -c 'to_entries[]
        | select (.value.location == "Stockholm")
        | [.key, .value.name]' json

Output:

["FOO","Donald"]
["BAR","Walt"]

How do I remove a single file from the staging area (undo git add)?

git checkout -- <file>

It works perfectly to remove files from Staging Area

How do I fix the npm UNMET PEER DEPENDENCY warning?

you can resolve by installing the UNMET dependencies globally.

example : npm install -g @angular/[email protected]

install each one by one. its worked for me.

What are the "spec.ts" files generated by Angular CLI for?

if you generate new angular project using "ng new", you may skip a generating of spec.ts files. For this you should apply --skip-tests option.

ng new ng-app-name --skip-tests

json Uncaught SyntaxError: Unexpected token :

That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character

How do I convert NSMutableArray to NSArray?

Objective-C

Below is way to convert NSMutableArray to NSArray:

//oldArray is having NSMutableArray data-type.
//Using Init with Array method.
NSArray *newArray1 = [[NSArray alloc]initWithArray:oldArray];

//Make copy of array
NSArray *newArray2 = [oldArray copy];

//Make mutablecopy of array
NSArray *newArray3 = [oldArray mutableCopy];

//Directly stored NSMutableArray to NSArray.
NSArray *newArray4 = oldArray;

Swift

In Swift 3.0 there is new data type Array. Declare Array using let keyword then it would become NSArray And if declare using var keyword then it's become NSMutableArray.

Sample code:

let newArray = oldArray as Array

Time calculation in php (add 10 hours)?

Full code that shows now and 10 minutes added.....

$nowtime = date("Y-m-d H:i:s");
echo $nowtime;
$date = date('Y-m-d H:i:s', strtotime($nowtime . ' + 10 minute'));
echo "<br>".$date;

Scale iFrame css width 100% like an image

I suppose this is a cleaner approach. It works with inline height and width properties (I set random value in the fiddle to prove that) and with CSS max-width property.

HTML:

<div class="wrapper">
    <div class="h_iframe">
        <iframe height="2" width="2" src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe>
    </div>
    <p>Please scale the "result" window to notice the effect.</p>
</div>

CSS:

html,body        {height: 100%;}
.wrapper         {width: 80%; max-width: 600px; height: 100%; margin: 0 auto; background: #CCC}
.h_iframe        {position: relative; padding-top: 56%;}
.h_iframe iframe {position: absolute; top: 0; left: 0; width: 100%; height: 100%;}

http://jsfiddle.net/7WRHM/1001/

CSS Image size, how to fill, but not stretch?

This will Fill images to a specific size, without stretching it or without cropping it

img{
    width:150px;  //your requirement size
    height:100px; //your requirement size

/*Scale down will take the necessary specified space that is 150px x 100px without stretching the image*/
    object-fit:scale-down;
}

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

There are two ways of doing it.

1.Right click on drawable New->Image Asset-> select your highest resolution image rest will be created automatically. once you finish you can see different resolution inside drawable folder

  1. The way you want. on the project Explorer window you see a dropdown as Android. Click it change to project.

Now yourprojectname->app->src->main->res->

Aila You can see your drawable folders with hdpi mdpi etc.

Only variables should be passed by reference

PHP complains because end() expects a reference to something that it wants to change (which can be a variable only). You however pass the result of explode() directly to end() without saving it to a variable first. At the moment when explode() returns your value, it exists only in memory and no variable points to it. You cannot create a reference to something (or to something unknown in the memory), that does not exists.

Or in other words: PHP does not know, if the value you give him is the direct value or just a pointer to the value (a pointer is also a variable (integer), which stores the offset of the memory, where the actual value resides). So PHP expects here a pointer (reference) always.

But since this is still just a notice (not even deprecated) in PHP 7, you can savely ignore notices and use the ignore-operator instead of completely deactivating error reporting for notices:

$file_extension = @end(explode('.', $file_name));

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

In case you are trying to use ARC app from google and post a XML and you are getting this error, then try changing the body content type to application/xml. Example here

Visual studio code terminal, how to run a command with administrator rights?

Step 1: Restart VS Code as an adminstrator

(click the windows key, search for "Visual Studio Code", right click, and you'll see the administrator option)

Step 2: In your VS code powershell terminal run Set-ExecutionPolicy Unrestricted

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

You could use find along with the -exec flag in a single command line to do the job

find . -name "*.zip" -exec unzip {} \;

How to provide shadow to Button

you can use this great library https://github.com/BluRe-CN/ComplexView and it is really easy to use

How to check if a value exists in an array in Ruby

If you need to check multiples times for any key, convert arr to hash, and now check in O(1)

arr = ['Cat', 'Dog', 'Bird']
hash = arr.map {|x| [x,true]}.to_h
 => {"Cat"=>true, "Dog"=>true, "Bird"=>true}
hash["Dog"]
 => true
hash["Insect"]
 => false

Performance of Hash#has_key? versus Array#include?

Parameter              Hash#has_key?                 Array#include 

Time Complexity         O(1) operation                O(n) operation 

Access Type             Accesses Hash[key] if it      Iterates through each element
                        returns any value then        of the array till it
                        true is returned to the       finds the value in Array
                        Hash#has_key? call
                        call    

For single time check using include? is fine

Cropping an UIImage

Follow Answer of @Arne. I Just fixing to Category function. put it in Category of UIImage.

-(UIImage*)cropImage:(CGRect)rect{

    UIGraphicsBeginImageContextWithOptions(rect.size, false, [self scale]);
    [self drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];
    UIImage* cropped_image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return cropped_image;
}

Copying one structure to another

You can memcpy structs, or you can just assign them like any other value.

struct {int a, b;} c, d;
c.a = c.b = 10;
d = c;

How to configure SMTP settings in web.config

Set IIS to forward your mail to the remote server. The specifics vary greatly depending on the version of IIS. For IIS 7.5:

  1. Open IIS Manager
  2. Connect to your server if needed
  3. Select the server node; you should see an SMTP option on the right in the ASP.NET section
  4. Double-click the SMTP icon.
  5. Select the "Deliver e-mail to SMTP server" option and enter your server name, credentials, etc.

How do I make a transparent border with CSS?

Many of you must be landing here to find a solution for opaque border instead of a transparent one. In that case you can use rgba, where a stands for alpha.

.your_class {
    height: 100px;
    width: 100px;
    margin: 100px;
    border: 10px solid rgba(255,255,255,.5);
}

Demo

Here, you can change the opacity of the border from 0-1


If you simply want a complete transparent border, the best thing to use is transparent, like border: 1px solid transparent;

How to change line color in EditText

i think the best way is by theme:

<style name="MyEditTextTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorControlNormal">@color/black</item>
        <item name="colorControlActivated">@color/action_blue</item>
        <item name="colorControlHighlight">@color/action_blue</item>
</style>

<style name="AddressBookStyle" parent="Theme.AppCompat.Light.DarkActionBar">
     <item name="android:layout_width">match_parent</item>
     <item name="android:layout_height">wrap_content</item>
     <item name="android:textSize">13sp</item>
     <item name="android:theme">@style/MyEditTextTheme</item>
</style>

<android.support.v7.widget.AppCompatEditText
            style="@style/AddressBookStyle"/>

How to get the number of characters in a string

Depends a lot on your definition of what a "character" is. If "rune equals a character " is OK for your task (generally it isn't) then the answer by VonC is perfect for you. Otherwise, it should be probably noted, that there are few situations where the number of runes in a Unicode string is an interesting value. And even in those situations it's better, if possible, to infer the count while "traversing" the string as the runes are processed to avoid doubling the UTF-8 decode effort.

Yes/No message box using QMessageBox

You can use the QMessage object to create a Message Box then add buttons :

QMessageBox msgBox;
msgBox.setWindowTitle("title");
msgBox.setText("Question");
msgBox.setStandardButtons(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
if(msgBox.exec() == QMessageBox::Yes){
  // do something
}else {
  // do something else
}

CMake not able to find OpenSSL library

fixed it on macOS using

brew install openssl
cmake -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl -DOPENSSL_LIBRARIES=/usr/local/opt/openssl/lib

Multiple definition of ... linker error

Don't define variables in headers. Put declarations in header and definitions in one of the .c files.

In config.h

extern const char *names[];

In some .c file:

const char *names[] =
    {
        "brian", "stefan", "steve"
    };

If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.

How do I convert a string to a double in Python?

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

Random float number generation

In my opinion the above answer do give some 'random' float, but none of them is truly a random float (i.e. they miss a part of the float representation). Before I will rush into my implementation lets first have a look at the ANSI/IEEE standard format for floats:

|sign (1-bit)| e (8-bits) | f (23-bit) |

the number represented by this word is (-1 * sign) * 2^e * 1.f

note the the 'e' number is a biased (with a bias of 127) number thus ranging from -127 to 126. The most simple (and actually most random) function is to just write the data of a random int into a float, thus

int tmp = rand();
float f = (float)*((float*)&tmp);

note that if you do float f = (float)rand(); it will convert the integer into a float (thus 10 will become 10.0).

So now if you want to limit the maximum value you can do something like (not sure if this works)

int tmp = rand();
float f = *((float*)&tmp);
tmp = (unsigned int)f       // note float to int conversion!
tmp %= max_number;
f -= tmp;

but if you look at the structure of the float you can see that the maximum value of a float is (approx) 2^127 which is way larger as the maximum value of an int (2^32) thus ruling out a significant part of the numbers that can be represented by a float. This is my final implementation:

/**
 * Function generates a random float using the upper_bound float to determine 
 * the upper bound for the exponent and for the fractional part.
 * @param min_exp sets the minimum number (closest to 0) to 1 * e^min_exp (min -127)
 * @param max_exp sets the maximum number to 2 * e^max_exp (max 126)
 * @param sign_flag if sign_flag = 0 the random number is always positive, if 
 *              sign_flag = 1 then the sign bit is random as well
 * @return a random float
 */
float randf(int min_exp, int max_exp, char sign_flag) {
    assert(min_exp <= max_exp);

    int min_exp_mod = min_exp + 126;

    int sign_mod = sign_flag + 1;
    int frac_mod = (1 << 23);

    int s = rand() % sign_mod;  // note x % 1 = 0
    int e = (rand() % max_exp) + min_exp_mod;
    int f = rand() % frac_mod;

    int tmp = (s << 31) | (e << 23) | f;

    float r = (float)*((float*)(&tmp));

    /** uncomment if you want to see the structure of the float. */
//    printf("%x, %x, %x, %x, %f\n", (s << 31), (e << 23), f, tmp, r);

    return r;
}

using this function randf(0, 8, 0) will return a random number between 0.0 and 255.0

How to make return key on iPhone make keyboard disappear?

After quite a bit of time hunting down something that makes sense, this is what I put together and it worked like a charm.

.h

//
//  ViewController.h
//  demoKeyboardScrolling
//
//  Created by Chris Cantley on 11/14/13.
//  Copyright (c) 2013 Chris Cantley. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>

// Connect your text field to this the below property.
@property (weak, nonatomic) IBOutlet UITextField *theTextField;

@end

.m

//
//  ViewController.m
//  demoKeyboardScrolling
//
//  Created by Chris Cantley on 11/14/13.
//  Copyright (c) 2013 Chris Cantley. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
    // _theTextField is the name of the parameter designated in the .h file. 
    _theTextField.returnKeyType = UIReturnKeyDone;
    [_theTextField setDelegate:self];

}

// This part is more dynamic as it closes the keyboard regardless of what text field 
// is being used when pressing return.  
// You might want to control every single text field separately but that isn't 
// what this code do.
-(void)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
}


@end

Hope this helps!

How to return value from function which has Observable subscription inside?

If you want to pre-subscribe to the same Observable which will be returned, just use

.do():

function getValueFromObservable() {
    return this.store.do(
        (data:any) => {
            console.log("Line 1: " +data);
        }
    );
}

getValueFromObservable().subscribe(
        (data:any) => {
            console.log("Line 2: " +data)
        }
    );

Is it possible to import a whole directory in sass using @import?

You might want to retain source order then you can just use this.

@import
  'foo',
  'bar';

I prefer this.

lodash multi-column sortBy descending

In the documentation of the version 4.11.x, says: ` "This method is like _.sortBy except that it allows specifying the sort orders of the iteratees to sort by. If orders is unspecified, all values are sorted in ascending order. Otherwise, specify an order of "desc" for descending or "asc" for ascending sort order of corresponding values." (source https://lodash.com/docs/4.17.10#orderBy)

let sorted = _.orderBy(this.items, ['fieldFoo', 'fieldBar'], ['asc', 'desc'])

jQuery Scroll to bottom of page/iframe

For example:

$('html, body').scrollTop($(document).height());

Error 500: Premature end of script headers

In my case it was a cache directory that wasn't so big, only 17MB but duo to the file structure it took forever to be accessed by the website and was producing that error after max_execution_time was reached.

I renamed the directory to cache-BK and created a new cache directory with the same permissions and that solved the problem.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

The count method of NSArray returns an NSUInteger, and on the 64-bit OS X platform

  • NSUInteger is defined as unsigned long, and
  • unsigned long is a 64-bit unsigned integer.
  • int is a 32-bit integer.

So int is a "smaller" datatype than NSUInteger, therefore the compiler warning.

See also NSUInteger in the "Foundation Data Types Reference":

When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.

To fix that compiler warning, you can either declare the local count variable as

NSUInteger count;

or (if you are sure that your array will never contain more than 2^31-1 elements!), add an explicit cast:

int count = (int)[myColors count];

Call of overloaded function is ambiguous

Cast the value so the compiler knows which function to call:

p.setval(static_cast<const char *>( 0 ));

Note, that you have a segmentation fault in your code after you get it to compile (depending on which function you really wanted to call).

How to kill an application with all its activities?

Using onBackPressed() method:

@Override
public void onBackPressed() {    
    android.os.Process.killProcess(android.os.Process.myPid());
}

or use the finish() method, I have something like

//Password Error, I call function
    Quit();             


    protected void Quit() {
        super.finish();
    }

With super.finish() you close the super class's activity.

Safely casting long to int in Java

Java integer types are represented as signed. With an input between 231 and 232 (or -231 and -232) the cast would succeed but your test would fail.

What to check for is whether all of the high bits of the long are all the same:

public static final long LONG_HIGH_BITS = 0xFFFFFFFF80000000L;
public static int safeLongToInt(long l) {
    if ((l & LONG_HIGH_BITS) == 0 || (l & LONG_HIGH_BITS) == LONG_HIGH_BITS) {
        return (int) l;
    } else {
        throw new IllegalArgumentException("...");
    }
}

Get month and year from a datetime in SQL Server 2005

Use:

select datepart(mm,getdate())  --to get month value
select datename(mm,getdate())  --to get name of month

Convert wchar_t to char

In general, no. int(wchar_t(255)) == int(char(255)) of course, but that just means they have the same int value. They may not represent the same characters.

You would see such a discrepancy in the majority of Windows PCs, even. For instance, on Windows Code page 1250, char(0xFF) is the same character as wchar_t(0x02D9) (dot above), not wchar_t(0x00FF) (small y with diaeresis).

Note that it does not even hold for the ASCII range, as C++ doesn't even require ASCII. On IBM systems in particular you may see that 'A' != 65

JQuery Parsing JSON array

getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

You can get all the values in an array using a for loop:

$.getJSON("url_with_json_here", function(data){
    for (var i = 0, len = data.length; i < len; i++) {
        console.log(data[i]);
    }
});

Check your console to see the output (Chrome, Firefox/Firebug, IE).

jQuery also provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (index, value) {
        console.log(value);
    });
});

What's the difference between interface and @interface in java?

The interface keyword indicates that you are declaring a traditional interface class in Java.
The @interface keyword is used to declare a new annotation type.

See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface means.

Insert array into MySQL database with PHP

Here is my full solution to this based on the accepted answer.

Usage example:

include("./assets/php/db.php");
$data = array('field1' => 'data1', 'field2'=> 'data2');
insertArr("databaseName.tableName", $data);

db.php

<?PHP
/**
 * Class to initiate a new MySQL connection based on $dbInfo settings found in dbSettings.php
 *
 * @example
 *    $db = new database(); // Initiate a new database connection
 *    mysql_close($db->get_link());
 */
class database{
    protected $databaseLink;
    function __construct(){
        include "dbSettings.php";
        $this->database = $dbInfo['host'];
        $this->mysql_user = $dbInfo['user'];
        $this->mysql_pass = $dbInfo['pass'];
        $this->openConnection();
        return $this->get_link();
    }
    function openConnection(){
    $this->databaseLink = mysql_connect($this->database, $this->mysql_user, $this->mysql_pass);
    }

    function get_link(){
    return $this->databaseLink;
    }
}

/**
 * Insert an associative array into a MySQL database
 *
 * @example
 *    $data = array('field1' => 'data1', 'field2'=> 'data2');
 *    insertArr("databaseName.tableName", $data);
 */
function insertArr($tableName, $insData){
    $db = new database();
    $columns = implode(", ",array_keys($insData));
    $escaped_values = array_map('mysql_real_escape_string', array_values($insData));
    foreach ($escaped_values as $idx=>$data) $escaped_values[$idx] = "'".$data."'";
    $values  = implode(", ", $escaped_values);
    $query = "INSERT INTO $tableName ($columns) VALUES ($values)";
    mysql_query($query) or die(mysql_error());
    mysql_close($db->get_link());
}
?>

dbSettings.php

<?PHP
$dbInfo = array(
    'host'      => "localhost",
    'user'      => "root",
    'pass'      => "password"
);
?>

css h1 - only as wide as the text

This is because your <h1> is the width of the centercol. Specify a width on the <h1> and use margin: 0 auto; if you want it centered.

Or, alternatively, you could float the <h1>, which would make it only exactly as wide as the text.

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

add this to your my.cnf

innodb_buffer_pool_size=1G

restart your mysql to make it effect

Can you remove elements from a std::list while iterating through it?

do while loop, it's flexable and fast and easy to read and write.

auto textRegion = m_pdfTextRegions.begin();
    while(textRegion != m_pdfTextRegions.end())
    {
        if ((*textRegion)->glyphs.empty())
        {
            m_pdfTextRegions.erase(textRegion);
            textRegion = m_pdfTextRegions.begin();
        }
        else
            textRegion++;
    } 

How to set environment variable or system property in spring tests?

The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

See @TestPropertySource in the Spring docs and Javadocs.

Appending a list to a list of lists in R

The purrr package has a lot of handy functions for working on lists. The flatten command can clean up unwanted nesting.

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

nested_outlist <- list(resultsa, resultsb, resultsc)
outlist <- purrr::flatten(nested_outlist)

How to find the last field using 'cut'

This is the only solution possible for using nothing but cut:

echo "s.t.r.i.n.g." | cut -d'.' -f2- [repeat_following_part_forever_or_until_out_of_memory:] | cut -d'.' -f2-

Using this solution, the number of fields can indeed be unknown and vary from time to time. However as line length must not exceed LINE_MAX characters or fields, including the new-line character, then an arbitrary number of fields can never be part as a real condition of this solution.

Yes, a very silly solution but the only one that meets the criterias I think.

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

How do I write a Windows batch script to copy the newest file from a directory?

@echo off
set source="C:\test case"
set target="C:\Users\Alexander\Desktop\random folder"

FOR /F "delims=" %%I IN ('DIR %source%\*.* /A:-D /O:-D /B') DO COPY %source%\"%%I" %target% & echo %%I & GOTO :END
:END
TIMEOUT 4

My attempt to copy the newest file from a folder

just set your source and target folders and it should work

This one ignores folders, concern itself only with files

Recommed that you choose filetype in the DIR path changing *.* to *.zip for example

TIMEOUT wont work on winXP I think

How to sum up elements of a C++ vector?

Why perform the summation forwards when you can do it backwards? Given:

std::vector<int> v;     // vector to be summed
int sum_of_elements(0); // result of the summation

We can use subscripting, counting backwards:

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v[i-1];

We can use range-checked "subscripting," counting backwards (just in case):

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v.at(i-1);

We can use reverse iterators in a for loop:

for(std::vector<int>::const_reverse_iterator i(v.rbegin()); i != v.rend(); ++i)
    sum_of_elements += *i;

We can use forward iterators, iterating backwards, in a for loop (oooh, tricky!):

for(std::vector<int>::const_iterator i(v.end()); i != v.begin(); --i)
    sum_of_elements += *(i - 1);

We can use accumulate with reverse iterators:

sum_of_elems = std::accumulate(v.rbegin(), v.rend(), 0);

We can use for_each with a lambda expression using reverse iterators:

std::for_each(v.rbegin(), v.rend(), [&](int n) { sum_of_elements += n; });

So, as you can see, there are just as many ways to sum the vector backwards as there are to sum the vector forwards, and some of these are much more exciting and offer far greater opportunity for off-by-one errors.

using wildcards in LDAP search filters/queries

Your best bet would be to anticipate prefixes, so:

"(|(displayName=SEARCHKEY*)(displayName=ITSM - SEARCHKEY*)(displayName=alt prefix - SEARCHKEY*))"

Clunky, but I'm doing a similar thing within my organization.

Better way to remove specific characters from a Perl string

You could use the tr instead:

       $p =~ tr/fo//d;

will delete every f and every o from $p. In your case it should be:

       $p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d

See Perl's tr documentation.

tr/SEARCHLIST/REPLACEMENTLIST/cdsr

Transliterates all occurrences of the characters found (or not found if the /c modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.

[…]

If the /d modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.

How to create checkbox inside dropdown?

Multiple drop downs with checkbox's and jQuery.

<div id="list3" class="dropdown-check-list" tabindex="100">
<span class="anchor">Which development(s) are you interested in?</span>
  <ul class="items">
      <li><input id="answers_2529_the-lawns" name="answers[2529][answers][]" type="checkbox" value="The Lawns"/><label for="answers_2529_the-lawns">The Lawns</label></li>
      <li><input id="answers_2529_the-residence" name="answers[2529][answers][]" type="checkbox" value="The Residence"/><label for="answers_2529_the-residence">The Residence</label></li>
  </ul>
</div>

<style>
.dropdown-check-list{
display: inline-block;
width: 100%;
}
.dropdown-check-list:focus{
outline:0;
}
.dropdown-check-list .anchor {
width: 98%;
position: relative;
cursor: pointer;
display: inline-block;
padding-top:5px;
padding-left:5px;
padding-bottom:5px;
border:1px #ccc solid;
}
.dropdown-check-list .anchor:after {
position: absolute;
content: "";
border-left: 2px solid black;
border-top: 2px solid black;
padding: 5px;
right: 10px;
top: 20%;
-moz-transform: rotate(-135deg);
-ms-transform: rotate(-135deg);
-o-transform: rotate(-135deg);
-webkit-transform: rotate(-135deg);
transform: rotate(-135deg);
}
.dropdown-check-list .anchor:active:after {
right: 8px;
top: 21%;
}
.dropdown-check-list ul.items {
padding: 2px;
display: none;
margin: 0;
border: 1px solid #ccc;
border-top: none;
}
.dropdown-check-list ul.items li {
list-style: none;
}
.dropdown-check-list.visible .anchor {
color: #0094ff;
}
.dropdown-check-list.visible .items {
display: block;
}
</style>

<script>
jQuery(function ($) {
        var checkList = $('.dropdown-check-list');
        checkList.on('click', 'span.anchor', function(event){
            var element = $(this).parent();

            if ( element.hasClass('visible') )
            {
                element.removeClass('visible');
            }
            else
            {
                element.addClass('visible');
            }
        });
    });
</script>

jQuery Validation plugin: validate check box

You can validate group checkbox and radio button without extra js code, see below example.

Your JS should be look like:

$("#formid").validate();

You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]

<fieldset class="col-md-12">
  <legend>Days</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="2">Tuesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="3">Wednesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="4">Thursday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="5">Friday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="6">Saturday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="7">Sunday
        </label>
        <label for="daysgroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.

eg. group radio button:

<fieldset class="col-md-12">
  <legend>Gender</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="w">woman
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="o">other
        </label>
        <label for="gendergroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can check working example here.

  • jQuery v3.3.x
  • jQuery Validation Plugin - v1.17.0

Set a button group's width to 100% and make buttons equal width?

BOOTSTRAP 2 (source)

The problem is that there is no width set on the buttons. Try this:

.btn {width:20%;}

EDIT:

By default the buttons take an auto width of its text length plus some padding, so I guess for your example it is probably more like 14.5% for 5 buttons (to compensate for the padding).

Note:

If you don't want to try and compensate for padding you can use box-sizing:border-box;

http://www.w3schools.com/cssref/css3_pr_box-sizing.asp

Unable to Connect to GitHub.com For Cloning

I had the same error because I was using proxy. As the answer is given but in case you are using proxy then please set your proxy first using these commands:

git config --global http.proxy http://proxy_username:proxy_password@proxy_ip:port
git config --global https.proxy https://proxy_username:proxy_password@proxy_ip:port

'invalid value encountered in double_scalars' warning, possibly numpy

Zero-size array passed to numpy.mean raises this warning (as indicated in several comments).

For some other candidates:

  • median also raises this warning on zero-sized array.

other candidates do not raise this warning:

  • min,argmin both raise ValueError on empty array
  • randn takes *arg; using randn(*[]) returns a single random number
  • std,var return nan on an empty array

Embed HTML5 YouTube video without iframe?

Yes, but it depends on what you mean by 'embed'; as far as I can tell after reading through the docs, it seems like you have a couple of options if you want to get around using the iframe API. You can use the javascript and flash API's (https://developers.google.com/youtube/player_parameters) to embed a player, but that involves creating Flash objects in your code (something I personally avoid, but not necessarily something that you have to). Below are some helpful sections from the dev docs for the Youtube API.

If you really want to get around all these methods and include video without any sort of iframe, then your best bet might be creating an HTML5 video player/app that can connect to the Youtube Data API (https://developers.google.com/youtube/v3/). I'm not sure what the extent of your needs are, but this would be the way to go if you really want to get around using any iframes or flash objects.

Hope this helps!


Useful:

(https://developers.google.com/youtube/player_parameters)

IFrame embeds using the IFrame Player API

Follow the IFrame Player API instructions to insert a video player in your web page or application after the Player API's JavaScript code has loaded. The second parameter in the constructor for the video player is an object that specifies player options. Within that object, the playerVars property identifies player parameters.

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

...

IFrame embeds using tags

Define an tag in your application in which the src URL specifies the content that the player will load as well as any other player parameters you want to set. The tag's height and width parameters specify the dimensions of the player.

If you are creating the element yourself (rather than using the IFrame Player API to create it), you can append player parameters directly to the end of the URL. The URL has the following format:

...

AS3 object embeds

Object embeds use an tag to specify the player's dimensions and parameters. The sample code below demonstrates how to use an object embed to load an AS3 player that automatically plays the same video as the previous two examples.

How to get the squared symbol (²) to display in a string

I create equations with random numbers in VBA and for x squared put in x^2.

I read each square (or textbox) text into a string.

I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.

Say the hats were at positions 4, 8 and 12.

I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.

I now select each character in turn and change the font to superscript.

Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.

For big powers like x to the 23 I build x^2^3 and the above routine does it.

What is the use of hashCode in Java?

Although hashcode does nothing with your business logic, we have to take care of it in most cases. Because when your object is put into a hash based container(HashSet, HashMap...), the container puts/gets the element's hashcode.

Rails: call another controller action from a controller

The logic you present is not MVC, then not Rails, compatible.

  • A controller renders a view or redirect

  • A method executes code

From these considerations, I advise you to create methods in your controller and call them from your action.

Example:

 def index
   get_variable
 end

 private

 def get_variable
   @var = Var.all
 end

That said you can do exactly the same through different controllers and summon a method from controller A while you are in controller B.

Vocabulary is extremely important that's why I insist much.

How to change identity column values programmatically?

I saw a good article which helped me out at the last moment .. I was trying to insert few rows in a table which had identity column but did it wrongly and have to delete back. Once I deleted the rows then my identity column got changed . I was trying to find an way to update the column which was inserted but - no luck. So, while searching on google found a link ..

  1. Deleted the columns which was wrongly inserted
  2. Use force insert using identity on/off (explained below)

http://beyondrelational.com/modules/2/blogs/28/posts/10337/sql-server-how-do-i-insert-an-explicit-value-into-an-identity-column-how-do-i-update-the-value-of-an.aspx

How to make a hyperlink in telegram without using bots?

First make link with @bold bot . Then Copy text and paste it to remove "via @bold"

jQuery if Element has an ID?

Simple way:

Fox example this is your html,

<div class='classname' id='your_id_name'>
</div>

Jquery code:

if($('.classname').prop('id')=='your_id_name')
{
    //works your_id_name exist (true part)
}
else
{ 
    //works your_id_name not exist (false part)
}

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

Get only filename from url in php without any variable values which exist in the url

$url = "learner.com/learningphp.php?lid=1348";
$l = parse_url($url);
print_r(stristr($l['path'], "/"));

How do you make sure email you send programmatically is not automatically marked as spam?

In the UK it's also best practice to include a real physical address for your company and its registered number.

That way it's all open and honest and they're less likely to manually mark it as spam.

Ignoring new fields on JSON objects using Jackson

Make sure that you place the @JsonIgnoreProperties(ignoreUnknown = true) annotation to the parent POJO class which you want to populate as a result of parsing the JSON response and not the class where the conversion from JSON to Java Object is taking place.

Label encoding across multiple columns in scikit-learn

Instead of LabelEncoder we can use OrdinalEncoder from scikit learn, which allows multi-column encoding.

Encode categorical features as an integer array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are converted to ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature.

>>> from sklearn.preprocessing import OrdinalEncoder
>>> enc = OrdinalEncoder()
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.fit(X)
OrdinalEncoder()
>>> enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> enc.transform([['Female', 3], ['Male', 1]])
array([[0., 2.],
       [1., 0.]])

Both the description and example were copied from its documentation page which you can find here:

https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html#sklearn.preprocessing.OrdinalEncoder

bash shell nested for loop

#!/bin/bash
# loop*figures.bash

for i in 1 2 3 4 5  # First loop.
do
    for j in $(seq 1 $i)
    do
        echo  -n "*" 
    done
    echo 
done
echo
# outputs
# *
# **
# ***
# ****
# *****

for i in 5 4 3 2 1 # First loop.
do
    for j in $(seq -$i -1)
    do
        echo  -n "*" 
    done
    echo 
done

# outputs
# *****
# ****
# ***
# **
# *

for i in 1 2 3 4 5  # First loop.
do
    for k in $(seq -5 -$i)
    do
        echo -n ' '
    done
    for j in $(seq 1 $i)
    do
        echo  -n "* " 
    done
    echo 
done
echo

# outputs
#     * 
#    * * 
#   * * * 
#  * * * * 
# * * * * * 

for i in 1 2 3 4 5  # First loop.
do
    for j in $(seq -5 -$i)
    do
        echo  -n "* " 
    done
    echo 
    for k in $(seq 1 $i)
    do
        echo -n ' '
    done
done
echo

# outputs
# * * * * * 
#  * * * * 
#   * * * 
#    * * 
#     *


exit 0

Check if a string within a list contains a specific string with Linq

If yoou use Contains, you could get false positives. Suppose you have a string that contains such text: "My text data Mdd LH" Using Contains method, this method will return true for call. The approach is use equals operator:

bool exists = myStringList.Any(c=>c == "Mdd LH")

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

How to clone a Date object?

Use the Date object's getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (epoch time):

var date = new Date();
var copiedDate = new Date(date.getTime());

In Safari 4, you can also write:

var date = new Date();
var copiedDate = new Date(date);

...but I'm not sure whether this works in other browsers. (It seems to work in IE8).

Why cannot change checkbox color whatever I do?

One line of CSS is enough using hue-rotate filter. You can change their sizes with transform: scale() as well.

.checkbox { filter: hue-rotate(0deg) }

Codepen

_x000D_
_x000D_
.c1 { filter: hue-rotate(0deg)   }
.c2 { filter: hue-rotate(30deg)  }
.c3 { filter: hue-rotate(60deg)  }
.c4 { filter: hue-rotate(90deg)  }
.c5 { filter: hue-rotate(120deg) }
.c6 { filter: hue-rotate(150deg) }
.c7 { filter: hue-rotate(180deg) }
.c8 { filter: hue-rotate(210deg) }
.c9 { filter: hue-rotate(240deg) }

input[type=checkbox] {
  transform: scale(2);
  margin: 10px;
  cursor: pointer;
}

/* Prevent cursor being `text` between checkboxes */
body { cursor: default }
_x000D_
<input type="checkbox" class="c1" />
<input type="checkbox" class="c2" />
<input type="checkbox" class="c3" />
<input type="checkbox" class="c4" />
<input type="checkbox" class="c5" />
<input type="checkbox" class="c6" />
<input type="checkbox" class="c7" />
<input type="checkbox" class="c8" />
<input type="checkbox" class="c9" />
_x000D_
_x000D_
_x000D_

'MOD' is not a recognized built-in function name

for your exact sample, it should be like this.

DECLARE @m INT
SET @m = 321%11
SELECT @m

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had this issue after converting my Write-Host cmdlets to Write-Information and I was missing quotes and parens around the parameters. The cmdlet signatures are evidently not the same.

Write-Host this is a good idea $here
Write-Information this is a good idea $here <=BAD

This is the cmdlet signature that corrected after spending 20-30 minutes digging down the function stack...

Write-Information ("this is a good idea $here") <=GOOD

Embedding VLC plugin on HTML page

I found this:

<embed type="application/x-vlc-plugin"
pluginspage="http://www.videolan.org"version="VideoLAN.VLCPlugin.2"  width="100%"        
height="100%" id="vlc" loop="yes"autoplay="yes" target="http://10.1.2.201:8000/"></embed>

I don't see that in your code anywhere.... I think that's all you need and the target would be the location of your video...

and here is more info on the vlc plugin:
http://wiki.videolan.org/Documentation%3aWebPlugin#Input_object

Another thing to check is that the address for the video file is correct....

Revert a jQuery draggable object back to its original container on out event of droppable

I'm not sure if this will work for your actual use, but it works in your test case - updated at http://jsfiddle.net/sTD8y/27/ .

I just made it so that the built-in revert is only used if the item has not been dropped before. If it has been dropped, the revert is done manually. You could adjust this to animate to some calculated offset by checking the actual CSS properties, but I'll let you play with that because a lot of it depends on the CSS of the draggable and it's surrounding DOM structure.

$(function() {
    $("#draggable").draggable({
        revert:  function(dropped) {
             var $draggable = $(this),
                 hasBeenDroppedBefore = $draggable.data('hasBeenDropped'),
                 wasJustDropped = dropped && dropped[0].id == "droppable";
             if(wasJustDropped) {
                 // don't revert, it's in the droppable
                 return false;
             } else {
                 if (hasBeenDroppedBefore) {
                     // don't rely on the built in revert, do it yourself
                     $draggable.animate({ top: 0, left: 0 }, 'slow');
                     return false;
                 } else {
                     // just let the built in revert work, although really, you could animate to 0,0 here as well
                     return true;
                 }
             }
        }
    });

    $("#droppable").droppable({
        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(event, ui) {
            $(this).addClass('ui-state-highlight').find('p').html('Dropped!');
            $(ui.draggable).data('hasBeenDropped', true);
        }
    });
});

Processing Symbol Files in Xcode

Add SDK version correspond to your iPhone iOS, eg: iOS 10.3

path:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport


It's downloading. When it's finished, it's OK. As shown in the figure:

enter image description here

gdb: how to print the current line or find the current line number?

The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:

(gdb) frame
\#0  zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139         int rc = fq.recv (msg_);
(gdb)

Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.

Mockito verify order / sequence of method calls

InOrder helps you to do that.

ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);

Mockito.doNothing().when(firstMock).methodOne();   
Mockito.doNothing().when(secondMock).methodTwo();  

//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();

PHP: trying to create a new line with "\n"

It will be written on a new line if you examine the source code of the page. If you want it to appear on a new line when it is rendered in the browser, you'll have use a <br /> tag instead.

Pipe to/from the clipboard in Bash script

  xsel -b

Does the job for X Window, and it is mostly already installed. A look in the man page of xsel is worth the effort.

UIButton action in table view cell

class TableViewCell: UITableViewCell {
   @IBOutlet weak var oneButton: UIButton!
   @IBOutlet weak var twoButton: UIButton!
}


class TableViewController: UITableViewController {

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell

    cell.oneButton.addTarget(self, action: #selector(TableViewController.oneTapped(_:)), for: .touchUpInside)
    cell.twoButton.addTarget(self, action: #selector(TableViewController.twoTapped(_:)), for: .touchUpInside)

    return cell
}

func oneTapped(_ sender: Any?) {

    print("Tapped")
}

func twoTapped(_ sender: Any?) {

    print("Tapped")
   }
}

How to get WooCommerce order details

WOOCOMMERCE ORDERS IN VERSION 3.0+

Since Woocommerce mega major Update 3.0+ things have changed quite a lot:

Related:
How to get Customer details from Order in WooCommerce?
Get Order items and WC_Order_Item_Product in WooCommerce 3

So the Order items properties will not be accessible as before in a foreach loop and you will have to use these specific getter and setter methods instead.

Using some WC_Order and WC_Abstract_Order methods (example):

// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );

$order_id  = $order->get_id(); // Get the order ID
$parent_id = $order->get_parent_id(); // Get the parent order ID (for subscriptions…)

$user_id   = $order->get_user_id(); // Get the costumer ID
$user      = $order->get_user(); // Get the WP_User object

$order_status  = $order->get_status(); // Get the order status (see the conditional method has_status() below)
$currency      = $order->get_currency(); // Get the currency used  
$payment_method = $order->get_payment_method(); // Get the payment method ID
$payment_title = $order->get_payment_method_title(); // Get the payment method title
$date_created  = $order->get_date_created(); // Get date created (WC_DateTime object)
$date_modified = $order->get_date_modified(); // Get date modified (WC_DateTime object)

$billing_country = $order->get_billing_country(); // Customer billing country

// ... and so on ...

For order status as a conditional method (where "the_targeted_status" need to be defined and replaced by an order status to target a specific order status):

if ( $order->has_status('completed') ) {
    // Do something
}

Get and access to the order data properties (in an array of values):

// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );

$order_data = $order->get_data(); // The Order data

$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];

## Creation and modified WC_DateTime Object date string ##

// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');

// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();

$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['total'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on

## BILLING INFORMATION:

$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];

## SHIPPING INFORMATION:

$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];

Get the order items and access the data with WC_Order_Item_Product and WC_Order_Item methods:

// Get an instance of the WC_Order object
$order = wc_get_order($order_id);

// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):

    ## Using WC_Order_Item methods ##

    // Item ID is directly accessible from the $item_key in the foreach loop or
    $item_id = $item->get_id();

    ## Using WC_Order_Item_Product methods ##

    $product      = $item->get_product(); // Get the WC_Product object

    $product_id   = $item->get_product_id(); // the Product id
    $variation_id = $item->get_variation_id(); // the Variation id

    $item_type    = $item->get_type(); // Type of the order item ("line_item")

    $item_name    = $item->get_name(); // Name of the product
    $quantity     = $item->get_quantity();  
    $tax_class    = $item->get_tax_class();
    $line_subtotal     = $item->get_subtotal(); // Line subtotal (non discounted)
    $line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
    $line_total        = $item->get_total(); // Line total (discounted)
    $line_total_tax    = $item->get_total_tax(); // Line total tax (discounted)

    ## Access Order Items data properties (in an array of values) ##
    $item_data    = $item->get_data();

    $product_name = $item_data['name'];
    $product_id   = $item_data['product_id'];
    $variation_id = $item_data['variation_id'];
    $quantity     = $item_data['quantity'];
    $tax_class    = $item_data['tax_class'];
    $line_subtotal     = $item_data['subtotal'];
    $line_subtotal_tax = $item_data['subtotal_tax'];
    $line_total        = $item_data['total'];
    $line_total_tax    = $item_data['total_tax'];

    // Get data from The WC_product object using methods (examples)
    $product        = $item->get_product(); // Get the WC_Product object

    $product_type   = $product->get_type();
    $product_sku    = $product->get_sku();
    $product_price  = $product->get_price();
    $stock_quantity = $product->get_stock_quantity();

endforeach;

So using get_data() method allow us to access to the protected data (associative array mode) …

How can I account for period (AM/PM) using strftime?

You used %H (24 hour format) instead of %I (12 hour format).

How to see query history in SQL Server Management Studio

If the queries you are interested in are dynamic queries that fail intermittently, you could log the SQL and the datetime and user in a table at the time the dynamic statement is created. It would be done on a case-by case basis though as it requires specific programming to happen and it takes a littel extra processing time, so do it only for those few queries you are most concerned about. But having a log of the specific statements executed can really help when you are trying to find out why it fails once a month only. Dynamic queries are hard to thoroughly test and sometimes you get one specific input value that just won't work and doing this logging at the time the SQL is created is often the best way to see what specifically wasn in the sql that was built.

How to get a value from a cell of a dataframe?

It doesn't need to be complicated:

val = df.loc[df.wd==1, 'col_name'].values[0]

How to open maximized window with Javascript?

 window.open('your_url', 'popup_name','height=' + screen.height + ',width=' + screen.width + ',resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes')

Draw text in OpenGL ES

Take a look at CBFG and the Android port of the loading/rendering code. You should be able to drop the code into your project and use it straight away.

CBFG - http://www.codehead.co.uk/cbfg

Android loader - http://www.codehead.co.uk/cbfg/TexFont.java

Making the main scrollbar always visible

An alternative approach is to set the width of the html element to 100vw. On many if not most browsers, this negates the effect of scrollbars on the width.

html { width: 100vw; }

How can I zoom an HTML element in Firefox and Opera?

Try this code, this’ll work:

-moz-transform: scale(2);

You can refer to this.

Making a div vertically scrollable using CSS

You can use overflow-y: scroll for vertical scrolling.

_x000D_
_x000D_
<div  style="overflow-y:scroll; height:400px; background:gray">_x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
 </div>
_x000D_
_x000D_
_x000D_

How to define global variable in Google Apps Script

In GAS global variables are not what they are in other languages. They are not constants nor variables available in all routines.

I thought I could use global variables for consistency amongst functions and efficiency as well. But I was wrong as pointed out by some people here at SO.

Global variable will be evaluated at each execution of a script, so not just once every time you run your application.
Global variables CAN be changed in a script (so they are not constants that cannot be changed by accident), but will be reinitialized when another script will be invoked.
There is also a speed penalty on using global variables. If within a function you use the same global variable two or more times, it will be faster to assign a local variable and use that instead.

If you want to preserve variables between all functions in your application, it might be using a cacheService will be best. I found out that looping through all files and folders on a drive takes a LOT of time. But you can store info about files and folders within cache (or even properties) and speed up at least 100 times.

The only way I use global variables now is for some prefixes and for naming widgets.

.attr("disabled", "disabled") issue

UPDATED

DEMO: http://jsbin.com/uneti3/3

your code is wrong, it should be something like this:

 $(bla).click(function() { 
        var disable =  $target.toggleClass('open').hasClass('open');
       $target.prev().prop("disabled", disable);
  });

you are using the toggleClass function in wrong way

malloc for struct and pointer in C

When you allocate memory for struct Vector you just allocate memory for pointer x, i.e. for space, where its value, which contains address, will be placed. So such way you do not allocate memory for the block, on which y.x will reference.

How to check the installed version of React-Native

Just Do a "npm audit" on your project directory and then go to your project package.json file. In the package.json file you will find all the versions and the package names.This should work irrespective of the OS.

How to change dot size in gnuplot

Use the pointtype and pointsize options, e.g.

plot "./points.dat" using 1:2 pt 7 ps 10  

where pt 7 gives you a filled circle and ps 10 is the size.

See: Plotting data.

How to do a SUM() inside a case statement in SQL server

The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.

Example

This one works!

     SELECT t.device,
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This one not (omitted t.device from the select)

     SELECT 
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This will produce your error complaining that I'm grouping for something that is not included in the select

Please, provide all the query to get more support.

Can I try/catch a warning?

I would only recommend using @ to suppress warnings when it's a straight forward operation (e.g. $prop = @($high/($width - $depth)); to skip division by zero warnings). However in most cases it's better to handle.

php - get numeric index of associative array

a solution i came up with... probably pretty inefficient in comparison tho Fosco's solution:

 protected function getFirstPosition(array$array, $content, $key = true) {

  $index = 0;
  if ($key) {
   foreach ($array as $key => $value) {
    if ($key == $content) {
     return $index;
    }
    $index++;
   }
  } else {
   foreach ($array as $key => $value) {
    if ($value == $content) {
     return $index;
    }
    $index++;
   }
  }
 }

How to sort 2 dimensional array by column value?

It's this simple:

var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];

a.sort(sortFunction);

function sortFunction(a, b) {
    if (a[0] === b[0]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}

I invite you to read the documentation.

If you want to sort by the second column, you can do this:

a.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] < b[1]) ? -1 : 1;
    }
}

Get first row of dataframe in Python Pandas based on criteria

This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:

>>> df[condition]

This will return a slice of your dataframe which you can index using iloc. Here are your examples:

  1. Get first row where A > 3 (returns row 2)

    >>> df[df.A > 3].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

If what you actually want is the row number, rather than using iloc, it would be df[df.A > 3].index[0].

  1. Get first row where A > 4 AND B > 3:

    >>> df[(df.A > 4) & (df.B > 3)].iloc[0]
    A    5
    B    4
    C    5
    Name: 4, dtype: int64
    
  2. Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)

    >>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:

>>> def series_or_default(X, condition, default_col, ascending=False):
...     sliced = X[condition]
...     if sliced.shape[0] == 0:
...         return X.sort_values(default_col, ascending=ascending).iloc[0]
...     return sliced.iloc[0]
>>> 
>>> series_or_default(df, df.A > 6, 'A')
A    5
B    4
C    5
Name: 4, dtype: int64

As expected, it returns row 4.

Some dates recognized as dates, some dates not recognized. Why?

This is caused by the regional settings of your computer.

When you paste data into excel it is only a bunch of strings (not dates).

Excel has some logic in it to recognize your current data formats as well as a few similar date formats or obvious date formats where it can assume it is a date. When it is able to match your pasted in data to a valid date then it will format it as a date in the cell it is in.

Your specific example is due to your list of dates is formatted as "m/d/yy" which is US format. it pastes correctly in my excel because I have my regional setting set to "US English" (even though I'm Canadian :) )

If you system is set to Canadian English/French format then it will expect "d/m/yy" format and not recognize any date where the month is > 13.

The best way to import data, that contains dates, into excel is to copy it in this format.

2011-04-22
2011-12-19
2011-11-04
2011-12-08
2011-09-27
2011-09-27
2011-04-01

Which is "yyyy-MM-dd", this format is recognized the same way on every computer I have ever seen (is often refered to as ODBC format or Standard format) where the units are always from greatest to least weight ("yyyy-MM-dd HH:mm:ss.fff") another side effect is it will sort correctly as a string.

To avoid swaping your regional settings back and forth you may consider writting a macro in excel to paste the data in. a simple popup format and some basic logic to reformat the dates would not be too difficult.

Using OpenSSL what does "unable to write 'random state'" mean?

One other issue on the Windows platform, make sure you are running your command prompt as an Administrative User!

I don't know how many times this has bitten me...

Cannot get a text value from a numeric cell “Poi”

This will work:

WebElement searchbox = driver.findElement(By.name("j_username"));
WebElement searchbox2 = driver.findElement(By.name("j_password"));         


try {

      FileInputStream file = new FileInputStream(new File("C:\\paulo.xls")); 
      HSSFWorkbook workbook = new HSSFWorkbook(file);

      HSSFSheet sheet = workbook.getSheetAt(0);

    for (int i=1; i <= sheet.getLastRowNum(); i++){

            HSSFCell j_username = sheet.getRow(i).getCell(0)
            HSSFCell j_password = sheet.getRow(i).getCell(0)

            //Setting the Cell type as String
            j_username.setCellType(j_username.CELL_TYPE_STRING)
            j_password.setCellType(j_password.CELL_TYPE_STRING)

            searchbox.sendKeys(j_username.toString());
            searchbox2.sendKeys(j_password.toString());


            searchbox.submit();       

            driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);

    }

      workbook.close();
      file.close();

     } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
     } catch (IOException ioe) {
      ioe.printStackTrace();
     }

How do I return the response from an asynchronous call?

Js is a single threaded.

Browser can be divided into three parts:

1)Event Loop

2)Web API

3)Event Queue

Event Loop runs for forever i.e kind of infinite loop.Event Queue is where all your function are pushed on some event(example:click) this is one by one carried out of queue and put into Event loop which execute this function and prepares it self for next one after first one is executed.This means Execution of one function doesn't starts till the function before it in queue is executed in event loop.

Now let us think we pushed two functions in a queue one is for getting a data from server and another utilises that data.We pushed the serverRequest() function in queue first then utiliseData() function. serverRequest function goes in event loop and makes a call to server as we never know how much time it will take to get data from server so this process is expected to take time and so we busy our event loop thus hanging our page, that's where Web API come into role it take this function from event loop and deals with server making event loop free so that we can execute next function from queue.The next function in queue is utiliseData() which goes in loop but because of no data available it goes waste and execution of next function continues till end of the queue.(This is called Async calling i.e we can do something else till we get data)

Let suppose our serverRequest() function had a return statement in a code, when we get back data from server Web API will push it in queue at the end of queue. As it get pushed at end in queue we cannot utilise its data as there is no function left in our queue to utilise this data.Thus it is not possible to return something from Async Call.

Thus Solution to this is callback or promise.

A Image from one of the answers here, Correctly explains callback use... We give our function(function utilising data returned from server) to function calling server.

CallBack

 function doAjax(callbackFunc, method, url) {
  var xmlHttpReq = new XMLHttpRequest();
  xmlHttpReq.open(method, url);
  xmlHttpReq.onreadystatechange = function() {

      if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
        callbackFunc(xmlHttpReq.responseText);
      }


  }
  xmlHttpReq.send(null);

}

In my Code it is called as

function loadMyJson(categoryValue){
  if(categoryValue==="veg")
  doAjax(print,"GET","http://localhost:3004/vegetables");
  else if(categoryValue==="fruits")
  doAjax(print,"GET","http://localhost:3004/fruits");
  else 
  console.log("Data not found");
}

Javscript.info callback

Create 3D array using Python

You can also use a nested for loop like shown below

n = 3
arr = []
for x in range(n):
    arr.append([])
    for y in range(n):
        arr[x].append([])
        for z in range(n):
            arr[x][y].append(0)
print(arr)

java how to use classes in other package?

Given your example, you need to add the following import in your main.main class:

import second.second;

Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:

package main;  //lowercase package names
public class Main //titlecase class names
{
    //Main class content
}

Getting multiple keys of specified value of a generic Dictionary?

Dictionary class is not optimized for this case, but if you really wanted to do it (in C# 2.0), you can do:

public List<TKey> GetKeysFromValue<TKey, TVal>(Dictionary<TKey, TVal> dict, TVal val)
{
   List<TKey> ks = new List<TKey>();
   foreach(TKey k in dict.Keys)
   {
      if (dict[k] == val) { ks.Add(k); }
   }
   return ks;
}

I prefer the LINQ solution for elegance, but this is the 2.0 way.

Using Address Instead Of Longitude And Latitude With Google Maps API

You can parse the geolocation through the addresses. Create an Array with jquery like this:

//follow this structure
var addressesArray = [
  'Address Str.No, Postal Area/city'
]

//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
  $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
    var p = data.results[0].geometry.location
    var latlng = new google.maps.LatLng(p.lat, p.lng);
    //it will place marker based on the addresses, which they will be translated as geolocations.
    var aMarker= new google.maps.Marker({
      position: latlng,
      map: map
    });
  });
}

Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.

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

clear:both makes the element drop below any floated elements that precede it in the document.

You can also use clear:left or clear:right to make it drop below only those elements that have been floated left or right.

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
+------------+
+---------------------+
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |
+---------------------+

Parameter "stratify" from method "train_test_split" (scikit Learn)

For my future self who comes here via Google:

train_test_split is now in model_selection, hence:

from sklearn.model_selection import train_test_split

# given:
# features: xs
# ground truth: ys

x_train, x_test, y_train, y_test = train_test_split(xs, ys,
                                                    test_size=0.33,
                                                    random_state=0,
                                                    stratify=ys)

is the way to use it. Setting the random_state is desirable for reproducibility.

Sticky and NON-Sticky sessions

I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477

Or you can read it there ==>

When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.

  • If you're using session replication without sticky session : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send some of these requests to the first tomcat instance, and send some other of these requests to the secondth instance, and other to the third.
  • If you're using sticky session without replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, BUT as you don't use session replication, the instance tomcat which receives the remaining requests doesn't have a copy of the user session then for this tomcat the user begin a session : the user loose his session and is disconnected from the web app although the web app is still running.
  • If you're using sticky session WITH session replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, as you use session replication, the instance tomcat which receives the remaining requests has a copy of the user session then the user keeps on his session : the user continue to browse your web app without being disconnected, the shutdown of the tomcat instance doesn't impact the user navigation.

Capitalize words in string

Use This:

_x000D_
_x000D_
String.prototype.toTitleCase = function() {_x000D_
  return this.charAt(0).toUpperCase() + this.slice(1);_x000D_
}_x000D_
_x000D_
let str = 'text';_x000D_
document.querySelector('#demo').innerText = str.toTitleCase();
_x000D_
<div class = "app">_x000D_
  <p id = "demo"></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

It looks like you are passing an NSString parameter where you should be passing an NSData parameter:

NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&jsonError];

How could others, on a local network, access my NodeJS app while it's running on my machine?

const express = require('express');

var app = express();    
app.listen(Port Number, "Your IP Address");
// e.g.
app.listen(3000, "192.183.190.3");

You can get your IP Address by typing ipconfig in cmd if your Windows user else you can use ifconfig.

Difference between Subquery and Correlated Subquery

A subquery is a select statement that is embedded in a clause of another select statement.

EX:

select ename, sal 
from emp  where sal > (select sal 
                       from emp where ename ='FORD');

A Correlated subquery is a subquery that is evaluated once for each row processed by the outer query or main query. Execute the Inner query based on the value fetched by the Outer query all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query.

Ex:

select empno,sal,deptid 
from emp e 
where sal=(select avg(sal) 
           from emp where deptid=e.deptid);

DIFFERENCE

The inner query executes first and finds a value, the outer query executes once using the value from the inner query (subquery)

Fetch by the outer query, execute the inner query using the value of the outer query, use the values resulting from the inner query to qualify or disqualify the outer query (correlated)

For more information : http://www.oraclegeneration.com/2014/01/sql-interview-questions.html

How to automatically insert a blank row after a group of data

Select your array, including column labels, DATA > Outline -Subtotal, At each change in: column1, Use function: Count, Add subtotal to: column3, check Replace current subtotals and Summary below data, OK.

Filter and select for Column1, Text Filters, Contains..., Count, OK. Select all visible apart from the labels and delete contents. Remove filter and, if desired, ungroup rows.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Understanding PIVOT function in T-SQL

A pivot is used to convert one of the columns in your data set from rows into columns (this is typically referred to as the spreading column). In the example you have given, this means converting the PhaseID rows into a set of columns, where there is one column for each distinct value that PhaseID can contain - 1, 5 and 6 in this case.

These pivoted values are grouped via the ElementID column in the example that you have given.

Typically you also then need to provide some form of aggregation that gives you the values referenced by the intersection of the spreading value (PhaseID) and the grouping value (ElementID). Although in the example given the aggregation that will be used is unclear, but involves the Effort column.

Once this pivoting is done, the grouping and spreading columns are used to find an aggregation value. Or in your case, ElementID and PhaseIDX lookup Effort.

Using the grouping, spreading, aggregation terminology you will typically see example syntax for a pivot as:

WITH PivotData AS
(
    SELECT <grouping column>
        , <spreading column>
        , <aggregation column>
    FROM <source table>
)
SELECT <grouping column>, <distinct spreading values>
FROM PivotData
    PIVOT (<aggregation function>(<aggregation column>)
        FOR <spreading column> IN <distinct spreading values>));

This gives a graphical explanation of how the grouping, spreading and aggregation columns convert from the source to pivoted tables if that helps further.

Can not change UILabel text color

It is possible, they are not connected in InterfaceBuilder.

Text colour(colorWithRed:(188/255) green:(149/255) blue:(88/255)) is correct, may be mistake in connections,

backgroundcolor is used for the background colour of label and textcolor is used for property textcolor.

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

For those also having issues with heroku command line tools after upgrading, I also had to do the following in my terminal:

xcode-select --install 
brew install heroku/brew/heroku
brew link --overwrite heroku

It seems the upgrade to High Sierra messed with my symlinks in addition to forcing me to reinstall xcode tools. I kept getting 'not a directory' errors:

? stat /Users/mattymc/.local/share/heroku/client/bin/heroku: not a directory  
? fork/exec /Users/mattmcinnis/.local/share/heroku/client/bin/heroku: not a directory 

Hope that saves someone an hour :)

jQuery: checking if the value of a field is null (empty)

Assuming

var val = $('#person_data[document_type]').value();

you have these cases:

val === 'NULL';  // actual value is a string with content "NULL"
val === '';      // actual value is an empty string
val === null;    // actual value is null (absence of any value)

So, use what you need.

How to change visibility of layout programmatically

You can change layout visibility just in the same way as for regular view. Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.

How can I tell when a MySQL table was last updated?

I'm surprised no one has suggested tracking last update time per row:

mysql> CREATE TABLE foo (
  id INT PRIMARY KEY
  x INT,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP 
                     ON UPDATE CURRENT_TIMESTAMP,
  KEY (updated_at)
);

mysql> INSERT INTO foo VALUES (1, NOW() - INTERVAL 3 DAY), (2, NOW());

mysql> SELECT * FROM foo;
+----+------+---------------------+
| id | x    | updated_at          |
+----+------+---------------------+
|  1 | NULL | 2013-08-18 03:26:28 |
|  2 | NULL | 2013-08-21 03:26:28 |
+----+------+---------------------+

mysql> UPDATE foo SET x = 1234 WHERE id = 1;

This updates the timestamp even though we didn't mention it in the UPDATE.

mysql> SELECT * FROM foo;
+----+------+---------------------+
| id | x    | updated_at          |
+----+------+---------------------+
|  1 | 1235 | 2013-08-21 03:30:20 | <-- this row has been updated
|  2 | NULL | 2013-08-21 03:26:28 |
+----+------+---------------------+

Now you can query for the MAX():

mysql> SELECT MAX(updated_at) FROM foo;
+---------------------+
| MAX(updated_at)     |
+---------------------+
| 2013-08-21 03:30:20 |
+---------------------+

Admittedly, this requires more storage (4 bytes per row for TIMESTAMP).
But this works for InnoDB tables before 5.7.15 version of MySQL, which INFORMATION_SCHEMA.TABLES.UPDATE_TIME doesn't.

Node.js: what is ENOSPC error and how to solve?

If you're using VS Code then it'll should unable to watch in large workspace error.

"Visual Studio Code is unable to watch for file changes in this large workspace" (error ENOSPC)

It indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. The current limit can be viewed by running:

cat /proc/sys/fs/inotify/max_user_watches

The limit can be increased to its maximum by editing /etc/sysctl.conf and adding this line to the end of the file:

fs.inotify.max_user_watches=524288

The new value can then be loaded in by running sudo sysctl -p.

Note: 524288 is the max value to watch the files. Though you can watch any no of files but is also recommended to watch upto that limit only.

Granting Rights on Stored Procedure to another user of Oracle

SQL> grant create any procedure to testdb;

This is a command when we want to give create privilege to "testdb" user.

How to use target in location.href

You could try this:

        <script type="text/javascript">
         function newWindow(url){
                window.open(url);
            }
        </script>

And call the function

How to extract a string using JavaScript Regex?

(.*) instead of (.)* would be a start. The latter will only capture the last character on the line.

Also, no need to escape the :.

C: socket connection timeout

On Linux you can also use:

struct timeval timeout;
timeout.tv_sec  = 7;  // after 7 seconds connect() will timeout
timeout.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
connect(...)

Don't forget to clear SO_SNDTIMEO after connect() if you don't need it.

SQLiteDatabase.query method

if your SQL query is like this

SELECT col-1, col-2 FROM tableName WHERE col-1=apple,col-2=mango
GROUPBY col-3 HAVING Count(col-4) > 5  ORDERBY col-2 DESC LIMIT 15;

Then for query() method, we can do as:-

String table = "tableName";
String[] columns = {"col-1", "col-2"};
String selection = "col-1 =? AND col-2=?";       
String[] selectionArgs = {"apple","mango"};
String groupBy =col-3;
String having =" COUNT(col-4) > 5";
String orderBy = "col-2 DESC";
String limit = "15";

query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

How to use in jQuery :not and hasClass() to get a specific element without a class

You can also use jQuery - is(selector) Method:

var lastOpenSite = $(this).siblings().is(':not(.closedTab)');

Insert Picture into SQL Server 2005 Image Field using only SQL

CREATE TABLE Employees
(
    Id int,
    Name varchar(50) not null,
    Photo varbinary(max) not null
)


INSERT INTO Employees (Id, Name, Photo) 
SELECT 10, 'John', BulkColumn 
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

For..In loops in JavaScript - key value pairs

var obj = {...};
for (var key in obj) {
    var value = obj[key];

}

The php syntax is just sugar.

Case insensitive access for generic dictionary

There is much simpler way:

using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

Print new output on same line

print("single",end=" ")
print("line")

this will give output

single line

for the question asked use

i = 0 
while i <10:
     i += 1 
     print (i,end="")

Remove quotes from String in Python

You can use eval() for this purpose

>>> url = "'http address'"
>>> eval(url)
'http address'

while eval() poses risk , i think in this context it is safe.

CodeIgniter 500 Internal Server Error

This works fine for me

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule >

Javascript use variable as object name

I think Shaz's answer for local variables is hard to understand, though it works for non-recursive functions. Here's another way that I think it's clearer (but it's still his idea, exact same behavior). It's also not accessing the local variables dynamically, just the property of the local variable.

Essentially, it's using a global variable (attached to the function object)

// Here's  a version of it that is more straight forward.
function doIt() {
    doIt.objname = {};
    var someObject = "objname";
    doIt[someObject].value = "value";    
    console.log(doIt.objname);
})();

Which is essentially the same thing as creating a global to store the variable, so you can access it as a property. Creating a global to do this is such a hack.

Here's a cleaner hack that doesn't create global variables, it uses a local variable instead.

function doIt() {
  var scope = {
     MyProp: "Hello"
  };
  var name = "MyProp";
  console.log(scope[name]);
}

See Javascript: interpret string as object reference?

How to log Apache CXF Soap Request and Soap Response using Log4j?

In your spring context configuring below would log the request and response soap messsage.

<bean id="loggingFeature" class="org.apache.cxf.feature.LoggingFeature">
    <property name="prettyLogging" value="true" />
</bean>

<cxf:bus>
    <cxf:features>
        <ref bean="loggingFeature" />
    </cxf:features>
</cxf:bus>

Find CRLF in Notepad++

It appears that this is a FAQ, and the resolution offered is:

Simple search (Ctrl+H) without regexp

You can turn on View/Show End of Line or view/Show All, and select the now visible newline characters. Then when you start the command some characters matching the newline character will be pasted into the search field. Matches will be replaced by the replace string, unlike in regex mode.

Note 1: If you select them with the mouse, start just before them and drag to the start of the next line. Dragging to the end of the line won't work.

Note 2: You can't copy and paste them into the field yourself.

Advanced search (Ctrl+R) without regexp

Ctrl+M will insert something that matches newlines. They will be replaced by the replace string.

Bash tool to get nth line from a file

I've put some of the above answers into a short bash script that you can put into a file called get.sh and link to /usr/local/bin/get (or whatever other name you prefer).

#!/bin/bash
if [ "${1}" == "" ]; then
    echo "error: blank line number";
    exit 1
fi
re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
    echo "error: line number arg not a number";
    exit 1
fi
if [ "${2}" == "" ]; then
    echo "error: blank file name";
    exit 1
fi
sed "${1}q;d" $2;
exit 0

Ensure it's executable with

$ chmod +x get

Link it to make it available on the PATH with

$ ln -s get.sh /usr/local/bin/get

Enjoy responsibly!

P