Programs & Examples On #Custom event

How can I set the opacity or transparency of a Panel in WinForms?

I just wanted to add to the William Smash solution as I couldn't get to his blog so answers which may have been in there to my simple questions could not be found.

Took me a while to realise, but maybe I was just having a moment...

If you haven't had to do so already you'll need to add a reference to System.Windows.Forms in the project properties.

Also you'll need to add

Imports System.Windows.Forms 

to the file where you're adding the override class.

For OnPaintBackground you'll need to add a reference for System.Drawing then

Imports System.Drawing.Printing.PrintEventArgs

How do you push a tag to a remote repository using Git?

How can I push my tag to the remote repository so that all client computers can see it?

Run this to push mytag to your git origin (eg: GitHub or GitLab)

git push origin refs/tags/mytag

It's better to use the full "refspec" as shown above (literally refs/tags/mytag) just in-case mytag is actually v1.0.0 and is ambiguous (eg: because there's a branch also named v1.0.0).

Exists Angularjs code/naming conventions?

Update : STYLE GUIDE is now on Angular docs.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

If you are looking for an opinionated style guide for syntax, conventions, and structuring AngularJS applications, then step right in. The styles contained here are based on my experience with AngularJS, presentations, training courses and working in teams.

The purpose of this style guide is to provide guidance on building AngularJS applications by showing the conventions I use and, more importantly, why I choose them.

- John Papa

Here is the Awesome Link (Latest and Up-to-date) : AngularJS Style Guide

Make new column in Panda dataframe by adding values from other columns

The simplest way would be to use DeepSpace answer. However, if you really want to use an anonymous function you can use apply:

df['C'] = df.apply(lambda row: row['A'] + row['B'], axis=1)

How do I POST urlencoded form data with $http without jQuery?

Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support application/x-www-form-urlencoded, then throw it away ... hopefully AngularJS does !

$http({
     method: 'POST',
     url: 'api_endpoint',
     headers: {'Content-Type': 'application/x-www-form-urlencoded'},
     data: 'username='+$scope.username+'&password='+$scope.password
 }).then(function(response) {
    // on success
 }, function(response) {
    // on error
 });

Works like a charm with AngularJS 1.5

People, let give u some advice:

  • use promises .then(success, error) when dealing with $http, forget about .sucess and .error callbacks (as they are being deprecated)

  • From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."

If your data model is more complex that just a username and a password, you can still do that (as suggested above)

$http({
     method: 'POST',
     url: 'api_endpoint',
     headers: {'Content-Type': 'application/x-www-form-urlencoded'},
     data: json_formatted_data,
     transformRequest: function(data, headers) {
          return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
     }
}).then(function(response) {
  // on succes
}, function(response) {
  // on error
});

Document for the encodeURIComponent can be found here

Get an image extension from an uploaded file in Laravel

Do something like this:

if($request->hasFile('video')){

    $video=$request->file('video');
    $filename=str_random(20).".".$video->extension(); 
    $path = Storage::putFileAs(
            '/', $video, $filename
     );
    $data['video']=$filename;
 }

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

It's little too late but this really works for me.

  1. react-native run-android.
  2. react-native start.

First command will build apk for android and deploy it on your device if its connected. When you open the App it will show red screen with error. Then run second command which will run packager and build app bundle for you.

Java - Convert int to Byte Array of 4 Bytes?

You can convert yourInt to bytes by using a ByteBuffer like this:

return ByteBuffer.allocate(4).putInt(yourInt).array();

Beware that you might have to think about the byte order when doing so.

Including a css file in a blade template?

include the css file into your blade template in laravel

  1. move css file into public->css folder in your laravel project.
  2. use <link rel="stylesheet" href="{{ asset('css/filename') }}">

so css is applied in a blade.php file.

How to get the current branch name in Git?

For my own reference (but it might be useful to others) I made an overview of most (basic command line) techniques mentioned in this thread, each applied to several use cases: HEAD is (pointing at):

  • local branch (master)
  • remote tracking branch, in sync with local branch (origin/master at same commit as master)
  • remote tracking branch, not in sync with a local branch (origin/feature-foo)
  • tag (v1.2.3)
  • submodule (run inside the submodule directory)
  • general detached head (none of the above)

Results:

  • git branch | sed -n '/\* /s///p'
    • local branch: master
    • remote tracking branch (in sync): (detached from origin/master)
    • remote tracking branch (not in sync): (detached from origin/feature-foo)
    • tag: (detached from v1.2.3)
    • submodule: (HEAD detached at 285f294)
    • general detached head: (detached from 285f294)
  • git status | head -1
    • local branch: # On branch master
    • remote tracking branch (in sync): # HEAD detached at origin/master
    • remote tracking branch (not in sync): # HEAD detached at origin/feature-foo
    • tag: # HEAD detached at v1.2.3
    • submodule: # HEAD detached at 285f294
    • general detached head: # HEAD detached at 285f294
  • git describe --all
    • local branch: heads/master
    • remote tracking branch (in sync): heads/master (note: not remotes/origin/master)
    • remote tracking branch (not in sync): remotes/origin/feature-foo
    • tag: v1.2.3
    • submodule: remotes/origin/HEAD
    • general detached head: v1.0.6-5-g2393761
  • cat .git/HEAD:
    • local branch: ref: refs/heads/master
    • submodule: cat: .git/HEAD: Not a directory
    • all other use cases: SHA of the corresponding commit
  • git rev-parse --abbrev-ref HEAD
    • local branch: master
    • all the other use cases: HEAD
  • git symbolic-ref --short HEAD
    • local branch: master
    • all the other use cases: fatal: ref HEAD is not a symbolic ref

(FYI this was done with git version 1.8.3.1)

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

newline in <td title="">

This should be OK, but is Internet Explorer specific:

<td title="lineone
linetwo 
etc...">

As others have mentioned, the only other way is to use an HTML + JavaScript based tooltip if you're only interested in the tooltip. If this is for accessibility then you will probably need to stick to just single lines for consistency.

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

That would be the modulo operator, which produces the remainder of the division of two numbers.

How do I get a substring of a string in Python?

Well, I got a situation where I needed to translate a PHP script to Python, and it had many usages of substr(string, beginning, LENGTH).
If I chose Python's string[beginning:end] I'd have to calculate a lot of end indexes, so the easier way was to use string[beginning:][:length], it saved me a lot of trouble.

VBScript - How to make program wait until process has finished?

This may not specifically answer your long 3 part question but this thread is old and I found this while searching today. Here is one shorter way to: "Wait until a process has finished." If you know the name of the process such as "EXCEL.EXE"

strProcess = "EXCEL.EXE"    
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Do While colProcesses.Count > 0
    Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
    Wscript.Sleep(1000) 'Sleep 1 second
   'msgbox colProcesses.count 'optional to show the loop works
Loop

Credit to: http://crimsonshift.com/scripting-check-if-process-or-program-is-running-and-start-it/

jQuery checkbox onChange

There is a typo error :

$('#activelist :checkbox')...

Should be :

$('#inactivelist:checkbox')...

CSS scale down image to fit in containing div, without specifing original size

Several of these things did not work for me... however, this did. Might help someone else in the future. Here is the CSS:

    .img-area {
     display: block;
     padding: 0px 0 0 0px;
     text-indent: 0;
     width: 100%;
     background-size: 100% 95%;
     background-repeat: no-repeat;
     background-image: url("https://yourimage.png");

    }

How to make <a href=""> link look like a button?

A simple as that :

<a href="#" class="btn btn-success" role="button">link</a>

Just add "class="btn btn-success" & role=button

How do I sort arrays using vbscript?

Here is a QuickSort that I wrote for the arrays returned from the GetRows method of ADODB.Recordset.

'Author:        Eric Weilnau
'Date Written:  7/16/2003
'Description:   QuickSortDataArray sorts a data array using the QuickSort algorithm.
'               Its arguments are the data array to be sorted, the low and high
'               bound of the data array, the integer index of the column by which the
'               data array should be sorted, and the string "asc" or "desc" for the
'               sort order.
'
Sub QuickSortDataArray(dataArray, loBound, hiBound, sortField, sortOrder)
    Dim pivot(), loSwap, hiSwap, count
    ReDim pivot(UBound(dataArray))

    If hiBound - loBound = 1 Then
        If (sortOrder = "asc" and dataArray(sortField,loBound) > dataArray(sortField,hiBound)) or (sortOrder = "desc" and dataArray(sortField,loBound) < dataArray(sortField,hiBound)) Then
            Call SwapDataRows(dataArray, hiBound, loBound)
        End If
    End If

    For count = 0 to UBound(dataArray)
        pivot(count) = dataArray(count,int((loBound + hiBound) / 2))
        dataArray(count,int((loBound + hiBound) / 2)) = dataArray(count,loBound)
        dataArray(count,loBound) = pivot(count)
    Next

    loSwap = loBound + 1
    hiSwap = hiBound

    Do
        Do While (sortOrder = "asc" and dataArray(sortField,loSwap) <= pivot(sortField)) or sortOrder = "desc" and (dataArray(sortField,loSwap) >= pivot(sortField))
            loSwap = loSwap + 1

            If loSwap > hiSwap Then
                Exit Do
            End If
        Loop

        Do While (sortOrder = "asc" and dataArray(sortField,hiSwap) > pivot(sortField)) or (sortOrder = "desc" and dataArray(sortField,hiSwap) < pivot(sortField))
            hiSwap = hiSwap - 1
        Loop

        If loSwap < hiSwap Then
            Call SwapDataRows(dataArray,loSwap,hiSwap)
        End If
    Loop While loSwap < hiSwap

    For count = 0 to Ubound(dataArray)
        dataArray(count,loBound) = dataArray(count,hiSwap)
        dataArray(count,hiSwap) = pivot(count)
    Next

    If loBound < (hiSwap - 1) Then
        Call QuickSortDataArray(dataArray, loBound, hiSwap-1, sortField, sortOrder)
    End If

    If (hiSwap + 1) < hiBound Then
        Call QuickSortDataArray(dataArray, hiSwap+1, hiBound, sortField, sortOrder)
    End If
End Sub

React Native android build failed. SDK location not found

Make sure you have the proper emulator and Android version installed. That solved the problem for me.

How to run Conda?

Mostly it is because when we install Anaconda in the end it adds the anaconda path to PATH variable in .bashrc file. So we just need to restart the terminal or just do

source ~/.bashrc

if still it don't work then follow this commands.

cat >> ~/.bashrc

paste the below command for anaconda3

export PATH=~/anaconda3/bin:$PATH

hit Enter then ctrl+d

source ~/.bashrc

Show current assembly instruction in GDB

Setting the following option:

set  disassemble-next-line on
show disassemble-next-line

Will give you results that look like this:

(gdb) stepi
0x000002ce in ResetISR () at startup_gcc.c:245
245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
=> 0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
   0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0
(gdb) stepi
0x000002d0  245 {
   0x000002cc <ResetISR+0>: 80 b5   push    {r7, lr}
   0x000002ce <ResetISR+2>: 82 b0   sub sp, #8
=> 0x000002d0 <ResetISR+4>: 00 af   add r7, sp, #0

Allow user to select camera or gallery for image

I found this. Using:

galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

for one of the intents shows the user the option of selecting 'documents' in Android 4, which I found very confusing. Using this instead shows the 'gallery' option:

Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

WPF: Grid with column/row margin/padding?

Sometimes the simple method is the best. Just pad your strings with spaces. If it is only a few textboxes etc this is by far the simplest method.

You can also simply insert blank columns/rows with a fixed size. Extremely simple and you can easily change it.

org.json.simple cannot be resolved

Try importing this in build.gradle dependencies

compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'

Failed to instantiate module error in Angular js

I got this error due to not pointing the script to the correct path. So make absolutely sure that you are pointing to the correct path in you html file.

vertical-align: middle with Bootstrap 2

If I remember correctly from my own use of bootstrap, the .spanN classes are floated, which automatically makes them behave as display: block. To make display: table-cell work, you need to remove the float.

COPY with docker but with exclusion

Create file .dockerignore in your docker build context directory (so in this case, most likely a directory that is a parent to node_modules) with one line in it:

**/node_modules

although you probably just want:

node_modules

Info about dockerignore: https://docs.docker.com/engine/reference/builder/#dockerignore-file

sql query to return differences between two tables

Presenting the Cadillac of Diffs as an SP. See within for the basic template that was based on answer by @erikkallen. It supports

  • Duplicate row sensing (most other answers here do not)
  • Sort results by argument
  • Limit to specific columns
  • Ignore columns (e.g. ModifiedUtc)
  • Cross database tables names
  • Temp tables (use as workaround to diff views)

Usage:

exec Common.usp_DiffTableRows '#t1', '#t2';

exec Common.usp_DiffTableRows 
    @pTable0          = 'ydb.ysh.table1',
    @pTable1          = 'xdb.xsh.table2',
    @pOrderByCsvOpt   = null,  -- Order the results
    @pOnlyCsvOpt      = null,  -- Only compare these columns
    @pIgnoreCsvOpt    = null;  -- Ignore these columns (ignored if @pOnlyCsvOpt is specified)

Code:

alter proc [Common].[usp_DiffTableRows]    
    @pTable0          varchar(300),
    @pTable1          varchar(300),
    @pOrderByCsvOpt   nvarchar(1000) = null,  -- Order the Results
    @pOnlyCsvOpt      nvarchar(4000) = null,  -- Only compare these columns
    @pIgnoreCsvOpt    nvarchar(4000) = null,  -- Ignore these columns (ignored if @pOnlyCsvOpt is specified)
    @pDebug           bit = 0
as
/*---------------------------------------------------------------------------------------------------------------------
    Purpose:  Compare rows between two tables.

      Usage:  exec Common.usp_DiffTableRows '#a', '#b';

    Modified    By          Description
    ----------  ----------  -------------------------------------------------------------------------------------------
    2015.10.06  crokusek    Initial Version
    2019.03.13  crokusek    Added @pOrderByCsvOpt
    2019.06.26  crokusek    Support for @pIgnoreCsvOpt, @pOnlyCsvOpt.    
    2019.09.04  crokusek    Minor debugging improvement
    2020.03.12  crokusek    Detect duplicate rows in either source table
  ---------------------------------------------------------------------------------------------------------------------*/
begin try

    if (substring(@pTable0, 1, 1) = '#')
        set @pTable0 = 'tempdb..' + @pTable0; -- object_id test below needs full names for temp tables

    if (substring(@pTable1, 1, 1) = '#')
        set @pTable1 = 'tempdb..' + @pTable1; -- object_id test below needs full names for temp tables

    if (object_id(@pTable0) is null)
        raiserror('Table name is not recognized: ''%s''', 16, 1, @pTable0);

    if (object_id(@pTable1) is null)
        raiserror('Table name is not recognized: ''%s''', 16, 1, @pTable1);

    create table #ColumnGathering
    (
        Name nvarchar(300) not null,
        Sequence int not null,
        TableArg tinyint not null
    );

    declare
        @usp          varchar(100) = object_name(@@procid),    
        @sql          nvarchar(4000),
        @sqlTemplate  nvarchar(4000) = 
        '  
            use $database$;

            insert into #ColumnGathering
            select Name, column_id as Sequence, $TableArg$ as TableArg
              from sys.columns c
             where object_id = object_id(''$table$'', ''U'')
        ';          

    set @sql = replace(replace(replace(@sqlTemplate,
        '$TableArg$', 0),
        '$database$', (select DatabaseName from Common.ufn_SplitDbIdentifier(@pTable0))),
        '$table$', @pTable0);

    if (@pDebug = 1)
        print 'Sql #CG 0: ' + @sql;

    exec sp_executesql @sql;

    set @sql = replace(replace(replace(@sqlTemplate,
        '$TableArg$', 1),
        '$database$', (select DatabaseName from Common.ufn_SplitDbIdentifier(@pTable1))),
        '$table$', @pTable1);

    if (@pDebug = 1)
        print 'Sql #CG 1: ' + @sql;

    exec sp_executesql @sql;

    if (@pDebug = 1)
        select * from #ColumnGathering;

    select Name, 
           min(Sequence) as Sequence, 
           convert(bit, iif(min(TableArg) = 0, 1, 0)) as InTable0,
           convert(bit, iif(max(TableArg) = 1, 1, 0)) as InTable1
      into #Columns
      from #ColumnGathering
     group by Name
    having (     @pOnlyCsvOpt is not null 
             and Name in (select Value from Common.ufn_UsvToNVarcharKeyTable(@pOnlyCsvOpt, default)))
        or 
           (     @pOnlyCsvOpt is null
             and @pIgnoreCsvOpt is not null 
             and Name not in (select Value from Common.ufn_UsvToNVarcharKeyTable(@pIgnoreCsvOpt, default)))
        or 
           (     @pOnlyCsvOpt is null
             and @pIgnoreCsvOpt is null)

    if (exists (select 1 from #Columns where InTable0 = 0 or InTable1 = 0))
    begin
        select 1; -- without this the debugging info doesn't stream sometimes
        select * from #Columns order by Sequence;        
        waitfor delay '00:00:02';  -- give results chance to stream before raising exception
        raiserror('Columns are not equal between tables, consider using args @pIgnoreCsvOpt, @pOnlyCsvOpt.  See Result Sets for details.', 16, 1);    
    end

    if (@pDebug = 1)
        select * from #Columns order by Sequence;

    declare 
        @columns nvarchar(4000) = --iif(@pOnlyCsvOpt is null and @pIgnoreCsvOpt is null,
           -- '*',     
            (
              select substring((select ',' + ac.name
                from #Columns ac
               order by Sequence
                 for xml path('')),2,200000) as csv
            );

    if (@pDebug = 1)
    begin
        print 'Columns: ' + @columns;
        waitfor delay '00:00:02';  -- give results chance to stream before possibly raising exception
    end

    -- Based on https://stackoverflow.com/a/2077929/538763
    --     - Added sensing for duplicate rows
    --     - Added reporting of source table location
    --
    set @sqlTemplate = '
            with 
               a as (select ~, Row_Number() over (partition by ~ order by (select null)) -1 as Duplicates from $a$), 
               b as (select ~, Row_Number() over (partition by ~ order by (select null)) -1 as Duplicates from $b$)
            select 0 as SourceTable, ~
              from 
                 (
                   select * from a
                   except
                   select * from b
                 )  anb
              union all
             select 1 as SourceTable, ~
               from 
                 (
                   select * from b
                   except
                   select * from a
                 )  bna
             order by $orderBy$
        ';    

     set @sql = replace(replace(replace(replace(@sqlTemplate, 
            '$a$', @pTable0), 
            '$b$', @pTable1),
            '~', @columns),
            '$orderBy$', coalesce(@pOrderByCsvOpt, @columns + ', SourceTable')
        );

     if (@pDebug = 1)
        print 'Sql: ' + @sql;

     exec sp_executesql @sql;

end try
begin catch
    declare        
        @CatchingUsp  varchar(100) = object_name(@@procid);    

    if (xact_state() = -1)
        rollback;    

    -- Disabled for S.O. post

    --exec Common.usp_Log
        --@pMethod = @CatchingUsp;

    --exec Common.usp_RethrowError        
        --@pCatchingMethod = @CatchingUsp;

    throw;
end catch
go

create function Common.Trim
(
    @pOriginalString nvarchar(max), 
    @pCharsToTrim nvarchar(50) = null -- specify null or 'default' for whitespae 
)  
returns table
with schemabinding
as 
/*--------------------------------------------------------------------------------------------------
    Purpose:   Trim the specified characters from a string.

    Modified    By              Description
    ----------  --------------  --------------------------------------------------------------------
    2012.09.25  S.Rutszy/crok   Modified from https://dba.stackexchange.com/a/133044/9415    
  --------------------------------------------------------------------------------------------------*/ 
return
with cte AS
(
  select patindex(N'%[^' + EffCharsToTrim + N']%', @pOriginalString) AS [FirstChar],
         patindex(N'%[^' + EffCharsToTrim + N']%', reverse(@pOriginalString)) AS [LastChar],
         len(@pOriginalString + N'~') - 1 AS [ActualLength]
   from
   (
         select EffCharsToTrim = coalesce(@pCharsToTrim, nchar(0x09) + nchar(0x20) + nchar(0x0d) + nchar(0x0a))
   ) c
)
select substring(@pOriginalString, [FirstChar],
                 ((cte.[ActualLength] - [LastChar]) - [FirstChar] + 2)
       ) AS [TrimmedString]
       --
       --cte.[ActualLength],
       --[FirstChar],
       --((cte.[ActualLength] - [LastChar]) + 1) AS [LastChar]              
from cte;
go

create function [Common].[ufn_UsvToNVarcharKeyTable] (
    @pCsvList     nvarchar(MAX),
    @pSeparator   nvarchar(1) = ','       -- can pass keyword 'default' when calling using ()'s
    )    
    --
    -- SQL Server 2012 distinguishes nvarchar keys up to maximum of 450 in length (900 bytes)
    -- 
    returns @tbl table (Value nvarchar(450) not null primary key(Value)) as
/*-------------------------------------------------------------------------------------------------
    Purpose:  Converts a comma separated list of strings into a sql NVarchar table.  From

              http://www.programmingado.net/a-398/SQL-Server-parsing-CSV-into-table.aspx     

              This may be called from RunSelectQuery:

                  GRANT SELECT ON Common.ufn_UsvToNVarcharTable TO MachCloudDynamicSql;

    Modified    By              Description
    ----------  --------------  -------------------------------------------------------------------
    2011.07.13  internet        Initial version
    2011.11.22  crokusek        Support nvarchar strings and a custom separator.
    2017.12.06  crokusek        Trim leading and trailing whitespace from each element.
    2019.01.26  crokusek        Remove newlines
  -------------------------------------------------------------------------------------------------*/     
begin
    declare 
        @pos      int,
        @textpos  int,
        @chunklen smallint,
        @str      nvarchar(4000),
        @tmpstr   nvarchar(4000),
        @leftover nvarchar(4000),
        @csvList nvarchar(max) = iif(@pSeparator not in (char(13), char(10), char(13) + char(10)),
            replace(replace(@pCsvList, char(13), ''), char(10), ''),
            @pCsvList); -- remove newlines

    set @textpos = 1
    set @leftover = ''  
    while @textpos <= len(@csvList)
    begin
        set @chunklen = 4000 - len(@leftover)
        set @tmpstr = ltrim(@leftover + substring(@csvList, @textpos, @chunklen))
        set @textpos = @textpos + @chunklen

        set @pos = charindex(@pSeparator, @tmpstr)
        while @pos > 0
        begin
            set @str = substring(@tmpstr, 1, @pos - 1)
            set @str = (select TrimmedString from Common.Trim(@str, default));
            insert @tbl (value) values(@str);
            set @tmpstr = ltrim(substring(@tmpstr, @pos + 1, len(@tmpstr)))
            set @pos = charindex(@pSeparator, @tmpstr)
        end

        set @leftover = @tmpstr
    end

    -- Handle @leftover

    set @str = (select TrimmedString from Common.Trim(@leftover, default));

    if @str <> ''
       insert @tbl (value) values(@str);

    return
end
GO

create function Common.ufn_SplitDbIdentifier(@pIdentifier nvarchar(300))
returns @table table 
(    
    InstanceName          nvarchar(300) not null,
    DatabaseName          nvarchar(300) not null,
    SchemaName            nvarchar(300),
    BaseName              nvarchar(300) not null,
    FullTempDbBaseName    nvarchar(300),            -- non-null for tempdb (e.g. #Abc____...)
    InstanceWasSpecified  bit not null,
    DatabaseWasSpecified  bit not null,
    SchemaWasSpecified    bit not null,
    IsCurrentInstance     bit not null,
    IsCurrentDatabase     bit not null,
    IsTempDb              bit not null,
    OrgIdentifier         nvarchar(300) not null
) as
/*-----------------------------------------------------------------------------------------------------------
    Purpose:  Split a Sql Server Identifier into its parts, providing appropriate default values and
              handling temp table (tempdb) references.

    Example:  select * from Common.ufn_SplitDbIdentifier('t')
              union all
              select * from Common.ufn_SplitDbIdentifier('s.t')
              union all
              select * from Common.ufn_SplitDbIdentifier('d.s.t')
              union all
              select * from Common.ufn_SplitDbIdentifier('i.d.s.t')
              union all
              select * from Common.ufn_SplitDbIdentifier('#d')
              union all
              select * from Common.ufn_SplitDbIdentifier('tempdb..#d'); 

              -- Empty
              select * from Common.ufn_SplitDbIdentifier('illegal name'); 

    Modified    By              Description
    ----------  --------------  -----------------------------------------------------------------------------
    2013.09.27  crokusek        Initial version.  
  -----------------------------------------------------------------------------------------------------------*/
begin
    declare 
        @name nvarchar(300) = ltrim(rtrim(@pIdentifier));

    -- Return an empty table as a "throw"
    --
    --Removed for SO post
    --if (Common.ufn_IsSpacelessLiteralIdentifier(@name) = 0)
      --  return;

    -- Find dots starting from the right by reversing first.

    declare 
        @revName nvarchar(300) = reverse(@name);

    declare
        @firstDot int = charindex('.', @revName);

    declare
        @secondDot  int = iif(@firstDot = 0,  0, charindex('.', @revName, @firstDot + 1));

    declare
        @thirdDot   int = iif(@secondDot = 0, 0, charindex('.', @revName, @secondDot + 1));

    declare
        @fourthDot  int = iif(@thirdDot = 0, 0, charindex('.', @revName, @thirdDot + 1));

    --select @firstDot, @secondDot, @thirdDot, @fourthDot, len(@name);

    -- Undo the reverse() (first dot is first from the right).
    --
    set @firstDot = iif(@firstDot = 0, 0, len(@name) - @firstDot + 1);
    set @secondDot = iif(@secondDot = 0, 0, len(@name) - @secondDot + 1);
    set @thirdDot = iif(@thirdDot = 0, 0, len(@name) - @thirdDot + 1);
    set @fourthDot = iif(@fourthDot = 0, 0, len(@name) - @fourthDot + 1);

    --select @firstDot, @secondDot, @thirdDot, @fourthDot, len(@name);

    declare
        @baseName   nvarchar(300)  = substring(@name, @firstDot + 1, len(@name) - @firstdot);

    declare
        @schemaName nvarchar(300) = iif(@firstDot - @secondDot - 1 <= 0, 
                                        null,
                                        substring(@name, @secondDot + 1, @firstDot - @secondDot - 1));
    declare
        @dbName     nvarchar(300) = iif(@secondDot - @thirdDot - 1 <= 0, 
                                        null,
                                        substring(@name, @thirdDot + 1, @secondDot - @thirdDot - 1));
    declare
        @instName   nvarchar(300) = iif(@thirdDot - @fourthDot - 1 <= 0, 
                                        null, 
                                        substring(@name, @fourthDot + 1, @thirdDot - @fourthDot - 1));

    with input as (
        select
           coalesce(@instName, '[' + @@servername + ']') as InstanceName,
           coalesce(@dbName,     iif(left(@baseName, 1) = '#', 'tempdb', db_name())) as DatabaseName,
           coalesce(@schemaName, iif(left(@baseName, 1) = '#', 'dbo', schema_name())) as SchemaName,
           @baseName as BaseName,
           iif(left(@baseName, 1) = '#',
               (
                  select [name] from tempdb.sys.objects
                  where object_id = object_id('tempdb..' + @baseName)
               ), 
               null) as FullTempDbBaseName,                
           iif(@instName is null, 0, 1) InstanceWasSpecified,       
           iif(@dbName is null, 0, 1) DatabaseWasSpecified,
           iif(@schemaName is null, 0, 1) SchemaWasSpecified    
     )
     insert into @table           
     select i.InstanceName, i.DatabaseName, i.SchemaName, i.BaseName, i.FullTempDbBaseName,
            i.InstanceWasSpecified, i.DatabaseWasSpecified, i.SchemaWasSpecified,
            iif(i.InstanceName = '[' + @@servername + ']', 1, 0) as IsCurrentInstance,
            iif(i.DatabaseName = db_name(), 1, 0) as IsCurrentDatabase,
            iif(left(@baseName, 1) = '#', 1, 0) as IsTempDb,
            @name as OrgIdentifier
       from input i;

    return;
end
GO

TSQL Default Minimum DateTime

I think this would work...

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT ((0))
)

Edit: This is wrong...The minimum SQL DateTime Value is 1/1/1753. My solution provides a datetime = 1/1/1900 00:00:00. Other answers have the correct minimum date...

Why is PHP session_destroy() not working?

if you destroy the session on 127.0.0.1 it will not affect on localhost and vice versa

Split Div Into 2 Columns Using CSS

I know this post is old, but if any of you still looking for a simpler solution.

#container .left,
#container .right {
    display: inline-block;
}

#container .left {
    width: 20%;
    float: left;
}
#container .right {
    width: 80%;
    float: right;
}

Remove quotes from a character vector in R

Try this: (even [1] will be removed)

> cat(noquote("love"))
love

else just use noquote

> noquote("love")
[1] love

How to check if a Java 8 Stream is empty?

This may be sufficient in many cases

stream.findAny().isPresent()

Remove part of string after "."

You could do:

sub("*\\.[0-9]", "", a)

or

library(stringr)
str_sub(a, start=1, end=-3)

Global Variable from a different file Python

When you write

from file2 import *

it actually copies the names defined in file2 into the namespace of file1. So if you reassign those names in file1, by writing

foo = "bar"

for example, it will only make that change in file1, not file2. Note that if you were to change an attribute of foo, say by doing

foo.blah = "bar"

then that change would be reflected in file2, because you are modifying the existing object referred to by the name foo, not replacing it with a new object.

You can get the effect you want by doing this in file1.py:

import file2
file2.foo = "bar"
test = SomeClass()

(note that you should delete from foo import *) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.

Modifying local variable from inside lambda

Yes, you can modify local variables from inside lambdas (in the way shown by the other answers), but you should not do it. Lambdas have been made for functional style of programming and this means: No side effects. What you want to do is considered bad style. It is also dangerous in case of parallel streams.

You should either find a solution without side effects or use a traditional for loop.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

Cross Browser Flash Detection in Javascript

To create a Flash object standart-compliant (with JavaScript however), I recommend you take a look at

Unobtrusive Flash Objects (UFO)

http://www.bobbyvandersluis.com/ufo/index.html

How to get ER model of database from server with Workbench

On mac, press Command + R or got to Database -> Reverse Engineer and keep selecting your requirements and continue

enter image description here

Relative div height

add this to you CSS:

html, body
{
    height: 100%;
}

working Fiddle

when you say to wrap to be 100%, 100% of what? of its parent (body), so his parent has to have some height.

and the same goes for body, his parent his html. html parent his the viewport.. so, by setting them both to 100%, wrap can also have a percentage height.

also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use

*
{
    padding: 0;
    margin: 0;
}

to disable that.

Look at That Fiddle

Search all the occurrences of a string in the entire project in Android Studio

Android Studio Version 4.0.1 on Mac combination is for me:

Shift + Control + F

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

How to correctly close a feature branch in Mercurial?

It is strange, that no one yet has suggested the most robust way of closing a feature branches... You can just combine merge commit with --close-branch flag (i.e. commit modified files and close the branch simultaneously):

hg up feature-x
hg merge default
hg ci -m "Merge feature-x and close branch" --close-branch
hg branch default -f

So, that is all. No one extra head on revgraph. No extra commit.

Verify object attribute value with mockito

If you're using Java 8, you can use Lambda expressions to match.

import java.util.Optional;
import java.util.function.Predicate;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;

public class LambdaMatcher<T> extends BaseMatcher<T>
{
    private final Predicate<T> matcher;
    private final Optional<String> description;

    public LambdaMatcher(Predicate<T> matcher)
    {
        this(matcher, null);
    }

    public LambdaMatcher(Predicate<T> matcher, String description)
    {
        this.matcher = matcher;
        this.description = Optional.ofNullable(description);
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean matches(Object argument)
    {
        return matcher.test((T) argument);
    }

    @Override
    public void describeTo(Description description)
    {
        this.description.ifPresent(description::appendText);
    }
}

Example call

@Test
public void canFindEmployee()
{
    Employee employee = new Employee("John");
    company.addEmployee(employee);

    verify(mockedDal).registerEmployee(argThat(new LambdaMatcher<>(e -> e.getName()
                                                                         .equals(employee.getName()))));
}

More info: http://source.coveo.com/2014/10/01/java8-mockito/

Position an element relative to its container

You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:

div.parent{
    position: relative;
    left: 0px;  /* stick it wherever it was positioned by default */
    top: 0px;
}

div.child{
    position: absolute;
    left: 10px;
    top: 10px;
}

How to push a single file in a subdirectory to Github (not master)

Let me start by saying that the way git works is you are not pushing/fetching files; well, at least not directly.

You are pushing/fetching refs, that point to commits. Then a commit in git is a reference to a tree of objects (where files are represented as objects, among other objects).

So, when you are pushing a commit, what git does it pushes a set of references like in this picture:

git commits

If you didn't push your master branch yet, the whole history of the branch will get pushed.

So, in your example, when you commit and push your file, the whole master branch will be pushed, if it was not pushed before.

To do what you asked for, you need to create a clean branch with no history, like in this answer.

Facebook page automatic "like" URL (for QR Code)

For a hyperlink just use www.facebook.com/++page ID++/like

Eg: www.facebook.com/MYPAGEISAWESOME/like

To make it work with m.facebook.com here's what you do:

Open the Facebook page you're looking for then change the URL to the mobile URL ( which is www.m.facebook.com/MYPAGEISAWESOME ).

Now you should see a big version of the mobile Facebook page. Copy the target URL of the like button.

Pop that URL into the QR generator to make a "scan to like" barcode. This will open the m.Facebook page in the browser of most mobiles directly from the QR reader. If they are not logged into Facebook then they will be prompted to log in and then click 'like'. If logged in, it will auto like.

Hope this helps!

Also, definitely include something with a "click here/scan here to like us on Facebook"

Using setattr() in python

Setattr: We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value. and with getattr we retrive these values

For example

Employee = type("Employee", (object,), dict())

employee = Employee()

# Set salary to 1000
setattr(employee,"salary", 1000 )

# Get the Salary
value = getattr(employee, "salary")

print(value)

Dynamically change color to lighter or darker by percentage CSS (Javascript)

You could use RGBa ('a' being alpha transparency), but it's not widely supported yet. It will be, though, so you could use it now and add a fallback:

a:link { 
    color: rgb(0,0,255); 
    }
a:link.lighter {
    color: rgb(128,128,255); /* This gets applied only in browsers that don't apply the rgba line */
    }
a:link.lighter { /* This comes after the previous line, so has priority in supporting browsers */
    color: rgba(0,0,255,0.5); /* last value is transparency */
    }

What is the boundary in multipart/form-data?

The exact answer to the question is: yes, you can use an arbitrary value for the boundary parameter, given it does not exceed 70 bytes in length and consists only of 7-bit US-ASCII (printable) characters.

If you are using one of multipart/* content types, you are actually required to specify the boundary parameter in the Content-Type header, otherwise the server (in the case of an HTTP request) will not be able to parse the payload.

You probably also want to set the charset parameter to UTF-8 in your Content-Type header, unless you can be absolutely sure that only US-ASCII charset will be used in the payload data.

A few relevant excerpts from the RFC2046:

  • 4.1.2. Charset Parameter:

    Unlike some other parameter values, the values of the charset parameter are NOT case sensitive. The default character set, which must be assumed in the absence of a charset parameter, is US-ASCII.

  • 5.1. Multipart Media Type

    As stated in the definition of the Content-Transfer-Encoding field [RFC 2045], no encoding other than "7bit", "8bit", or "binary" is permitted for entities of type "multipart". The "multipart" boundary delimiters and header fields are always represented as 7bit US-ASCII in any case (though the header fields may encode non-US-ASCII header text as per RFC 2047) and data within the body parts can be encoded on a part-by-part basis, with Content-Transfer-Encoding fields for each appropriate body part.

    The Content-Type field for multipart entities requires one parameter, "boundary". The boundary delimiter line is then defined as a line consisting entirely of two hyphen characters ("-", decimal value 45) followed by the boundary parameter value from the Content-Type header field, optional linear whitespace, and a terminating CRLF.

    Boundary delimiters must not appear within the encapsulated material, and must be no longer than 70 characters, not counting the two leading hyphens.

    The boundary delimiter line following the last body part is a distinguished delimiter that indicates that no further body parts will follow. Such a delimiter line is identical to the previous delimiter lines, with the addition of two more hyphens after the boundary parameter value.

Here is an example using an arbitrary boundary:

Content-Type: multipart/form-data; charset=utf-8; boundary="another cool boundary"

--another cool boundary
Content-Disposition: form-data; name="foo"

bar
--another cool boundary
Content-Disposition: form-data; name="baz"

quux
--another cool boundary--

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?

var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone', 
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike 
v7.6 release 92', 'Pike v7.8 release 517'];

// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
    // Execute code
}
// If NOT on Apple device
else {
    // Execute code
}

XML Schema minOccurs / maxOccurs default values

Short answer:

As written in xsd:

<xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/>
<xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/>

If you provide an attribute with number, then the number is boundary. Otherwise attribute should appear exactly once.

Is there a MySQL option/feature to track history of changes to records?

MariaDB supports System Versioning since 10.3 which is the standard SQL feature that does exactly what you want: it stores history of table records and provides access to it via SELECT queries. MariaDB is an open-development fork of MySQL. You can find more on its System Versioning via this link:

https://mariadb.com/kb/en/library/system-versioned-tables/

Equal sized table cells to fill the entire width of the containing table

You don't even have to set a specific width for the cells, table-layout: fixed suffices to spread the cells evenly.

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid hotpink;_x000D_
    vertical-align: middle;_x000D_
    word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that for table-layout to work the table styled element must have a width set (100% in my example).

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try:

SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date', 
       convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date', 
FROM
(......)SA
WHERE......

Or:

SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date', 
       format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date', 
FROM
(......)SA
WHERE......

C# : changing listbox row color?

I find solution that instead of using ListBox I used ListView.It allows to change list items BackColor.

private void listView1_Refresh()
{
    for (int i = 0; i < listView1.Items.Count; i++)
    {
        listView1.Items[i].BackColor = Color.Red;
        for (int j = 0; j < existingStudents.Count; j++)
        {
            if (listView1.Items[i].ToString().Contains(existingStudents[j]))
            {
                listView1.Items[i].BackColor = Color.Green;
            }
        }
    }
}

Is there a quick change tabs function in Visual Studio Code?

This also works on MAC OS:

Prev tab: Shift + Cmd + [

Next Tab: Shift + Cmd + ]

How to undo a git pull?

Even though the above solutions do work,This answer is for you in case you want to reverse the clock instead of undoing a git pull.I mean if you want to get your exact repo the way it was X Mins back then run the command

git reset --hard branchName@{"X Minutes ago"}

Note: before you actually go ahead and run this command please only try this command if you are sure about the time you want to go back to and heres about my situation.

I was currently on a branch develop, I was supposed to checkout to a new branch and pull in another branch lets say Branch A but I accidentally ran git pull origin B before checking out.

so to undo this change I tried this command

git reset --hard develop@{"10 Minutes ago"}

if you are on windows cmd and get error: unknown switch `e

try adding quotes like this

git reset --hard 'develop@{"10 Minutes ago"}'

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Could not find module FindOpenCV.cmake ( Error in configuration process)

The error you're seeing is that CMake cannot find a FindOpenCV.cmake file, because cmake doesn't include one out of the box. Therefore you need to find one and put it where cmake can find it:

You can find a good start here. If you're feeling adventurous you can also write your own.

Then add it somewhere in your project and adjust CMAKE_MODULE_PATH so that cmake can find it.

e.g., if you have

CMakeLists.txt
cmake-modules/FindOpenCV.cmake

Then you should do a

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake-modules)

In your CMakeLists.txt file before you do a find_package(OpenCV)

How to check Oracle database for long running queries

Try this, it will give you queries currently running for more than 60 seconds. Note that it prints multiple lines per running query if the SQL has multiple lines. Look at the sid,serial# to see what belongs together.

select s.username,s.sid,s.serial#,s.last_call_et/60 mins_running,q.sql_text from v$session s 
join v$sqltext_with_newlines q
on s.sql_address = q.address
 where status='ACTIVE'
and type <>'BACKGROUND'
and last_call_et> 60
order by sid,serial#,q.piece

Angularjs dynamic ng-pattern validation

You can use site https://regex101.com/ for building your own specific pattern for some country:

For example, Poland:

-pattern = xxxxxxxxx OR xxx-xxx-xxx OR xxx xxx xxx 
-regexp ="^\d{9}|^\d{3}-\d{3}-\d{3}|^\d{3}\s\d{3}\s\d{3}"

Calculate RSA key fingerprint

The fastest way if your keys are in an SSH agent:

$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin

Each key in the agent will be printed as:

4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)

How to retrieve current workspace using Jenkins Pipeline Groovy script?

There is no variable included for that yet, so you have to use shell-out-read-file method:

sh 'pwd > workspace'
workspace = readFile('workspace').trim()

Or (if running on master node):

workspace = pwd()

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

If you are doing local testing or calling the file from something like file:// then you need to disable browser security.

On MAC: open -a Google\ Chrome --args --disable-web-security

How do I prevent an Android device from going to sleep programmatically?

I found another working solution: add the following line to your app under the onCreate event.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

My sample Cordova project looks like this:

package com.apps.demo;
import android.os.Bundle;
import android.view.WindowManager;
import org.apache.cordova.*;

public class ScanManActivity extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.loadUrl("http://stackoverflow.com");
    }
}

After that, my app would not go to sleep while it was open. Thanks for the anwer goes to xSus.

Looping through all the properties of object php

Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)

Java - checking if parseInt throws exception

You can use the try..catch statement in java, to capture an exception that may arise from Integer.parseInt().

Example:

try {
  int i = Integer.parseint(stringToParse);
  //parseInt succeded
} catch(Exception e)
{
   //parseInt failed
}

how do I get eclipse to use a different compiler version for Java?

Eclipse uses it's own internal compiler that can compile to several Java versions.

From Eclipse Help > Java development user guide > Concepts > Java Builder

The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.

For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.

When you configure a project:

[project-name] > Properties > Java Compiler > Compiler compliance level

This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.

Host environment variables, eg JAVA_HOME etc, are not used.

The Oracle/Sun JDK compiler is not used.

git diff file against its last change

This does exist, but it's actually a feature of git log:

git log -p [--follow] [-1] <path>

Note that -p can also be used to show the inline diff from a single commit:

git log -p -1 <commit>

Options used:

  • -p (also -u or --patch) is hidden deeeeeeeep in the git-log man page, and is actually a display option for git-diff. When used with log, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>. (This behavior is described in the paragraph on --full-diff, which causes the full diff of each commit to be shown.)
  • -1 shows just the most recent change to the specified file (-n 1 can be used instead of -1); otherwise, all non-zero diffs of that file are shown.
  • --follow is required to see changes that occurred prior to a rename.

As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log (or similar) to either count the number of intervening revisions or determine the hash of the commit.

To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)

Credit where credit is due:

  • I discovered log -p thanks to this answer.
  • Credit to FranciscoPuga and this answer for showing me the --follow option.
  • Credit to ChrisBetti for mentioning the -n 1 option and atatko for mentioning the -1 variant.
  • Credit to sweaver2112 for getting me to actually read the documentation and figure out what -p "means" semantically.

Genymotion Android emulator - adb access?

Simply do this, with genymotion device running you can open Virtual Box , and see that there is a VM for you device , then go to network Settings of the VM, NAT and do port forwarding of local 5555 to remote 5555 screen attachedVirtual Box Nat Network Port forwarding

jQuery & CSS - Remove/Add display:none

So, let me give you sample code:

<div class="news">
Blah, blah, blah. I'm hidden.
</div>

<a class="trigger">Hide/Show News</a>

The link will be the trigger to show the div when clicked. So your Javascript will be:

$('.trigger').click(function() {
   $('.news').toggle();
});

You're almost always better off letting jQuery handle the styling for hiding and showing elements.

Edit: I see people above are recommending using .show and .hide for this. .toggle allows you to do both with just one effect. So that's cool.

Convert a Pandas DataFrame to a dictionary

Try to use Zip

df = pd.read_csv("file")
d= dict([(i,[a,b,c ]) for i, a,b,c in zip(df.ID, df.A,df.B,df.C)])
print d

Output:

{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

Regular expression replace in C#

Add the following 2 lines

var regex = new Regex(Regex.Escape(","));
sb_trim = regex.Replace(sb_trim, " ", 1);

If sb_trim= John,Smith,100000,M the above code will return "John Smith,100000,M"

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

I made the following filter:

angular.module('app').filter('ifEmpty', function() {
    return function(input, defaultValue) {
        if (angular.isUndefined(input) || input === null || input === '') {
            return defaultValue;
        }

        return input;
    }
});

To be used like this:

<span>{{aPrice | currency | ifEmpty:'N/A'}}</span>
<span>{{aNum | number:3 | ifEmpty:0}}</span>

How to open SharePoint files in Chrome/Firefox

Installing the Chrome extension IE Tab did the job for me.

It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.

You can install IETab for FireFox too.

What are .iml files in Android Studio?

Those files are created and used by Android Studio editor.

You don't need to check in those files to version control.

Git uses .gitignore file, that contains list of files and directories, to know the list of files and directories that don't need to be checked in.

Android studio automatically creates .gitingnore files listing all files and directories which don't need to be checked in to any version control.

Moment JS start and end of given month

Try the following code:

const moment=require('moment');
console.log("startDate=>",moment().startOf('month').format("YYYY-DD-MM"));
console.log("endDate=>",moment().endOf('month').format("YYYY-DD-MM"));

How to jump back to NERDTree from file in tab?

ctrl-ww Could be useful when you have limited tabs open. But could get annoying when you have too many tabs open.

I type in :NERDTree again to get the focus back on NERDTree tab instantly wherever my cursor's focus is. Hope that helps

Calculating Pearson correlation and significance in Python

The Pearson correlation can be calculated with numpy's corrcoef.

import numpy
numpy.corrcoef(list1, list2)[0, 1]

How can I sort a std::map first by value, then by key?

You can use std::set instead of std::map.

You can store both key and value in std::pair and the type of container will look like this:

std::set< std::pair<int, std::string> > items;

std::set will sort it's values both by original keys and values that were stored in std::map.

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

Simulate Keypress With jQuery

You could try this SendKeys jQuery plugin:

http://bililite.com/blog/2011/01/23/improved-sendkeys/

$(element).sendkeys(string) inserts string at the insertion point in an input, textarea or other element with contenteditable=true. If the insertion point is not currently in the element, it remembers where the insertion point was when sendkeys was last called (if the insertion point was never in the element, it appends to the end).

Background color in input and text fields

You want to restrict to input fields that are of type text so use the selector input[type=text] rather than input (which will apply to all input fields (e.g. those of type submit as well)).

How to scanf only integer?

Use fgets and strtol,

A pointer to the first character following the integer representation in s is stored in the object pointed by p, if *p is different to \n then you have a bad input.

#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
    char *p, s[100];
    long n;

    while (fgets(s, sizeof(s), stdin)) {
        n = strtol(s, &p, 10);
        if (p == s || *p != '\n') {
            printf("Please enter an integer: ");
        } else break;
    }
    printf("You entered: %ld\n", n);
    return 0;
}

How can I autoplay a video using the new embed code style for Youtube?

You are using a wrong url for youtube auto play http://www.youtube.com/embed/JW5meKfy3fY&autoplay=1 this url display youtube id as wholeJW5meKfy3fY&autoplay=1 which youtube rejects to play. we have to pass autoplay variable to youtube, therefore you have to use ? instead of & so your url will be http://www.youtube.com/embed/JW5meKfy3fY?autoplay=1 and your final iframe will be like that.

<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>

How to Merge Two Eloquent Collections?

$users = User::all();
$associates = Associate::all();

$userAndAssociate = $users->merge($associates);

The application was unable to start correctly (0xc000007b)

To start, I would suggest to test whether there is a problem between your application and its dependencies using dependency walker

How do I format my oracle queries so the columns don't wrap?

I use a generic query I call "dump" (why? I don't know) that looks like this:

SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |

spool &1..txt

@@&1

spool off
exit

I then call SQL*Plus passing the actual SQL script I want to run as an argument:

sqlplus -S user/password@database @dump.sql my_real_query.sql

The result is written to a file

my_real_query.sql.txt

.

Html.DropDownList - Disabled/Readonly

Or you can try something like this:

Html.DropDownList("Types", Model.Types, new { @readonly = "true" })

No input file specified

The No input file specified is a message you are presented with because of the implementation of PHP on your server, which in this case indicates a CGI implementation (can be verified with phpinfo()).

Now, to properly explain this, you need to have some basic understanding on how your system works with URL's. Based on your .htaccess file, it seems that your CMS expects the URL to passed along as a PATH_INFO variable. CGI and FastCGI implementations do not have PATH_INFO available, so when trying to pass the URI along, PHP fails with that message.

We need to find an alternative.

One option is to try and fix this. Looking into the documentation for core php.ini directives you can see that you can change the workings for your implementation. Although, GoDaddy probably won't allow you to change PHP settings on a shared enviroment.

We need to find an alternative to modifying PHP settings
Looking into system/uri.php on line 40, you will see that the CMS attempts two types of URI detection - the first being PATH_INFO, which we just learned won't work - the other being the REQUEST_URI.

This should basically, be enough - but the parsing of the URI passed, will cause you more trouble, as the URI, which you could pass to REQUEST_URI variable, forces parse_url() to only return the URL path - which basically puts you back to zero.

Now, there's actually only one possibilty left - and that's changing the core of the CMS. The URI detection part is insufficient.

Add QUERY_STRING to the array on line 40 as the first element in system/uri.php and change your .htaccess to look like this:

RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule ^(.*)$ index.php?/$1 [L]

This will pass the URI you request to index.php as QUERY_STRING and have the URI detection to find it.

This, on the other hand, makes it impossible to update the CMS without changing core files till this have been fixed. That sucks...

Need a better option?
Find a better CMS.

How to use background thread in swift?

From Jameson Quave's tutorial

Swift 2

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    //All stuff here
})

Python: converting a list of dictionaries to json

response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
response_json = json.dumps(response_json)
response_json = json.loads(response_json)

Port 80 is being used by SYSTEM (PID 4), what is that?

For me it worked after stopping Web Deployment Agent Service.

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

Run php script as daemon process

you can check pm2 here is, http://pm2.keymetrics.io/

create a ssh file, such as worker.sh put into your php script that you will deal with.

worker.sh

php /path/myscript.php

daemon start

pm2 start worker.sh

Cheers, that is it.

xpath find if node exists

Might be better to use a choice, don't have to type (or possibly mistype) your expressions more than once, and allows you to follow additional different behaviors.

I very often use count(/html/body) = 0, as the specific number of nodes is more interesting than the set. For example... when there is unexpectedly more than 1 node that matches your expression.

<xsl:choose>
    <xsl:when test="/html/body">
         <!-- Found the node(s) -->
    </xsl:when>
    <!-- more xsl:when here, if needed -->
    <xsl:otherwise>
         <!-- No node exists -->
    </xsl:otherwise>
</xsl:choose>

How should strace be used?

I liked some of the answers where it reads strace checks how you interacts with your operating system.

This is exactly what we can see. The system calls. If you compare strace and ltrace the difference is more obvious.

$>strace -c cd
Desktop  Documents  Downloads  examples.desktop  Music  Pictures  Public  Templates  Videos
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
  0.00    0.000000           0         7           read
  0.00    0.000000           0         1           write
  0.00    0.000000           0        11           close
  0.00    0.000000           0        10           fstat
  0.00    0.000000           0        17           mmap
  0.00    0.000000           0        12           mprotect
  0.00    0.000000           0         1           munmap
  0.00    0.000000           0         3           brk
  0.00    0.000000           0         2           rt_sigaction
  0.00    0.000000           0         1           rt_sigprocmask
  0.00    0.000000           0         2           ioctl
  0.00    0.000000           0         8         8 access
  0.00    0.000000           0         1           execve
  0.00    0.000000           0         2           getdents
  0.00    0.000000           0         2         2 statfs
  0.00    0.000000           0         1           arch_prctl
  0.00    0.000000           0         1           set_tid_address
  0.00    0.000000           0         9           openat
  0.00    0.000000           0         1           set_robust_list
  0.00    0.000000           0         1           prlimit64
------ ----------- ----------- --------- --------- ----------------
100.00    0.000000                    93        10 total

On the other hand there is ltrace that traces functions.

$>ltrace -c cd
Desktop  Documents  Downloads  examples.desktop  Music  Pictures  Public  Templates  Videos
% time     seconds  usecs/call     calls      function
------ ----------- ----------- --------- --------------------
 15.52    0.004946         329        15 memcpy
 13.34    0.004249          94        45 __ctype_get_mb_cur_max
 12.87    0.004099        2049         2 fclose
 12.12    0.003861          83        46 strlen
 10.96    0.003491         109        32 __errno_location
 10.37    0.003303         117        28 readdir
  8.41    0.002679         133        20 strcoll
  5.62    0.001791         111        16 __overflow
  3.24    0.001032         114         9 fwrite_unlocked
  1.26    0.000400         100         4 __freading
  1.17    0.000372          41         9 getenv
  0.70    0.000222         111         2 fflush
  0.67    0.000214         107         2 __fpending
  0.64    0.000203         101         2 fileno
  0.62    0.000196         196         1 closedir
  0.43    0.000138         138         1 setlocale
  0.36    0.000114         114         1 _setjmp
  0.31    0.000098          98         1 realloc
  0.25    0.000080          80         1 bindtextdomain
  0.21    0.000068          68         1 opendir
  0.19    0.000062          62         1 strrchr
  0.18    0.000056          56         1 isatty
  0.16    0.000051          51         1 ioctl
  0.15    0.000047          47         1 getopt_long
  0.14    0.000045          45         1 textdomain
  0.13    0.000042          42         1 __cxa_atexit
------ ----------- ----------- --------- --------------------
100.00    0.031859                   244 total

Although I checked the manuals several time, I haven't found the origin of the name strace but it is likely system-call trace, since this is obvious.

There are three bigger notes to say about strace.

Note 1: Both these functions strace and ltrace are using the system call ptrace. So ptrace system call is effectively how strace works.

The ptrace() system call provides a means by which one process (the "tracer") may observe and control the execution of another process (the "tracee"), and examine and change the tracee's memory and registers. It is primarily used to implement breakpoint debugging and system call tracing.

Note 2: There are different parameters you can use with strace, since strace can be very verbose. I like to experiment with -c which is like a summary of things. Based on -c you can select one system-call like -e trace=open where you will see only that call. This can be interesting if you are examining what files will be opened during the command you are tracing. And of course, you can use the grep for the same purpose but note you need to redirect like this 2>&1 | grep etc to understand that config files are referenced when the command was issued.

Note 3: I find this very important note. You are not limited to a specific architecture. strace will blow you mind, since it can trace over binaries of different architectures. enter image description here

String contains another two strings

With the code d.Contains(b + a) you check if "You hit someone for 50 damage" contains "someonedamage". And this (i guess) you don't want.

The + concats the two string of b and a.

You have to check it by

if(d.Contains(b) && d.Contains(a))

jQuery - Increase the value of a counter when a button is clicked

Several of the suggestions above use global variables. This is not a good solution for the problem. The count is specific to one element, and you can use jQuery's data function to bind an item of data to an element:

$('#counter').data('count', 0);
$('#update').click(function(){
    $('#counter').html(function(){
        var $this = $(this),
            count = $this.data('count') + 1;

        $this.data('count', count);
        return count;
    });
});

Note also that this uses the callback syntax of html to make the code more fluent and fast.

Is there a developers api for craigslist.org

Craiglist is pretty stingy with their data , they even go out of their way to block scraping. If you use ruby here is a gem I wrote to help scrape craiglist data you can search through multiple cities , calculate average price ect...

How to add external fonts to android application

To implement you need use Typeface go through with sample below

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
   if (view instanceof TextView) 
   {
      TextView textView = (TextView) view;
      textView.setTypeface(typeface);
      }
   }
}

How to create an executable .exe file from a .m file

The "StandAlone" method to compile .m file (or files) requires a set of Matlab published library (.dll) files on a target (non-Matlab) platform to allow execution of the compiler generated .exe.

Check MATLAB main site for their compiler products and their limitations.

How to add anchor tags dynamically to a div in Javascript?

<script type="text/javascript" language="javascript">
function createDiv()
{
  var divTag = document.createElement("div");            
  divTag.innerHTML = "Div tag created using Javascript DOM dynamically";        
  document.body.appendChild(divTag);
}
</script>

Java constant examples (Create a java file having only constants)

Both are valid but I normally choose interfaces. A class (abstract or not) is not needed if there is no implementations.

As an advise, try to choose the location of your constants wisely, they are part of your external contract. Do not put every single constant in one file.

For example, if a group of constants is only used in one class or one method put them in that class, the extended class or the implemented interfaces. If you do not take care you could end up with a big dependency mess.

Sometimes an enumeration is a good alternative to constants (Java 5), take look at: http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html

Stored procedure - return identity as output parameter or scalar

I prefer to return the identity value as an output parameter. The result of the SP should indicate whether it succeeded or not. A value of 0 indicates the SP successfully completed, a non-zero value indicates an error. Also, if you ever need to make a change and return an additional value from the SP you don't need to make any changes other than adding an additional output parameter.

How to change column datatype from character to numeric in PostgreSQL 8.4

If your VARCHAR column contains empty strings (which are not the same as NULL for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:

ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
            USING COALESCE(NULLIF(code, '')::NUMERIC, 0);

(found with the help of this answer)

Need to navigate to a folder in command prompt

To access another drive, type the drive's letter, followed by ":".

D:

Then enter:

cd d:\windows\movie

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

using awk with column value conditions

If you're looking for a particular string, put quotes around it:

awk '$1 == "findtext" {print $3}'

Otherwise, awk will assume it's a variable name.

Get current folder path

System.AppDomain.CurrentDomain.BaseDirectory

This will give you running directory of your application. This even works for web applications. Afterwards you can reach your file.

Is there a way to make npm install (the command) to work behind proxy?

Try to find .npmrc in C:\Users\.npmrc

then open (notepad), write, and save inside :

proxy=http://<username>:<pass>@<proxyhost>:<port>

PS : remove "<" and ">" please !!

how do you filter pandas dataframes by multiple columns

You can filter by multiple columns (more than two) by using the np.logical_and operator to replace & (or np.logical_or to replace |)

Here's an example function that does the job, if you provide target values for multiple fields. You can adapt it for different types of filtering and whatnot:

def filter_df(df, filter_values):
    """Filter df by matching targets for multiple columns.

    Args:
        df (pd.DataFrame): dataframe
        filter_values (None or dict): Dictionary of the form:
                `{<field>: <target_values_list>}`
            used to filter columns data.
    """
    import numpy as np
    if filter_values is None or not filter_values:
        return df
    return df[
        np.logical_and.reduce([
            df[column].isin(target_values) 
            for column, target_values in filter_values.items()
        ])
    ]

Usage:

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

filter_df(df, {
    'a': [1, 2, 3],
    'b': [1, 2, 4]
})

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

I had twoo users: one that had the sysadmin role, the other one (the problematic one) didn't.

So I logged in with the other user(you can create a new one) and checked the ckeck box 'sysadmin' from: Security --> Logins --> Right ckick on your SQL user name --> Properties --> Server Roles --> make sure that the 'sysadmin' checkbox has the check mark. Press OK and try connecting with the newly checked user.

Center HTML Input Text Field Placeholder

You can make like this:

    <center>
    <form action="" method="POST">
    <input type="text" class="emailField" placeholder="[email protected]" style="text-align: center" name="email" />
    <input type="submit" value="submit" />  
</form>
    </center>

Working CodePen here

Getting "conflicting types for function" in C, why?

Make sure that types in the function declaration are declared first.

/* start of the header file */
.
.
.
struct intr_frame{...}; //must be first!
.
.
.
void kill (struct intr_frame *);
.
.
.
/* end of the header file */

How to check if an array is empty?

To check array is null:

int arr[] = null;
if (arr == null) {
 System.out.println("array is null");
}

To check array is empty:

arr = new int[0];
if (arr.length == 0) {
 System.out.println("array is empty");
}

How do I make an HTML text box show a hint when empty?

The best way is to wire up your JavaScript events using some kind of JavaScript library like jQuery or YUI and put your code in an external .js-file.

But if you want a quick-and-dirty solution this is your inline HTML-solution:

<input type="text" id="textbox" value="Search"
    onclick="if(this.value=='Search'){this.value=''; this.style.color='#000'}" 
    onblur="if(this.value==''){this.value='Search'; this.style.color='#555'}" />

Updated: Added the requested coloring-stuff.

How to use phpexcel to read data and insert into database?

Using the PHPExcel library to read an Excel file and transfer the data into a database

//  Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';

$inputFileName = './sampleData/example1.xls';

//  Read your Excel workbook
try {
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
    die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}

//  Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0); 
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn();

//  Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){ 
    //  Read a row of data into an array
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                    NULL,
                                    TRUE,
                                    FALSE);
    //  Insert row data array into your database of choice here
}

Anything more becomes very dependent on your database, and how you want the data structured in it

Clear data in MySQL table with PHP?

TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.

we can use for truncate

TRUNCATE TABLE tablename

we can use for delete

DELETE FROM tablename

we can also give conditions as below

DELETE FROM tablename WHERE id='xyz'

What's better at freeing memory with PHP: unset() or $var = null

I created a new performance test for unset and =null, because as mentioned in the comments the here written has an error (the recreating of the elements). I used arrays, as you see it didn't matter now.

<?php
$arr1 = array();
$arr2 = array();
for ($i = 0; $i < 10000000; $i++) {
    $arr1[$i] = 'a';
    $arr2[$i] = 'a';
}

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $arr1[$i] = null;
}
$elapsed = microtime(true) - $start;

echo 'took '. $elapsed .'seconds<br>';

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    unset($arr2[$i]);
}
$elapsed = microtime(true) - $start;

echo 'took '. $elapsed .'seconds<br>';

But i can only test it on an PHP 5.5.9 server, here the results: - took 4.4571571350098 seconds - took 4.4425978660583 seconds

I prefer unset for readability reasons.

Why is jquery's .ajax() method not sending my session cookie?

Perhaps not 100% answering the question, but i stumbled onto this thread in the hope of solving a session problem when ajax-posting a fileupload from the assetmanager of the innovastudio editor. Eventually the solution was simple: they have a flash-uploader. Disabling that (setting

var flashUpload = false;   

in asset.php) and the lights started blinking again.

As these problems can be very hard to debug i found that putting something like the following in the upload handler will set you (well, me in this case) on the right track:

$sn=session_name();
error_log("session_name: $sn ");

if(isset($_GET[$sn])) error_log("session as GET param");
if(isset($_POST[$sn])) error_log("session as POST param");
if(isset($_COOKIE[$sn])) error_log("session as Cookie");
if(isset($PHPSESSID)) error_log("session as Global");

A dive into the log and I quickly spotted the missing session, where no cookie was sent.

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

How to detect orientation change?

- (void)viewDidLoad {
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(OrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}

-(void)OrientationDidChange:(NSNotification*)notification {
  UIDeviceOrientation Orientation=[[UIDevice currentDevice]orientation];

  if(Orientation==UIDeviceOrientationLandscapeLeft || Orientation==UIDeviceOrientationLandscapeRight) {
    NSLog(@"Landscape");
  } else if(Orientation==UIDeviceOrientationPortrait) {
    NSLog(@"Potrait Mode");
  }
}

NOTE: Just use this code to identify UIViewController is in which orientation

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

How do I calculate the date six months from the current date using the datetime Python module?

I could not find an exact solution to this question so i'll post my solution in case it may be of any help using stantard Calendar and datetime libs. this works for add and substract months, and accounts for month-end rolls and cases where the final month has less days than the initial one. I also have a more generalized solution if you are looking for more complex manipulation, it adds regular intervals (days, months, years, quarters, semeters, etc) like: '1m', '-9m', '-1.5y', '-3q', '1s' etc.

from datetime import datetime
from calendar import monthrange
def date_bump_months(start_date, months):
    """
    bumps months back and forth. 
    --> if initial date is end-of-month, i will move to corresponding month-end
    --> ir inital date.day is greater than end of month of final date, it casts it to momth-end
    """
    signbit = -1 if months < 0 else 1
    d_year, d_month = divmod(abs(months),12)    
    end_year = start_date.year + d_year*signbit 
    end_month = 0
    if signbit ==-1:            
        if d_month < start_date.month:
            end_month = start_date.month - d_month
        else:
            end_year -=1
            end_month = 12 - (d_month - start_date.month)
    else:
        end_month +=start_date.month
        if end_month  > 12:
            end_year +=1
            end_month -=12
    # check if we are running end-of-month dates
    eom_run = monthrange(start_date.year, start_date.month)[1]==start_date.day
    eom_month = monthrange((end_year), (end_month))[1]
    if eom_run:
        end_day = eom_month 
    else:
        end_day = min(start_date.day, eom_month )    
    return date(end_year, end_month, end_day)

When should we implement Serializable interface?

The answer to this question is, perhaps surprisingly, never, or more realistically, only when you are forced to for interoperability with legacy code. This is the recommendation in Effective Java, 3rd Edition by Joshua Bloch:

There is no reason to use Java serialization in any new system you write

Oracle's chief architect, Mark Reinhold, is on record as saying removing the current Java serialization mechanism is a long-term goal.


Why Java serialization is flawed

Java provides as part of the language a serialization scheme you can opt in to, by using the Serializable interface. This scheme however has several intractable flaws and should be treated as a failed experiment by the Java language designers.

  • It fundamentally pretends that one can talk about the serialized form of an object. But there are infinitely many serialization schemes, resulting in infinitely many serialized forms. By imposing one scheme, without any way of changing the scheme, applications can not use a scheme most appropriate for them.
  • It is implemented as an additional means of constructing objects, which bypasses any precondition checks your constructors or factory methods perform. Unless tricky, error prone, and difficult to test extra deserialization code is written, your code probably has a gaping security weakness.
  • Testing interoperability of different versions of the serialized form is very difficult.
  • Handling of immutable objects is troublesome.

What to do instead

Instead, use a serialization scheme that you can explicitly control. Such as Protocol Buffers, JSON, XML, or your own custom scheme.

PHP to write Tab Characters inside a file?

The tab character is \t. Notice the use of " instead of '.

$chunk = "abc\tdef\tghi";

PHP Strings - Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

...

\t horizontal tab (HT or 0x09 (9) in ASCII)


Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.

Including one C source file in another?

The C language doesn't prohibit that kind of #include, but the resulting translation unit still has to be valid C.

I don't know what program you're using with a .prj file. If you're using something like "make" or Visual Studio or whatever, just make sure that you set its list of files to be compiled without the one that can't compile independently.

jQuery - setting the selected value of a select control via its text description

take a look at the jquery selectedbox plugin

selectOptions(value[, clear]): 

Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");, or a regular expression $("#myselect2").selectOptions(/^val/i);.

You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

How to Bold entire row 10 example:

workSheet.Cells[10, 1].EntireRow.Font.Bold = true;    

More formally:

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[10, 1] as Xl.Range;
rng.EntireRow.Font.Bold = true;

How to Bold Specific Cell 'A10' for example:

workSheet.Cells[10, 1].Font.Bold = true;

Little more formal:

int row = 1;
int column = 1;  /// 1 = 'A' in Excel

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[row, column] as Xl.Range;
rng.Font.Bold = true;

Android: Difference between Parcelable and Serializable?

Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations.

Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme.

I believe that Binder and AIDL work with Parcelable objects.

However, you can use Serializable objects in Intents.

How to send password securely over HTTP?

Using https sounds best option here (certificates are not that expensive nowadays). However if http is a requirement, you may use some encription - encript it on server side and decript in users browser (send key separately).

We have used that while implementing safevia.net - encription is done on clients (sender/receiver) sides, so users data are not available on network nor server layer.

Error message "Strict standards: Only variables should be passed by reference"

$instance->find() returns a reference to a variable.

You get the report when you are trying to use this reference as an argument to a function, without storing it in a variable first.

This helps preventing memory leaks and will probably become an error in the next PHP versions.

Your second code block would throw an error if it wrote like (note the & in the function signature):

function &get_arr(){
    return array(1, 2);
}
$el = array_shift(get_arr());

So a quick (and not so nice) fix would be:

$el = array_shift($tmp = $instance->find(..));

Basically, you do an assignment to a temporary variable first and send the variable as an argument.

Cannot open solution file in Visual Studio Code

VSCode is a code editor, not a full IDE. Think of VSCode as a notepad on steroids with IntelliSense code completion, richer semantic code understanding of multiple languages, code refactoring, including navigation, keyboard support with customizable bindings, syntax highlighting, bracket matching, auto indentation, and snippets.

It's not meant to replace Visual Studio, but making "Visual Studio" part of the name in VSCode will of course confuse some people at first.

Center text in table cell

How about simply (Please note, come up with a better name for the class name this is simply an example):

.centerText{
   text-align: center;
}


<div>
   <table style="width:100%">
   <tbody>
   <tr>
      <td class="centerText">Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td class="centerText">Cell 3</td>
      <td>Cell 4</td>
    </tr>
    </tbody>
    </table>
</div>

Example here

You can place the css in a separate file, which is recommended. In my example, I created a file called styles.css and placed my css rules in it. Then include it in the html document in the <head> section as follows:

<head>
    <link href="styles.css" rel="stylesheet" type="text/css">
</head>

The alternative, not creating a seperate css file, not recommended at all... Create <style> block in your <head> in the html document. Then just place your rules there.

<head>
 <style type="text/css">
   .centerText{
       text-align: center;
    }
 </style>
</head>

notifyDataSetChanged not working on RecyclerView

Try this method:

List<Business> mBusinesses2 = mBusinesses;
mBusinesses.clear();
mBusinesses.addAll(mBusinesses2);
//and do the notification

a little time consuming, but it should work.

jQuery autoComplete view all on click?

I can't see an obvious way to do that in the docs, but you try triggering the focus (or click) event on the autocomplete enabled textbox:

$('#myButton').click(function() {
   $('#autocomplete').trigger("focus"); //or "click", at least one should work
});

Get class list for element with jQuery

Here is a jQuery plugin which will return an array of all the classes the matched element(s) have

;!(function ($) {
    $.fn.classes = function (callback) {
        var classes = [];
        $.each(this, function (i, v) {
            var splitClassName = v.className.split(/\s+/);
            for (var j = 0; j < splitClassName.length; j++) {
                var className = splitClassName[j];
                if (-1 === classes.indexOf(className)) {
                    classes.push(className);
                }
            }
        });
        if ('function' === typeof callback) {
            for (var i in classes) {
                callback(classes[i]);
            }
        }
        return classes;
    };
})(jQuery);

Use it like

$('div').classes();

In your case returns

["Lorem", "ipsum", "dolor_spec", "sit", "amet"]

You can also pass a function to the method to be called on each class

$('div').classes(
    function(c) {
        // do something with each class
    }
);

Here is a jsFiddle I set up to demonstrate and test http://jsfiddle.net/GD8Qn/8/

Minified Javascript

;!function(e){e.fn.classes=function(t){var n=[];e.each(this,function(e,t){var r=t.className.split(/\s+/);for(var i in r){var s=r[i];if(-1===n.indexOf(s)){n.push(s)}}});if("function"===typeof t){for(var r in n){t(n[r])}}return n}}(jQuery);

Clear Application's Data Programmatically

There's a new API introduced in API 19 (KitKat): ActivityManager.clearApplicationUserData().

I highly recommend using it in new applications:

import android.os.Build.*;
if (VERSION_CODES.KITKAT <= VERSION.SDK_INT) {
    ((ActivityManager)context.getSystemService(ACTIVITY_SERVICE))
            .clearApplicationUserData(); // note: it has a return value!
} else {
    // use old hacky way, which can be removed
    // once minSdkVersion goes above 19 in a few years.
}

If you don't want the hacky way you can also hide the button on the UI, so that functionality is just not available on old phones.

Knowledge of this method is mandatory for anyone using android:manageSpaceActivity.


Whenever I use this, I do so from a manageSpaceActivity which has android:process=":manager". There, I manually kill any other processes of my app. This allows me to let a UI stay running and let the user decide where to go next.

private static void killProcessesAround(Activity activity) throws NameNotFoundException {
    ActivityManager am = (ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE);
    String myProcessPrefix = activity.getApplicationInfo().processName;
    String myProcessName = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).processName;
    for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
        if (proc.processName.startsWith(myProcessPrefix) && !proc.processName.equals(myProcessName)) {
            android.os.Process.killProcess(proc.pid);
        }
    }
}

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

You can access any LayoutParams from code using View.getLayoutParams. You just have to be very aware of what LayoutParams your accessing. This is normally achieved by checking the containing ViewGroup if it has a LayoutParams inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams. You'll be using RelativeLayout.LayoutParams#addRule(int verb) and RelativeLayout.LayoutParams#addRule(int verb, int anchor)

You can get to it via code:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);

button.setLayoutParams(params); //causes layout update

How can I clear an HTML file input with JavaScript?

Here are my two cents, the input files are stored as array so here is how to null it

document.getElementById('selector').value = []

this return an empty array and works on all browsers

Changing the width of Bootstrap popover

No final solution here :/ Just some thoughts how to "cleanly" solve this problem...

Updated version (jQuery 1.11 + Bootstrap 3.1.1 + class="col-xs-" instead of class="col-md-") of your original JSFiddle: http://jsfiddle.net/tkrotoff/N99h7/

Now the same JSFiddle with your proposed solution: http://jsfiddle.net/tkrotoff/N99h7/8/
It does not work: the popover is positioned relative to the <div class="col-*"> + imagine you have multiple inputs for the same <div class="col-*">...

So if we want to keep the popover on the inputs (semantically better):

  • .popover { position: fixed; }: but then each time you scroll the page, the popover will not follow the scroll
  • .popover { width: 100%; }: not that good since you still depend on the parent width (i.e <div class="col-*">
  • .popover-content { white-space: nowrap; }: good only if the text inside the popover is shorter than max-width

See http://jsfiddle.net/tkrotoff/N99h7/11/

Maybe, using very recent browsers, the new CSS width values can solve the problem, I didn't try.

How to remove the querystring and get only the url?

Try this

$url_with_querystring = 'www.mydomian.com/myurl.html?unwantedthngs';
$url_data = parse_url($url_with_querystring);
$url_without_querystring = str_replace('?'.$url_data['query'], '', $url_with_querystring);

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

If you're wondering why this optimization was added to range.__contains__, and why it wasn't added to xrange.__contains__ in 2.7:

First, as Ashwini Chaudhary discovered, issue 1766304 was opened explicitly to optimize [x]range.__contains__. A patch for this was accepted and checked in for 3.2, but not backported to 2.7 because "xrange has behaved like this for such a long time that I don't see what it buys us to commit the patch this late." (2.7 was nearly out at that point.)

Meanwhile:

Originally, xrange was a not-quite-sequence object. As the 3.1 docs say:

Range objects have very little behavior: they only support indexing, iteration, and the len function.

This wasn't quite true; an xrange object actually supported a few other things that come automatically with indexing and len,* including __contains__ (via linear search). But nobody thought it was worth making them full sequences at the time.

Then, as part of implementing the Abstract Base Classes PEP, it was important to figure out which builtin types should be marked as implementing which ABCs, and xrange/range claimed to implement collections.Sequence, even though it still only handled the same "very little behavior". Nobody noticed that problem until issue 9213. The patch for that issue not only added index and count to 3.2's range, it also re-worked the optimized __contains__ (which shares the same math with index, and is directly used by count).** This change went in for 3.2 as well, and was not backported to 2.x, because "it's a bugfix that adds new methods". (At this point, 2.7 was already past rc status.)

So, there were two chances to get this optimization backported to 2.7, but they were both rejected.


* In fact, you even get iteration for free with indexing alone, but in 2.3 xrange objects got a custom iterator.

** The first version actually reimplemented it, and got the details wrong—e.g., it would give you MyIntSubclass(2) in range(5) == False. But Daniel Stutzbach's updated version of the patch restored most of the previous code, including the fallback to the generic, slow _PySequence_IterSearch that pre-3.2 range.__contains__ was implicitly using when the optimization doesn't apply.

Android "elevation" not showing a shadow

Apparently, you cannot just set an elevation on a View and have it appear. You also need to specify a background.

The following lines added to my LinearLayout finally showed a shadow:

android:background="@android:color/white"
android:elevation="10dp"

NumPy array is not JSON serializable

use NumpyEncoder it will process json dump successfully.without throwing - NumPy array is not JSON serializable

import numpy as np
import json
from numpyencoder import NumpyEncoder
arr = array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64) 
json.dumps(arr,cls=NumpyEncoder)

How do we control web page caching, across all browsers?

Setting the modified http header to some date in 1995 usually does the trick.

Here's an example:

Expires: Wed, 15 Nov 1995 04:58:08 GMT
Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT
Cache-Control: no-cache, must-revalidate

java.lang.UnsupportedClassVersionError

Another option is to delete all the classes and rebuild. Having build file is an ideal solution to control whole process like compilation, packaging and deployment. You can also specify source/target versions

How to populate/instantiate a C# array with a single value?

this also works...but might be unnecessary

 bool[] abValues = new bool[1000];
 abValues = abValues.Select( n => n = true ).ToArray<bool>();

javascript unexpected identifier

It looks like there is an extra curly bracket in the code.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

Java Pass Method as Parameter

I'm not a java expert but I solve your problem like this:

@FunctionalInterface
public interface AutoCompleteCallable<T> {
  String call(T model) throws Exception;
}

I define the parameter in my special Interface

public <T> void initialize(List<T> entries, AutoCompleteCallable getSearchText) {.......
//call here
String value = getSearchText.call(item);
...
}

Finally, I implement getSearchText method while calling initialize method.

initialize(getMessageContactModelList(), new AutoCompleteCallable() {
          @Override
          public String call(Object model) throws Exception {
            return "custom string" + ((xxxModel)model.getTitle());
          }
        })

How to check if a char is equal to an empty space?

if (c == ' ')

char is a primitive data type, so it can be compared with ==.

Also, by using double quotes you create String constant (" "), while with single quotes it's a char constant (' ').

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                collisionCount++;
                System.out.println("Collision: " + asString + " <-> " + collisionString);
            }
        }

        System.out.println("Collision count: " + collisionCount);
    }

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;
                break;
            }
        }

        return new String(inputValue, 0, endIndex);
    }

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;
        }

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);
        }

    }

}

My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check

System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());

My output is

86390
86390

Conclusion:

If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

Split function equivalent in T-SQL?

I am tempted to squeeze in my favourite solution. The resulting table will consist of 2 columns: PosIdx for position of the found integer; and Value in integer.


create function FnSplitToTableInt
(
    @param nvarchar(4000)
)
returns table as
return
    with Numbers(Number) as 
    (
        select 1 
        union all 
        select Number + 1 from Numbers where Number < 4000
    ),
    Found as
    (
        select 
            Number as PosIdx,
            convert(int, ltrim(rtrim(convert(nvarchar(4000), 
                substring(@param, Number, 
                charindex(N',' collate Latin1_General_BIN, 
                @param + N',', Number) - Number))))) as Value
        from   
            Numbers 
        where  
            Number <= len(@param)
        and substring(N',' + @param, Number, 1) = N',' collate Latin1_General_BIN
    )
    select 
        PosIdx, 
        case when isnumeric(Value) = 1 
            then convert(int, Value) 
            else convert(int, null) end as Value 
    from 
        Found

It works by using recursive CTE as the list of positions, from 1 to 100 by default. If you need to work with string longer than 100, simply call this function using 'option (maxrecursion 4000)' like the following:


select * from FnSplitToTableInt
(
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' + 
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' +
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' +
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' +
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0'
) 
option (maxrecursion 4000)

What is the difference between static func and class func in Swift?

To declare a type variable property, mark the declaration with the static declaration modifier. Classes may mark type computed properties with the class declaration modifier instead to allow subclasses to override the superclass’s implementation. Type properties are discussed in Type Properties.

NOTE
In a class declaration, the keyword static has the same effect as marking the declaration with both the class and final declaration modifiers.

Source: The Swift Programming Language - Type Variable Properties

Javascript to set hidden form value on drop down change

Plain old Javascript:

<script type="text/javascript">

function changeHiddenInput (objDropDown)
{
    var objHidden = document.getElementById("hiddenInput");
    objHidden.value = objDropDown.value; 
}

</script>
<form>
    <select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
    </select>

    <input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
</form>

How to remove non UTF-8 characters from text file

This command:

iconv -f utf-8 -t utf-8 -c file.txt

will clean up your UTF-8 file, skipping all the invalid characters.

-f is the source format
-t the target format
-c skips any invalid sequence

Checking if a list is empty with LINQ

You could do this:

public static Boolean IsEmpty<T>(this IEnumerable<T> source)
{
    if (source == null)
        return true; // or throw an exception
    return !source.Any();
}

Edit: Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the .Count property of those, instead of the .Any() approach, but then fall back to .Any() if no guarantee can be made.

Start index for iterating Python list

Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?

Use a normal for-loop with range(start, stop, step) (where start and step are optional arguments).

For example, looping through an array starting at index 1:

for i in range(1, len(arr)):
    print(arr[i])

how to sort an ArrayList in ascending order using Collections and Comparator

Here a complete example :

Suppose we have a Person class like :

public class Person
{
    protected String fname;
    protected String lname;

    public Person()
    {

    }

    public Person(String fname, String lname)
    {
        this.fname = fname;
        this.lname = lname;
    }

    public boolean equals(Object objet)
    {
        if(objet instanceof Person)
        {
            Person p = (Person) objet;
            return (p.getFname().equals(this.fname)) && p.getLname().equals(this.lname));
        }
        else return super.equals(objet);
    }

    @Override
    public String toString()
    {
        return "Person(fname : " + getFname + ", lname : " + getLname + ")";
    }

    /** Getters and Setters **/
}

Now we create a comparator :

import java.util.Comparator;

public class ComparePerson implements Comparator<Person>
{
    @Override
    public int compare(Person p1, Person p2)
    {
        if(p1.getFname().equalsIgnoreCase(p2.getFname()))
        {
            return p1.getLname().compareTo(p2.getLname());
        }
        return p1.getFname().compareTo(p2.getFname());
    }
}

Finally suppose we have a group of persons :

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

public class Group
{
    protected List<Person> listPersons;

    public Group()
    {
        this.listPersons = new ArrayList<Person>();
    }

    public Group(List<Person> listPersons)
    {
        this.listPersons = listPersons;
    }

    public void order(boolean asc)
    {
        Comparator<Person> comp = asc ? new ComparePerson() : Collections.reverseOrder(new ComparePerson());
        Collections.sort(this.listPersons, comp);
    }

    public void display()
    {
        for(Person p : this.listPersons)
        {
            System.out.println(p);
        }
    }

    /** Getters and Setters **/
}

Now we try this :

import java.util.ArrayList;
import java.util.List;

public class App
{
    public static void main(String[] args)
    {
        Group g = new Group();
        List listPersons = new ArrayList<Person>();
        g.setListPersons(listPersons);

        Person p;

        p = new Person("A", "B");
        listPersons.add(p);

        p = new Person("C", "D");
        listPersons.add(p);

        /** you can add Person as many as you want **/

        g.display();

        g.order(true);
        g.display();

        g.order(false);
        g.display();
    }
}

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I know this is old but this answer still applies to newer Core releases.

If by chance your DbContext implementation is in a different project than your startup project and you run ef migrations, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations know where they're at.

dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]

Both -s and -p are optionals that default to the current folder.

PHP: Call to undefined function: simplexml_load_string()

I think it can be something like in this Post: Class 'SimpleXMLElement' not found on puphpet PHP 5.6 So maybe you could install/activate

php-xml or php-simplexml

Do not forget to activate the libraries in the php.ini file. (like the top comment)

jquery - check length of input field?

If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.

Something like:

$("#fbss").keypress(function() {
    if($(this).val().length > 1) {
         // Enable submit button
    } else {
         // Disable submit button
    }
});

How to load a controller from another controller in codeigniter?

There are many ways by which you can access one controller into another.

class Test1 extends CI_controller
{
    function testfunction(){
        return 1;
    }
}

Then create another class, and include first Class in it, and extend it with your class.

include 'Test1.php';

class Test extends Test1
{
    function myfunction(){
        $this->test();
        echo 1;
    }
}

How to count TRUE values in a logical vector

There are some problems when logical vector contains NA values.
See for example:

z <- c(TRUE, FALSE, NA)
sum(z) # gives you NA
table(z)["TRUE"] # gives you 1
length(z[z == TRUE]) # f3lix answer, gives you 2 (because NA indexing returns values)

So I think the safest is to use na.rm = TRUE:

sum(z, na.rm = TRUE) # best way to count TRUE values

(which gives 1). I think that table solution is less efficient (look at the code of table function).

Also, you should be careful with the "table" solution, in case there are no TRUE values in the logical vector. Suppose z <- c(NA, FALSE, NA) or simply z <- c(FALSE, FALSE), then table(z)["TRUE"] gives you NA for both cases.

Getting path of captured image in Android using camera intent

Try this method to get path of original image captured by camera.

public String getOriginalImagePath() {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        int column_index_data = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToLast();

        return cursor.getString(column_index_data);
    }

This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.

How can I refresh a page with jQuery?

Three approaches with different cache-related behaviours:

  • location.reload(true)

    In browsers that implement the forcedReload parameter of location.reload(), reloads by fetching a fresh copy of the page and all of its resources (scripts, stylesheets, images, etc.). Will not serve any resources from the cache - gets fresh copies from the server without sending any if-modified-since or if-none-match headers in the request.

    Equivalent to the user doing a "hard reload" in browsers where that's possible.

    Note that passing true to location.reload() is supported in Firefox (see MDN) and Internet Explorer (see MSDN) but is not supported universally and is not part of the W3 HTML 5 spec, nor the W3 draft HTML 5.1 spec, nor the WHATWG HTML Living Standard.

    In unsupporting browsers, like Google Chrome, location.reload(true) behaves the same as location.reload().

  • location.reload() or location.reload(false)

    Reloads the page, fetching a fresh, non-cached copy of the page HTML itself, and performing RFC 7234 revalidation requests for any resources (like scripts) that the browser has cached, even if they are fresh are RFC 7234 permits the browser to serve them without revalidation.

    Exactly how the browser should utilise its cache when performing a location.reload() call isn't specified or documented as far as I can tell; I determined the behaviour above by experimentation.

    This is equivalent to the user simply pressing the "refresh" button in their browser.

  • location = location (or infinitely many other possible techniques that involve assigning to location or to its properties)

    Only works if the page's URL doesn't contain a fragid/hashbang!

    Reloads the page without refetching or revalidating any fresh resources from the cache. If the page's HTML itself is fresh, this will reload the page without performing any HTTP requests at all.

    This is equivalent (from a caching perspective) to the user opening the page in a new tab.

    However, if the page's URL contains a hash, this will have no effect.

    Again, the caching behaviour here is unspecified as far as I know; I determined it by testing.

So, in summary, you want to use:

  • location = location for maximum use of the cache, as long as the page doesn't have a hash in its URL, in which case this won't work
  • location.reload(true) to fetch new copies of all resources without revalidating (although it's not universally supported and will behave no differently to location.reload() in some browsers, like Chrome)
  • location.reload() to faithfully reproduce the effect of the user clicking the 'refresh' button.

jQuery - Detect value change on hidden input field

$('#userid').change(function(){
  //fire your ajax call  
});

$('#userid').val(10).change();

Is there a way to take the first 1000 rows of a Spark Dataframe?

The method you are looking for is .limit.

Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.

Example usage:

df.limit(1000)

Add views below toolbar in CoordinatorLayout

As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView.

app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"

How do I expand the output display to see more columns of a pandas DataFrame?

You can use print df.describe().to_string() to force it to show the whole table. (You can use to_string() like this for any DataFrame. The result of describe is just a DataFrame itself.)

The 8 is the number of rows in the DataFrame holding the "description" (because describe computes 8 statistics, min, max, mean, etc.).

Passing multiple parameters with $.ajax url

Why are you combining GET and POST? Use one or the other.

$.ajax({
    type: 'post',
    data: {
        timestamp: timestamp,
        uid: uid
        ...
    }
});

php:

$uid =$_POST['uid'];

Or, just format your request properly (you're missing the ampersands for the get parameters).

url:"getdata.php?timestamp="+timestamp+"&uid="+id+"&uname="+name,

BOOLEAN or TINYINT confusion

Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.

A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).

It's a nit, but enough to cause unit tests to fail.

Applying .gitignore to committed files

After editing .gitignore to match the ignored files, you can do git ls-files -ci --exclude-standard to see the files that are included in the exclude lists; you can then do

  • Linux/MacOS: git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
  • Windows (PowerShell): git ls-files -ci --exclude-standard | % { git rm --cached "$_" }
  • Windows (cmd.exe): for /F "tokens=*" %a in ('git ls-files -ci --exclude-standard') do @git rm --cached "%a"

to remove them from the repository (without deleting them from disk).

Edit: You can also add this as an alias in your .gitconfig file so you can run it anytime you like. Just add the following line under the [alias] section (modify as needed for Windows or Mac):

apply-gitignore = !git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached

(The -r flag in xargs prevents git rm from running on an empty result and printing out its usage message, but may only be supported by GNU findutils. Other versions of xargs may or may not have a similar option.)

Now you can just type git apply-gitignore in your repo, and it'll do the work for you!

How can I do a line break (line continuation) in Python?

What is the line? You can just have arguments on the next line without any problems:

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
            blahblah6, blahblah7)

Otherwise you can do something like this:

if (a == True and
    b == False):

or with explicit line break:

if a == True and \
   b == False:

Check the style guide for more information.

Using parentheses, your example can be written over multiple lines:

a = ('1' + '2' + '3' +
    '4' + '5')

The same effect can be obtained using explicit line break:

a = '1' + '2' + '3' + \
    '4' + '5'

Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.

Compute a confidence interval from sample data

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module:

from statistics import NormalDist

def confidence_interval(data, confidence=0.95):
  dist = NormalDist.from_samples(data)
  z = NormalDist().inv_cdf((1 + confidence) / 2.)
  h = dist.stdev * z / ((len(data) - 1) ** .5)
  return dist.mean - h, dist.mean + h

This:

  • Creates a NormalDist object from the data sample (NormalDist.from_samples(data), which gives us access to the sample's mean and standard deviation via NormalDist.mean and NormalDist.stdev.

  • Compute the Z-score based on the standard normal distribution (represented by NormalDist()) for the given confidence using the inverse of the cumulative distribution function (inv_cdf).

  • Produces the confidence interval based on the sample's standard deviation and mean.


This assumes the sample size is big enough (let's say more than ~100 points) in order to use the standard normal distribution rather than the student's t distribution to compute the z value.

how to inherit Constructor from super class to sub class

Say if you have

/**
 * 
 */
public KKSSocket(final KKSApp app, final String name) {
    this.app = app;
    this.name = name;
    ...
}

then a sub-class named KKSUDPSocket extending KKSSocket could have:

/**
 * @param app
 * @param path
 * @param remoteAddr
 */
public KKSUDPSocket(KKSApp app, String path, KKSAddress remoteAddr) {
    super(app, path, remoteAddr);
}

and

/**
 * @param app
 * @param path
 */
public KKSUDPSocket(KKSApp app, String path) {
    super(app, path);
}

You simply pass the arguments up the constructor chain, like method calls to super classes, but using super(...) which references the super-class constructor and passes in the given args.

How to globally replace a forward slash in a JavaScript string?

Hi a small correction in the above script.. above script skipping the first character when displaying the output.

function stripSlashes(x)
{
var y = "";
for(i = 0; i < x.length; i++)
{
    if(x.charAt(i) == "/")
    {
        y += "";
    }
    else
    {
        y+= x.charAt(i);
    }
}
return y;   
}

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

How do you share constants in NodeJS modules?

I found the solution Dominic suggested to be the best one, but it still misses one feature of the "const" declaration. When you declare a constant in JS with the "const" keyword, the existence of the constant is checked at parse time, not at runtime. So if you misspelled the name of the constant somewhere later in your code, you'll get an error when you try to start your node.js program. Which is a far more better misspelling check.

If you define the constant with the define() function like Dominic suggested, you won't get an error if you misspelled the constant, and the value of the misspelled constant will be undefined (which can lead to debugging headaches).

But I guess this is the best we can get.

Additionally, here's a kind of improvement of Dominic's function, in constans.js:

global.define = function ( name, value, exportsObject )
{
    if ( !exportsObject )
    {
        if ( exports.exportsObject )
            exportsObject = exports.exportsObject;
        else 
            exportsObject = exports;        
    }

    Object.defineProperty( exportsObject, name, {
        'value': value,
        'enumerable': true,
        'writable': false,
    });
}

exports.exportObject = null;

In this way you can use the define() function in other modules, and it allows you to define constants both inside the constants.js module and constants inside your module from which you called the function. Declaring module constants can then be done in two ways (in script.js).

First:

require( './constants.js' );

define( 'SOME_LOCAL_CONSTANT', "const value 1", this ); // constant in script.js
define( 'SOME_OTHER_LOCAL_CONSTANT', "const value 2", this ); // constant in script.js

define( 'CONSTANT_IN_CONSTANTS_MODULE', "const value x" ); // this is a constant in constants.js module

Second:

constants = require( './constants.js' );

// More convenient for setting a lot of constants inside the module
constants.exportsObject = this;
define( 'SOME_CONSTANT', "const value 1" ); // constant in script.js
define( 'SOME_OTHER_CONSTANT', "const value 2" ); // constant in script.js

Also, if you want the define() function to be called only from the constants module (not to bloat the global object), you define it like this in constants.js:

exports.define = function ( name, value, exportsObject )

and use it like this in script.js:

constants.define( 'SOME_CONSTANT', "const value 1" );

how to detect search engine bots with php?

Because any client can set the user-agent to what they want, looking for 'Googlebot', 'bingbot' etc is only half the job.

The 2nd part is verifying the client's IP. In the old days this required maintaining IP lists. All the lists you find online are outdated. The top search engines officially support verification through DNS, as explained by Google https://support.google.com/webmasters/answer/80553 and Bing http://www.bing.com/webmaster/help/how-to-verify-bingbot-3905dc26

At first perform a reverse DNS lookup of the client IP. For Google this brings a host name under googlebot.com, for Bing it's under search.msn.com. Then, because someone could set such a reverse DNS on his IP, you need to verify with a forward DNS lookup on that hostname. If the resulting IP is the same as the one of the site's visitor, you're sure it's a crawler from that search engine.

I've written a library in Java that performs these checks for you. Feel free to port it to PHP. It's on GitHub: https://github.com/optimaize/webcrawler-verifier

Adding local .aar files to Gradle build using "flatDirs" is not working

This solution is working with Android Studio 4.0.1.

Apart from creating a new module as suggested in above solution, you can try this solution.

If you have multiple modules in your application and want to add aar to just one of the module then this solution come handy.

In your root project build.gradle

add

repositories {
flatDir {
    dirs 'libs'
}}

Then in the module where you want to add the .aar file locally. simply add below lines of code.

dependencies {
api fileTree(include: ['*.aar'], dir: 'libs')
implementation files('libs/<yourAarName>.aar')

}

Happy Coding :)

Basic Authentication Using JavaScript

Today we use Bearer token more often that Basic Authentication but if you want to have Basic Authentication first to get Bearer token then there is a couple ways:

const request = new XMLHttpRequest();
request.open('GET', url, false, username,password)
request.onreadystatechange = function() {
        // D some business logics here if you receive return
   if(request.readyState === 4 && request.status === 200) {
       console.log(request.responseText);
   }
}
request.send()

Full syntax is here

Second Approach using Ajax:

$.ajax
({
  type: "GET",
  url: "abc.xyz",
  dataType: 'json',
  async: false,
  username: "username",
  password: "password",
  data: '{ "key":"sample" }',
  success: function (){
    alert('Thanks for your up vote!');
  }
});

Hopefully, this provides you a hint where to start API calls with JS. In Frameworks like Angular, React, etc there are more powerful ways to make API call with Basic Authentication or Oauth Authentication. Just explore it.

Adding Python Path on Windows 7

For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.

How to print to stderr in Python?

Nobody's mentioned logging yet, but logging was created specifically to communicate error messages. Basic configuration will set up a stream handler writing to stderr.

This script:

# foo.py
import logging

logging.basicConfig(format='%(message)s')
log = logging.getLogger(__name__)
log.warning('I print to stderr by default')
print('hello world')

has the following result when run on the command line:

$ python3 foo.py > bar.txt
I print to stderr by default

and bar.txt will contain the 'hello world' printed on stdout.

How to avoid "Permission denied" when using pip with virtualenv

You did not activate the virtual environment before using pip.

Try it with:

$(your venv path) . bin/activate

And then use pip -r requirements.txt on your main folder

nil detection in Go

The compiler is pointing the error to you, you're comparing a structure instance and nil. They're not of the same type so it considers it as an invalid comparison and yells at you.

What you want to do here is to compare a pointer to your config instance to nil, which is a valid comparison. To do that you can either use the golang new builtin, or initialize a pointer to it:

config := new(Config) // not nil

or

config := &Config{
                  host: "myhost.com", 
                  port: 22,
                 } // not nil

or

var config *Config // nil

Then you'll be able to check if

if config == nil {
    // then
}

What, exactly, is needed for "margin: 0 auto;" to work?

Off the top of my head, it needs a width. You need to specify the width of the container you are centering (not the parent width).

Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

Why is width: 100% not working on div {display: table-cell}?

Your 100% means 100% of the viewport, you can fix that using the vw unit besides the % unit at the width. The problem is that 100vw is related to the viewport, besides % is related to parent tag. Do like that:

.table-cell-wrapper {
    width: 100vw;
    height: 100%;  
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

How are booleans formatted in Strings in Python?

You may also use the Formatter class of string

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

These are the results

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language

Do you have to put Task.Run in a method to make it async?

One of the most important thing to remember when decorating a method with async is that at least there is one await operator inside the method. In your example, I would translate it as shown below using TaskCompletionSource.

private Task<int> DoWorkAsync()
{
    //create a task completion source
    //the type of the result value must be the same
    //as the type in the returning Task
    TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
    Task.Run(() =>
    {
        int result = 1 + 2;
        //set the result to TaskCompletionSource
        tcs.SetResult(result);
    });
    //return the Task
    return tcs.Task;
}

private async void DoWork()
{
    int result = await DoWorkAsync();
}