Programs & Examples On #Sysinternals

Windows Sysinternals is a part of the Microsoft TechNet website which offers technical resources and utilities to manage, diagnose, troubleshoot, and monitor a Microsoft Windows environment.

Executing a batch file in a remote machine through PsExec

Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!

@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call


:: help
if '%1' =='-h' (
 echo.
 echo %~n0
 echo.
 echo Runs a command on one or many remote machines. If no input parameters
 echo are given you will be asked for a target remote machine.
 echo.
 echo You will be prompted for remote credentials with elevated privileges.
 echo.
 echo UNC paths and local paths can be supplied.
 echo Commands will be executed on the remote side just the way you typed
 echo them, so be sure to mind extensions and the path variable!
 echo.
 echo Please note that PsExec.exe must be allowed on remote machines, i.e.
 echo not blocked by firewall or antivirus solutions.
 echo.
 echo Syntax: %~n0 [^<inputfile^>]
 echo.
 echo     inputfile      = a plain text file ^(one hostname or ip address per line^)
 echo.
 echo.
 echo Example:
 echo %~n0 mylist.txt
 exit /b 0
)


:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
 echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
 echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
 "%temp%\getadmin.vbs"
 del "%temp%\getadmin.vbs"
 exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
 cls
 echo ERROR: This script requires elevated privileges!
 echo.
 echo Launch by Right-Click / Run as Administrator ...
 pause
 exit /b 1
) else (
 rd /s /q "%ADMINTESTDIR%"
 echo Running with elevated privileges...
)
echo.


:checkRequirements
if not exist "%~dp0PsExec.exe" (
 echo PsExec.exe from Sysinternals/Microsoft not found 
 echo in %~dp0
 echo.
 echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
 echo.
 pause
 exit /B
)


:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory:  %cd%\
echo Script directory:   %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator : 
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password             : 
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1


:inputMultipleTargets
if not exist %REMOTE_LIST% (
 echo File %REMOTE_LIST% not found
 goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
 echo Access denied %REMOTE_LIST%
 goto menu
)
set batchProcessing=true
echo Batch processing:   %REMOTE_LIST%   ...
ping -n 2 127.0.0.1 >nul
goto runOnce


:menu
if exist "%~dp0last.computer"  set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing"   set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command"   set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo                (1)  select target computer [default]
echo                (2)  select multiple computers
echo                     -----------------------------------
echo                     last target : %LAST_COMPUTER%
echo                     last listing: %LAST_LISTING%
echo                     last path   : %LAST_DIRECTORY%
echo                     last command: %LAST_COMMAND%
echo                     last run    : %LAST_TIMESTAMP%
echo                     -----------------------------------
echo                (0)  exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...): 
if NOT DEFINED mychoice  goto promptSingleTarget
if "%mychoice%"=="1"     goto promptSingleTarget
if "%mychoice%"=="2"     goto promptMultipleTargets
if "%mychoice%"=="0"     goto end
goto mychoice


:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename             : 
goto inputMultipleTargets


:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer      : 
goto runOnce


:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo       Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder : 
SET /P REMOTE_CMD=Command with params: 
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle


:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
 if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
 if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart


:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart


:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu


:end
SET REMOTE_USER=
SET REMOTE_PASS=

Run PowerShell scripts on remote PC

Accepted answer doesn't work for me, but this does. Ensure script in the location (c:\temp_ below on each remote server. servers.txt contains a list of IP addresses (one per line).

psexec @servers.txt -u <username> cmd /c "powershell -noninteractive -file C:\temp\script.ps1"

Generate 'n' unique random numbers within a range

Generate the range of data first and then shuffle it like this

import random
data = range(numLow, numHigh)
random.shuffle(data)
print data

By doing this way, you will get all the numbers in the particular range but in a random order.

But you can use random.sample to get the number of elements you need, from a range of numbers like this

print random.sample(range(numLow, numHigh), 3)

Using the Underscore module with Node.js

As of today (April 30, 2012) you can use Underscore as usual on your Node.js code. Previous comments are right pointing that REPL interface (Node's command line mode) uses the "_" to hold the last result BUT on you are free to use it on your code files and it will work without a problem by doing the standard:

var _ = require('underscore');

Happy coding!

WPF Binding to parent DataContext

I dont know about XamGrid but that's what i'll do with a standard wpf DataGrid:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Since the TextBlock and the TextBox specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.

Change visibility of ASP.NET label with JavaScript

Try this.

<asp:Button id="myButton" runat="server" style="display:none" Text="Click Me" />

<script type="text/javascript">
    function ShowButton() {
        var buttonID = '<%= myButton.ClientID %>';
        var button = document.getElementById(buttonID);
        if(button) { button.style.display = 'inherit'; }
    }
</script>

Don't use server-side code to do this because that would require a postback. Instead of using Visibility="false", you can just set a CSS property that hides the button. Then, in javascript, switch that property back whenever you want to show the button again.

The ClientID is used because it can be different from the server ID if the button is inside a Naming Container control. These include Panels of various sorts.

What does <T> (angle brackets) mean in Java?

is called a generic type. You can instantiate an object Pool like this:

PoolFactory<Integer> pool = new Pool<Integer>();

The generic parameter can only be a reference type. So you can't use primitive types like int or double or char or other primitive types.

How to view/delete local storage in Firefox?

I could not use localStorage directly in the Firefox (v27) console. I got the error:

[Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: debugger eval code :: :: line 1" data: no]

What worked was:

window.content.localStorage

No shadow by default on Toolbar?

I had similar problem with the shadow. The shadow is drawn by direct parent of AppBarLayout in my case. If height of the parent is the same as AppBarLayout's the shadow cannot be drawn. So checking size of the parent layout and maybe layout remake can solve the problem. https://www.reddit.com/r/androiddev/comments/6xddb0/having_a_toolbar_as_a_fragment_the_shadow/

button image as form input submit button?

<div class="container-fluid login-container">
    <div class="row">
        <form (ngSubmit)="login('da')">
            <div class="col-md-4">
                    <div class="login-text">
                        Login
                    </div>
                    <div class="form-signin">
                            <input type="text" class="form-control" placeholder="Email" required>
                            <input type="password" class="form-control" placeholder="Password" required>
                    </div>
            </div>
            <div class="col-md-4">
                <div class="login-go-div">
                    <input type="image" src="../../../assets/images/svg/login-go-initial.svg" class="login-go"
                         onmouseover="this.src='../../../assets/images/svg/login-go.svg'"
                         onmouseout="this.src='../../../assets/images/svg/login-go-initial.svg'"/>
                </div>
            </div>
        </form>
    </div>
</div>

This is the working code for it.

jQuery OR Selector?

Use a comma.

'.classA, .classB'

You may choose to omit the space.

How to test that a registered variable is not empty?

(ansible 2.9.6 ansible-lint 4.2.0)

See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string

    when: test_myscript.stderr != ""

Correct syntax and also "Ansible Galaxy Warning-Free" option is

    when: test_myscript.stderr | length > 0

Quoting from source code

"Use when: var|length > 0 rather than when: var != "" (or ' 'conversely when: var|length == 0 rather than when: var == "")"


Notes

  1. Test empty bare variable e.g.
    - debug:
        msg: "Empty string '{{ var }}' evaluates to False"
      when: not var
      vars:
        var: ''

    - debug:
        msg: "Empty list {{ var }} evaluates to False"
      when: not var
      vars:
        var: []

give

    "msg": "Empty string '' evaluates to False"
    "msg": "Empty list [] evaluates to False"
  1. But, testing non-empty bare variable string depends on CONDITIONAL_BARE_VARS. Setting ANSIBLE_CONDITIONAL_BARE_VARS=false the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true the condition will fail
    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var
      vars:
        var: 'abc'

gives

fatal: [localhost]: FAILED! => 
  msg: |-
    The conditional check 'var' failed. The error was: error while 
    evaluating conditional (var): 'abc' is undefined

Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'). When the filter bool is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true and ANSIBLE_CONDITIONAL_BARE_VARS=false have no effect

    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var|bool
      vars:
        var: 'abc'

gives

skipping: [localhost]
  1. Quoting from Porting guide 2.8 Bare variables in conditionals
  - include_tasks: teardown.yml
    when: teardown

  - include_tasks: provision.yml
    when: not teardown

" based on a variable you define as a string (with quotation marks around it):"

  • In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'

  • In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'

  • In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')

  1. Quoting from CONDITIONAL_BARE_VARS

"Expect that this setting eventually will be deprecated after 2.12"

Multiple radio button groups in MVC 4 Razor

all you need is to tie the group to a different item in your model

@Html.RadioButtonFor(x => x.Field1, "Milk")
@Html.RadioButtonFor(x => x.Field1, "Butter")

@Html.RadioButtonFor(x => x.Field2, "Water")
@Html.RadioButtonFor(x => x.Field2, "Beer")

Proper way of checking if row exists in table in PL/SQL block

select nvl(max(1), 0) from mytable;

This statement yields 0 if there are no rows, 1 if you have at least one row in that table. It's way faster than doing a select count(*). The optimizer "sees" that only a single row needs to be fetched to answer the question.

Here's a (verbose) little example:

declare
  YES constant      signtype := 1;
  NO  constant      signtype := 0;
  v_table_has_rows  signtype;
begin

  select nvl(max(YES), NO)
    into v_table_has_rows
    from mytable -- where ...
  ;

  if v_table_has_rows = YES then
    DBMS_OUTPUT.PUT_LINE ('mytable has at least one row');
  end if;

end;

Disable single warning error

In certain situations you must have a named parameter but you don't use it directly.
For example, I ran into it on VS2010, when 'e' is used only inside a decltype statement, the compiler complains but you must have the named varible e.

All the above non-#pragma suggestions all boil down to just adding a single statement:

bool f(int e)
{ 
   // code not using e
   return true;
   e; // use without doing anything
}

Passing parameter via url to sql server reporting service

I had the same question and more, and though this thread is old, it is still a good one, so in summary for SSRS 2008R2 I found...

Situations

  1. You want to use a value from a URL to look up data
  2. You want to display a parameter from a URL in a report
  3. You want to pass a parameter from one report to another report

Actions

If applicable, be sure to replace Reports/Pages/Report.aspx?ItemPath= with ReportServer?. In other words: Instead of this:

http://server/Reports/Pages/Report.aspx?ItemPath=/ReportFolder/ReportSubfolder/ReportName

Use this syntax:

http://server/ReportServer?/ReportFolder/ReportSubfolder/ReportName

Add parameter(s) to the report and set as hidden (or visible if user action allowed, though keep in mind that while the report parameter will change, the URL will not change based on an updated entry).

Attach parameters to URL with &ParameterName=Value

Parameters can be referenced or displayed in report using @ParameterName, whether they're set in the report or in the URL

To hide the toolbar where parameters are displayed, add &rc:Toolbar=false to the URL (reference)

Putting that all together, you can run a URL with embedded values, or call this as an action from one report and read by another report:

http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID=ABC123&rc:Toolbar=false

In report dataset properties query: SELECT stuff FROM view WHERE User = @UserID

In report, set expression value to [UserID] (or =Fields!UserID.Value)

Keep in mind that if a report has multiple parameters, you might need to include all parameters in the URL, even if blank, depending on how your dataset query is written.

To pass a parameter using Action = Go to URL, set expression to:

="http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID="
 &Fields!UserID.Value 
 &"&rc:Toolbar=false"
 &"&rs:ClearSession=True"

Be sure to have a space after an expression if followed by & (a line break is isn't enough). No space is required before an expression. This method can pass a parameter but does not hide it as it is visible in the URL.

If you don't include &rs:ClearSession=True then the report won't refresh until browser session cache is cleared.

To pass a parameter using Action = Go to report:

  • Specify the report
  • Add parameter(s) to run the report
  • Add parameter(s) you wish to pass (the parameters need to be defined in the destination report, so to my knowledge you can't use URL-specific commands such as rc:toolbar using this method); however, I suppose it would be possible to read or set the Prompt User checkbox, as seen in reporting sever parameters, through custom code in the report.)

For reference, / = %2f

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

If you use the procedural style, you have to provide both a connection and a string:

$name = mysqli_real_escape_string($conn, $name);

Only the object oriented version can be done with just a string:

$name = $link->real_escape_string($name);

The documentation should hopefully make this clear.

How to Delete Session Cookie?

Deleting a jQuery cookie:

$(function() {
    var COOKIE_NAME = 'test_cookie';
    var options = { path: '/', expires: 10 };
    $.cookie(COOKIE_NAME, 'test', options); // sets the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns test
    $.cookie(COOKIE_NAME, null, options);   // deletes the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns null
});

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

How to get default gateway in Mac OSX

Using System Preferences:

Step 1: Click the Apple icon (at the top left of the screen) and select System Preferences.

Step 2: Click Network.

Step 3: Select your network connection and then click Advanced.

Step 4: Select the TCP/IP tab and find your gateway IP address listed next to Router.

Spark - Error "A master URL must be set in your configuration" when submitting an app

I used this SparkContext constructor instead, and errors were gone:

val sc = new SparkContext("local[*]", "MyApp")

Get selected option text with JavaScript

Try the below:

myNewFunction = function(id, index) {
    var selection = document.getElementById(id);
    alert(selection.options[index].innerHTML);
};

See here jsfiddle sample

PHP combine two associative arrays into one array

        $array = array(
            22 => true,
            25 => true,
            34 => true,
            35 => true,
        );

        print_r(
            array_replace($array, [
                22 => true,
                42 => true,
            ])
        );

        print_r(
            array_merge($array, [
                22 => true,
                42 => true,
            ])
        );

If it is numeric but not sequential associative array, you need to use array_replace

How to split a string between letters and digits (or between digits and letters)?

You can try this:

Pattern p = Pattern.compile("[a-z]+|\\d+");
Matcher m = p.matcher("123abc345def");
ArrayList<String> allMatches = new ArrayList<>();
while (m.find()) {
    allMatches.add(m.group());
}

The result (allMatches) will be:

["123", "abc", "345", "def"]

How to put a delay on AngularJS instant search?

Angular 1.3 will have ng-model-options debounce, but until then, you have to use a timer like Josue Ibarra said. However, in his code he launches a timer on every key press. Also, he is using setTimeout, when in Angular one has to use $timeout or use $apply at the end of setTimeout.

How to run a PowerShell script

Type:

powershell -executionpolicy bypass -File .\Test.ps1

NOTE: Here Test.ps1 is the PowerShell script.

Lua string to int

tonumber (e [, base])

tonumber takes two arguments, first is string which is converted to number and second is base of e.

Return value tonumber is in base 10.

If no base is provided it converts number to base 10.

> a = '101'
> tonumber(a)
101

If base is provided, it converts it to the given base.

> a = '101'
> 
> tonumber(a, 2)
5
> tonumber(a, 8)
65
> tonumber(a, 10)
101
> tonumber(a, 16)
257
> 

If e contains invalid character then it returns nil.

> --[[ Failed because base 2 numbers consist (0 and 1) --]]
> a = '112'
> tonumber(a, 2)
nil
> 
> --[[ similar to above one, this failed because --]]
> --[[ base 8 consist (0 - 7) --]]
> --[[ base 10 consist (0 - 9) --]]
> a = 'AB'
> tonumber(a, 8)
nil
> tonumber(a, 10)
nil
> tonumber(a, 16)
171

I answered considering Lua5.3

Run a .bat file using python code

If you are trying to call another exe file inside the bat-file. You must use SET Path inside the bat-file that you are calling. set Path should point into the directory there the exe-file is located:

set PATH=C:\;C:\DOS     {Sets C:\;C:\DOS as the current search path.} 

Java, return if trimmed String in List contains String

Try this:

for(String str: myList) {
    if(str.trim().equals("A"))
       return true;
}
return false;

You need to use str.equals or str.equalsIgnoreCase instead of contains because contains in string works not the same as contains in List

List<String> s = Arrays.asList("BAB", "SAB", "DAS");
s.contains("A"); // false
"BAB".contains("A"); // true

spring data jpa @query and pageable

Declare native count queries for pagination at the query method by using @Query

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
  countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
  nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);

}

Hope this helps

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods

Best way to detect when a user leaves a web page?

I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:

window.onbeforeunload = function (e) {
        if ((window.event.clientY < 0)) {
            //window.localStorage.clear();
            //alert("Y coords: " + window.event.clientY)
        }
};

In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.

Creating a dictionary from a CSV file

For simple csv files, such as the following

id,col1,col2,col3
row1,r1c1,r1c2,r1c3
row2,r2c1,r2c2,r2c3
row3,r3c1,r3c2,r3c3
row4,r4c1,r4c2,r4c3

You can convert it to a Python dictionary using only built-ins

with open(csv_file) as f:
    csv_list = [[val.strip() for val in r.split(",")] for r in f.readlines()]

(_, *header), *data = csv_list
csv_dict = {}
for row in data:
    key, *values = row   
    csv_dict[key] = {key: value for key, value in zip(header, values)}

This should yield the following dictionary

{'row1': {'col1': 'r1c1', 'col2': 'r1c2', 'col3': 'r1c3'},
 'row2': {'col1': 'r2c1', 'col2': 'r2c2', 'col3': 'r2c3'},
 'row3': {'col1': 'r3c1', 'col2': 'r3c2', 'col3': 'r3c3'},
 'row4': {'col1': 'r4c1', 'col2': 'r4c2', 'col3': 'r4c3'}}

Note: Python dictionaries have unique keys, so if your csv file has duplicate ids you should append each row to a list.

for row in data:
    key, *values = row

    if key not in csv_dict:
            csv_dict[key] = []

    csv_dict[key].append({key: value for key, value in zip(header, values)})

jQuery function to get all unique elements from an array?

Based on @kennebec's answer, but fixed for IE8 and below by using jQuery wrappers around the array to provide missing Array functions filter and indexOf:

$.makeArray() wrapper might not be absolutely needed, but you'll get odd results if you omit this wrapper and JSON.stringify the result otherwise.

var a = [1,5,1,6,4,5,2,5,4,3,1,2,6,6,3,3,2,4];

// note: jQuery's filter params are opposite of javascript's native implementation :(
var unique = $.makeArray($(a).filter(function(i,itm){ 
    // note: 'index', not 'indexOf'
    return i == $(a).index(itm);
}));

// unique: [1, 5, 6, 4, 2, 3]

ModelState.AddModelError - How can I add an error that isn't for a property?

I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:

ModelState.AddModelError(string key, string errorMessage);

but use an empty string for the key:

ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

How do I use $rootScope in Angular to store variables?

first store the values in $rootScope as

.run(function($rootScope){
$rootScope.myData = {name : "nikhil"}
})

.controller('myCtrl', function($scope) {
var a ="Nikhilesh";
$scope.myData.name = a;
});

.controller('myCtrl2', function($scope) {
var b = $scope.myData.name;
)}

$rootScope is the parent of all $scope, each $scope receives a copy of $rootScope data which you can access using $scope itself.

Simple way to understand Encapsulation and Abstraction

An example using C#

//abstraction - exposing only the relevant behavior
public interface IMakeFire
{
     void LightFire();
}

//encapsulation - hiding things that the rest of the world doesn't need to see
public class Caveman: IMakeFire
{
     //exposed information  
     public string Name {get;set;}

     // exposed but unchangeable information
     public byte Age {get; private set;}

     //internal i.e hidden object detail. This can be changed freely, the outside world
     // doesn't know about it
     private bool CanMakeFire()
     {  
         return Age >7;
     }

     //implementation of a relevant feature
     public void LightFire()
     {
        if (!CanMakeFire())
        {
           throw new UnableToLightFireException("Too young");
        }
        GatherWood();
        GetFireStone();
        //light the fire

     }

     private GatherWood() {};
     private GetFireStone();
}

public class PersonWithMatch:IMakeFire
{
      //implementation
 }

Any caveman can make a fire, because it implements the IMakeFire 'feature'. Having a group of fire makers (List) this means that both Caveman and PersonWithMatch are valid choises.

This means that

  //this method (and class) isn't coupled to a Caveman or a PersonWithMatch
  // it can work with ANY object implementing IMakeFire
  public void FireStarter(IMakeFire starter)
  {
        starter.LightFire();
    }

So you can have lots of implementors with plenty of details (properties) and behavior(methods), but in this scenario what matters is their ability to make fire. This is abstraction.

Since making a fire requires some steps (GetWood etc), these are hidden from the view as they are an internal concern of the class. The caveman has many other public behaviors which can be called by the outside world. But some details will be always hidden because are related to internal working. They're private and exist only for the object, they are never exposed. This is encapsulation

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

How can I print a circular structure in a JSON-like format?

I'd recommend checking out json-stringify-safe from @isaacs-- it's used in NPM.

BTW- if you're not using Node.js, you can just copy and paste lines 4-27 from the relevant part of the source code.

To install:

$ npm install json-stringify-safe --save

To use:

// Require the thing
var stringify = require('json-stringify-safe');

// Take some nasty circular object
var theBigNasty = {
  a: "foo",
  b: theBigNasty
};

// Then clean it up a little bit
var sanitized = JSON.parse(stringify(theBigNasty));

This yields:

{
  a: 'foo',
  b: '[Circular]'
}

Note that, just like with the vanilla JSON.stringify function as @Rob W mentioned, you can also customize the sanitization behavior by passing in a "replacer" function as the second argument to stringify(). If you find yourself needing a simple example of how to do this, I just wrote a custom replacer which coerces errors, regexps, and functions into human-readable strings here.

includes() not working in all browsers

In my case i found better to use "string.search".

var str = "Some very very very long string";
var n = str.search("very");

In case it would be helpful for someone.

No restricted globals

This is a simple and maybe not the best solution, but it works.

On the line above the line you get your error, paste this:

// eslint-disable-next-line no-restricted-globals

How can I run a program from a batch file without leaving the console open after the program starts?

Loads of answers for this question already, but I am posting this to clarify something important, though this might not always be the case:

Start "C:\Program Files\someprog.exe"

Might cause issues in some windows versions as Start actually expects the first set of quotation marks to be a windows title. So it is best practice to first double quote a comment, or a blank comment:

Start "" "C:\Program Files\someprog.exe"

or

Start "Window Title" "C:\Program Files\someprog.exe"

What killed my process and why?

A tool like systemtap (or a tracer) can monitor kernel signal-transmission logic and report. e.g., https://sourceware.org/systemtap/examples/process/sigmon.stp

# stap .../sigmon.stp -x 31994 SIGKILL
   SPID     SNAME            RPID  RNAME            SIGNUM SIGNAME
   5609     bash             31994 find             9      SIGKILL

The filtering if block in that script can be adjusted to taste, or eliminated to trace systemwide signal traffic. Causes can be further isolated by collecting backtraces (add a print_backtrace() and/or print_ubacktrace() to the probe, for kernel- and userspace- respectively).

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector was part of 1.0 -- the original implementation had two drawbacks:

1. Naming: vectors are really just lists which can be accessed as arrays, so it should have been called ArrayList (which is the Java 1.2 Collections replacement for Vector).

2. Concurrency: All of the get(), set() methods are synchronized, so you can't have fine grained control over synchronization.

There is not much difference between ArrayList and Vector, but you should use ArrayList.

From the API doc.

As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized.

How to remove \n from a list element?

Since the OP's question is about stripping the newline character from the last element, I would reset it with the_list[-1].rstrip():

>>> the_list = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> the_list[-1] = ls[-1].rstrip()
>>> the_list
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']

It's O(1).

Session only cookies with Javascript

For creating session only cookie with java script, you can use the following. This works for me.

document.cookie = "cookiename=value; expires=0; path=/";

then get cookie value as following

 //get cookie 
var cookiename = getCookie("cookiename");
if (cookiename == "value") {
    //write your script
}

//function getCookie        
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

Okay to support IE we can leave "expires" completely and can use this

document.cookie = "mtracker=somevalue; path=/";

Getting DOM elements by classname

I think the accepted way is better, but I guess this might work as well

function getElementByClass(&$parentNode, $tagName, $className, $offset = 0) {
    $response = false;

    $childNodeList = $parentNode->getElementsByTagName($tagName);
    $tagCount = 0;
    for ($i = 0; $i < $childNodeList->length; $i++) {
        $temp = $childNodeList->item($i);
        if (stripos($temp->getAttribute('class'), $className) !== false) {
            if ($tagCount == $offset) {
                $response = $temp;
                break;
            }

            $tagCount++;
        }

    }

    return $response;
}

How do I select the parent form based on which submit button is clicked?

i used the following method & it worked fine for me

$('#mybutton').click(function(){
        clearForm($('#mybutton').closest("form"));
    });

$('#mybutton').closest("form") did the trick for me.

Null check in an enhanced for loop

I have modified the above answer, so you don't need to cast from Object

public static <T> List<T> safeClient( List<T> other ) {
            return other == null ? Collections.EMPTY_LIST : other;
}

and then simply call the List by

for (MyOwnObject ownObject : safeClient(someList)) {
    // do whatever
}

Explaination: MyOwnObject: If List<Integer> then MyOwnObject will be Integer in this case.

jQuery get specific option tag text

As an alternative solution, you can also use a context part of jQuery selector to find <option> element(s) with value="2" inside the dropdown list:

$("option[value='2']", "#list").text();

How to delete a certain row from mysql table with same column values?

All tables should have a primary key (consisting of a single or multiple columns), duplicate rows doesn't make sense in a relational database. You can limit the number of delete rows using LIMIT though:

DELETE FROM orders WHERE id_users = 1 AND id_product = 2 LIMIT 1

But that just solves your current issue, you should definitely work on the bigger issue by defining primary keys.

datetime datatype in java

java.time

The java.time framework built into Java 8 and later supplants both the old date-time classes bundled with the earliest versions of Java and the Joda-Time library. The java.time classes have been back-ported to Java 6 & 7 and to Android.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.now();

Apply an offset-from-UTC (a number of hours and possible minutes and seconds) to get an OffsetDateTime.

ZoneOffset offset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , offset );

Better yet is applying a full time zone which is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Database

Hopefully the JDBC drivers will be updated to work directly with the java.time classes. Until then we must use the java.sql classes to move date-time values to/from the database. But limit your use of the java.sql classes to the chore of database transit. Do not use them for business logic. As part of the old date-time classes they are poorly designed, confusing, and troublesome.

Use new methods added to the old classes to convert to/from java.time. Look for to… and valueOf methods.

Use the java.sql.Timestamp class for date-time values.

java.sql.Timestamp ts = java.sql.Timestamp.valueOf( instant );

And going the other direction…

Instant instant = ts.toInstant();

For date-time data you virtually always want the TIMESTAMP WITH TIME ZONE data type rather than WITHOUT when designing your table columns in your database.

How to print full stack trace in exception?

I usually use the .ToString() method on exceptions to present the full exception information (including the inner stack trace) in text:

catch (MyCustomException ex)
{
    Debug.WriteLine(ex.ToString());
}

Sample output:

ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes!
   at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14
   --- End of inner exception stack trace ---
   at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18
   at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23
   at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13

How do I analyze a program's core dump file with GDB when it has command-line parameters?

A slightly different approach will allow you to skip GDB entirely. If all you want is a backtrace, the Linux-specific utility 'catchsegv' will catch SIGSEGV and display a backtrace.

Using querySelectorAll to retrieve direct children

I'd have gone with

var myFoo = document.querySelectorAll("#myDiv > .foo");
var myDiv = myFoo.parentNode;

Adding elements to object

With that row

var element = {};

you define element to be a plain object. The native JavaScript object has no push() method. To add new items to a plain object use this syntax:

element[ yourKey ] = yourValue;

On the other hand you could define element as an array using

var element = [];

Then you can add elements using push().

Is there a way to do repetitive tasks at intervals?

Check out this library: https://github.com/robfig/cron

Example as below:

c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.AddFunc("@hourly",      func() { fmt.Println("Every hour") })
c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })
c.Start()

Java int to String - Integer.toString(i) vs new Integer(i).toString()

In terms of performance measurement, if you are considering the time performance then the Integer.toString(i); is expensive if you are calling less than 100 million times. Else if it is more than 100 million calls then the new Integer(10).toString() will perform better.

Below is the code through u can try to measure the performance,

public static void main(String args[]) {
            int MAX_ITERATION = 10000000;
        long starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s = Integer.toString(10);
        }
        long endtime = System.currentTimeMillis();
        System.out.println("diff1: " + (endtime-starttime));

        starttime = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATION; ++i) {
            String s1 = new Integer(10).toString();
        }
        endtime = System.currentTimeMillis();
        System.out.println("diff2: " + (endtime-starttime));
    }

In terms of memory, the

new Integer(i).toString();

will take more memory as it will create the object each time, so memory fragmentation will happen.

Flask-SQLAlchemy how to delete all rows in a single table

DazWorrall's answer is spot on. Here's a variation that might be useful if your code is structured differently than the OP's:

num_rows_deleted = db.session.query(Model).delete()

Also, don't forget that the deletion won't take effect until you commit, as in this snippet:

try:
    num_rows_deleted = db.session.query(Model).delete()
    db.session.commit()
except:
    db.session.rollback()

Get hours difference between two dates in Moment Js

var __startTime = moment("2016-06-06T09:00").format();
var __endTime = moment("2016-06-06T21:00").format();

var __duration = moment.duration(moment(__endTime).diff(__startTime));
var __hours = __duration.asHours();
console.log(__hours);

Find the min/max element of an array in JavaScript

Aside using the math function max and min, another function to use is the built in function of sort(): here we go

const nums = [12, 67, 58, 30].sort((x, y) => 
x -  y)
let min_val = nums[0]
let max_val = nums[nums.length -1]

AngularJS: Insert HTML from a string

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

Delimiter must not be alphanumeric or backslash and preg_match

You can also use T-Regx library which has automatic delimiters for you:

$matches = pattern("My name is '(.*)' and im fine")->match($string1)->all();

                 // ? No delimiters needed 

Using jQuery to compare two arrays of Javascript objects

_x000D_
_x000D_
var arr1 = [_x000D_
             {name: 'a', Val: 1}, _x000D_
             {name: 'b', Val: 2}, _x000D_
             {name: 'c', Val: 3}_x000D_
           ];_x000D_
_x000D_
var arr2 = [_x000D_
             {name: 'c', Val: 3},_x000D_
             {name: 'x', Val: 4}, _x000D_
             {name: 'y', Val: 5}, _x000D_
             {name: 'z', Val: 6}_x000D_
           ];_x000D_
var _isEqual = _.intersectionWith(arr1, arr2, _.isEqual);// common in both array_x000D_
var _difference1 = _.differenceWith(arr1, arr2, _.isEqual);//difference from array1 _x000D_
var _difference2 = _.differenceWith(arr2, arr1, _.isEqual);//difference from array2 _x000D_
console.log(_isEqual);// common in both array_x000D_
console.log(_difference1);//difference from array1 _x000D_
console.log(_difference2);//difference from array2 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
_x000D_
_x000D_
_x000D_

Find rows that have the same value on a column in MySQL

Here is query to find email's which are used for more then one login_id:

SELECT email
FROM table
GROUP BY email
HAVING count(*) > 1

You'll need second (of nested) query to get list of login_id by email.

JPA : How to convert a native query result set to POJO class collection

Use DTO Design Pattern. It was used in EJB 2.0. Entity was container managed. DTO Design Pattern is used to solve this problem. But, it might be use now, when the application is developed Server Side and Client Side separately.DTO is used when Server side doesn't want to pass/return Entity with annotation to Client Side.

DTO Example :

PersonEntity.java

@Entity
public class PersonEntity {
    @Id
    private String id;
    private String address;

    public PersonEntity(){

    }
    public PersonEntity(String id, String address) {
        this.id = id;
        this.address = address;
    }
    //getter and setter

}

PersonDTO.java

public class PersonDTO {
    private String id;
    private String address;

    public PersonDTO() {
    }
    public PersonDTO(String id, String address) {
        this.id = id;
        this.address = address;
    }

    //getter and setter 
}

DTOBuilder.java

public class DTOBuilder() {
    public static PersonDTO buildPersonDTO(PersonEntity person) {
        return new PersonDTO(person.getId(). person.getAddress());
    }
}

EntityBuilder.java <-- it mide be need

public class EntityBuilder() {
    public static PersonEntity buildPersonEntity(PersonDTO person) {
        return new PersonEntity(person.getId(). person.getAddress());
    }
}

Git pushing to remote branch

Simply push this branch to a different branch name

 git push -u origin localBranch:remoteBranch

How to check variable type at runtime in Go language

The answer by @Darius is the most idiomatic (and probably more performant) method. One limitation is that the type you are checking has to be of type interface{}. If you use a concrete type it will fail.

An alternative way to determine the type of something at run-time, including concrete types, is to use the Go reflect package. Chaining TypeOf(x).Kind() together you can get a reflect.Kind value which is a uint type: http://golang.org/pkg/reflect/#Kind

You can then do checks for types outside of a switch block, like so:

import (
    "fmt"
    "reflect"
)

// ....

x := 42
y := float32(43.3)
z := "hello"

xt := reflect.TypeOf(x).Kind()
yt := reflect.TypeOf(y).Kind()
zt := reflect.TypeOf(z).Kind()

fmt.Printf("%T: %s\n", xt, xt)
fmt.Printf("%T: %s\n", yt, yt)
fmt.Printf("%T: %s\n", zt, zt)

if xt == reflect.Int {
    println(">> x is int")
}
if yt == reflect.Float32 {
    println(">> y is float32")
}
if zt == reflect.String {
    println(">> z is string")
}

Which prints outs:

reflect.Kind: int
reflect.Kind: float32
reflect.Kind: string
>> x is int
>> y is float32
>> z is string

Again, this is probably not the preferred way to do it, but it's good to know alternative options.

How to sort with lambda in Python

Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

Remove NA values from a vector

Just in case someone new to R wants a simplified answer to the original question

How can I remove NA values from a vector?

Here it is:

Assume you have a vector foo as follows:

foo = c(1:10, NA, 20:30)

running length(foo) gives 22.

nona_foo = foo[!is.na(foo)]

length(nona_foo) is 21, because the NA values have been removed.

Remember is.na(foo) returns a boolean matrix, so indexing foo with the opposite of this value will give you all the elements which are not NA.

Find the number of columns in a table

Its been little late but please take it from me...

In the editor(New Query) by select the database object it can be a table too, if we use the Shortcut Key Alt+F1 we will get all the information of the object and I think will solve your problem as well.

Convert integer to binary in C#

primitive way:

public string ToBinary(int n)
{
    if (n < 2) return n.ToString();

    var divisor = n / 2;
    var remainder = n % 2;

    return ToBinary(divisor) + remainder;
}

How to apply box-shadow on all four sides?

The most simple solution and easiest way is to add shadow for all four side. CSS

box-shadow: 0 0 2px 2px #ccc; /* with blur shadow*/
box-shadow: 0 0 0 2px #ccc; /* without blur shadow*/

Python, creating objects

Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -

# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
    name = "Unknown name"
    age = 0
    major = "Unknown major"

You can create a make_student function by explicitly assigning the attributes to a new instance of Student -

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    return student

But it probably makes more sense to do this in a constructor (__init__) -

class Student(object):
    def __init__(self, name="Unknown name", age=0, major="Unknown major"):
        self.name = name
        self.age = age
        self.major = major

The constructor is called when you use Student(). It will take the arguments defined in the __init__ method. The constructor signature would now essentially be Student(name, age, major).

If you use that, then a make_student function is trivial (and superfluous) -

def make_student(name, age, major):
    return Student(name, age, major)

For fun, here is an example of how to create a make_student function without defining a class. Please do not try this at home.

def make_student(name, age, major):
    return type('Student', (object,),
                {'name': name, 'age': age, 'major': major})()

How to convert minutes to hours/minutes and add various time values together using jQuery?

This code can be used with timezone

javascript:

_x000D_
_x000D_
let minToHm = (m) => {_x000D_
  let h = Math.floor(m / 60);_x000D_
  h += (h < 0) ? 1 : 0;_x000D_
  let m2 = Math.abs(m % 60);_x000D_
  m2 = (m2 < 10) ? '0' + m2 : m2;_x000D_
  return (h < 0 ? '' : '+') + h + ':' + m2;_x000D_
}_x000D_
_x000D_
console.log(minToHm(210)) // "+3:30"_x000D_
console.log(minToHm(-210)) // "-3:30"_x000D_
console.log(minToHm(0)) // "+0:00"
_x000D_
_x000D_
_x000D_

minToHm(210)
"+3:30"

minToHm(-210)
"-3:30"

minToHm(0)
"+0:00"

How do I open an .exe from another C++ .exe?

You are getting this error because you are not giving full path. (C:\Users...\file.exe) If you want to remove this error then either give full path or copy that application (you want to open) to the folder where your project(.exe) is present/saved.

#include <windows.h>
using namespace std;
int main()
{
  system ("start C:\\Users\\Folder\\chrome.exe https://www.stackoverflow.com"); //for opening stackoverflow through google chrome , if chorme.exe is in that folder..
  return 0;
}

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

EDIT:

Forgot to say that this solution is in pure js, the only thing you need is a browser that supports promises https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Promise


For those who still needs to accomplish such, I've written my own solution that combines promises with timeouts.

Code:

/*
    class: Geolocalizer
        - Handles location triangulation and calculations.
        -- Returns various prototypes to fetch position from strings or coords or dragons or whatever.
*/

var Geolocalizer = function () {
    this.queue          = [];     // queue handler..
    this.resolved       = [];
    this.geolocalizer = new google.maps.Geocoder();  
};

Geolocalizer.prototype = {
    /*
        @fn: Localize
        @scope: resolve single or multiple queued requests.
        @params: <array> needles
        @returns: <deferred> object
    */
    Localize: function ( needles ) {
        var that = this;
        // Enqueue the needles.
        for ( var i = 0; i < needles.length; i++ ) {
            this.queue.push(needles[i]);
        }
        // return a promise and resolve it after every element have been fetched (either with success or failure), then reset the queue.
        return new Promise (
            function (resolve, reject) {
                that.resolveQueueElements().then(function(resolved){
                  resolve(resolved);
                  that.queue    = [];
                  that.resolved = [];
                });
            }
        );
    },

    /*
        @fn: resolveQueueElements
        @scope: resolve queue elements.
        @returns: <deferred> object (promise)
    */

    resolveQueueElements: function (callback) {
        var that = this;
        return new Promise(
            function(resolve, reject) {
                // Loop the queue and resolve each element.
                // Prevent QUERY_LIMIT by delaying actions by one second.
                (function loopWithDelay(such, queue, i){
                    console.log("Attempting the resolution of " +queue[i-1]);
                    setTimeout(function(){
                        such.find(queue[i-1], function(res){
                           such.resolved.push(res); 
                        });
                        if (--i) {
                            loopWithDelay(such,queue,i);
                        }
                    }, 1000);
                })(that, that.queue, that.queue.length);

                // Check every second if the queue has been cleared.
                var it = setInterval(function(){
                    if (that.queue.length == that.resolved.length) {
                        resolve(that.resolved);
                        clearInterval(it);
                    }
                }, 1000);
            }
        );
    },

    /*
        @fn: find
        @scope: resolve an address from string
        @params: <string> s, <fn> Callback
    */
    find: function (s, callback) {
        this.geolocalizer.geocode({
            "address": s
        }, function(res, status){
           if (status == google.maps.GeocoderStatus.OK) {
               var r = {
                   originalString:  s,
                   lat: res[0].geometry.location.lat(),
                   lng: res[0].geometry.location.lng()
               };
               callback(r);
           }
            else {
                callback(undefined);
                console.log(status);
                console.log("could not locate " + s);
            }
        });
    }
};

Please note that it's just a part of a bigger library I wrote to handle google maps stuff, hence comments may be confusing.

Usage is quite simple, the approach, however, is slightly different: instead of looping and resolving one address at a time, you will need to pass an array of addresses to the class and it will handle the search by itself, returning a promise which, when resolved, returns an array containing all the resolved (and unresolved) address.

Example:

var myAmazingGeo = new Geolocalizer();
var locations = ["Italy","California","Dragons are thugs...","China","Georgia"];
myAmazingGeo.Localize(locations).then(function(res){ 
   console.log(res); 
});

Console output:

Attempting the resolution of Georgia
Attempting the resolution of China
Attempting the resolution of Dragons are thugs...
Attempting the resolution of California
ZERO_RESULTS
could not locate Dragons are thugs...
Attempting the resolution of Italy

Object returned:

enter image description here

The whole magic happens here:

(function loopWithDelay(such, queue, i){
                    console.log("Attempting the resolution of " +queue[i-1]);
                    setTimeout(function(){
                        such.find(queue[i-1], function(res){
                           such.resolved.push(res); 
                        });
                        if (--i) {
                            loopWithDelay(such,queue,i);
                    }
                }, 750);
            })(that, that.queue, that.queue.length);

Basically, it loops every item with a delay of 750 milliseconds between each of them, hence every 750 milliseconds an address is controlled.

I've made some further testings and I've found out that even at 700 milliseconds I was sometimes getting the QUERY_LIMIT error, while with 750 I haven't had any issue at all.

In any case, feel free to edit the 750 above if you feel you are safe by handling a lower delay.

Hope this helps someone in the near future ;)

How can I keep Bootstrap popovers alive while being hovered?

Same thing for tooltips:

For me following solution works because it does not add event listeners on every 'mouseenter' and it is possible to hover back on the tooltip element which keeps the tooltip alive.

$ ->

  $('.element').tooltip({
    html: true,
    trigger: 'manual'
  }).
  on 'mouseenter', ->
    clearTimeout window.tooltipTimeout
    $(this).tooltip('show') unless $('.tooltip:visible').length > 0
  .
  on 'mouseleave', ->
    _this = this
    window.tooltipTimeout = setTimeout ->
      $(_this).tooltip('hide')
    , 100

$(document).on 'mouseenter', '.tooltip', ->
  clearTimeout window.tooltipTimeout

$(document).on 'mouseleave', '.tooltip', ->
  trigger = $($(this).siblings('.element')[0])
  window.tooltipTimeout = setTimeout ->
    trigger.tooltip('hide')
  , 100

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Setting top and left CSS attributes

We can create a new CSS class for div.

 .div {
      position: absolute;
      left: 150px;
      width: 200px;
      height: 120px;
    }

What causes: "Notice: Uninitialized string offset" to appear?

It means one of your arrays isn't actually an array.

By the way, your if check is unnecessary. If $varsCount is 0 the for loop won't execute anyway.

TortoiseSVN icons overlay not showing after updating to Windows 10

For anyone using Windows 10, there's a request in Feedback Hub to get Microsoft to fix this issue. If you'd like to add a +1 to have it fixed, here's a link: https://aka.ms/Cryalp.

The link only works on Windows 10 as it needs to open Feedback Hub to get to the suggestion. The link was generated using the "Share" feature in Feedback Hub and aka.ms is an internal link shortening service used by Microsoft.

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

How can I use grep to show just filenames on Linux?

Your question How can I just get the file-names (with paths)

Your syntax example find . -iname "*php" -exec grep -H myString {} \;

My Command suggestion

sudo find /home -name *.php

The output from this command on my Linux OS:

compose-sample-3/html/mail/contact_me.php

As you require the filename with path, enjoy!

alert a variable value

show alert box with use variable with message

<script>
$(document).ready(function() {
var total = 30 ;
alert("your total is :"+ total +"rs");
});
</script>

How do I convert a double into a string in C++?

You may want to read my prior posting on SO. (Macro'ed version with a temporary ostringstream object.)

For the record: In my own code, I favor snprintf(). With a char array on the local stack, it's not that inefficient. (Well, maybe if you exceeded the array size and looped to do it twice...)

(I've also wrapped it via vsnprintf(). But that costs me some type checking. Yelp if you want the code...)

Saving and loading objects and using pickle

You can use anycache to do the job for you. Assuming you have a function myfunc which creates the instance:

from anycache import anycache

class Fruits:pass

@anycache(cachedir='/path/to/your/cache')    
def myfunc()
    banana = Fruits()
    banana.color = 'yellow'
    banana.value = 30
return banana

Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the the function name and the arguments) as filename. On any consecutive run, the pickled object is loaded.

If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

The function arguments are also taken into account. A refactored implementation works likewise:

from anycache import anycache

class Fruits:pass

@anycache(cachedir='/path/to/your/cache')    
def myfunc(color, value)
    fruit = Fruits()
    fruit.color = color
    fruit.value = value
return fruit

How to download Javadoc to read offline?

update 2019-09-29: Java version 11

The technique below does not now work with Java 11, and probably higher versions: there is no way of ignoring multiple "broken links" (i.e. to other classes, other APIs). Solution: keep your javadoc executable file (or javadoc.exe) from Java version 8


There are good reasons for making your own local javadocs, and it's not particularly difficult!

First you need the source. At the time of writing the Java 8 JDK comes with a zip file called src.zip. Sometimes, for unexplained reasons, Oracle don't always include the source. So for some older versions (and who knows about the future) you have to get hold of the Java source in another way. It's worth also being aware that, in the past, Oracle have sometimes included the source with the Linux version of the JDK, but not with the Windows one.

I just unzipped this file... the top directories are "com", "java", "javax", "launcher" and "org". Directory launcher contains no files to document.

You can generate the javadocs very very simply from any or all of these by CD'ing at the command prompt/terminal to the directory ...\src. Then go

javadoc -d docs -Xmaxwarns 10 -Xmaxerrs 10 -Xdoclint:none -sourcepath . -subpackages java:javax:org:com

NB note that there is a "." after -sourcepath

Simple as that. Generating your own javadocs also has 2 huge advantages

  1. you know they are precisely the right javadocs for the JDK (or any exernal jar file) you are using on your system
  2. once you get into the habit, reconstituting your Javadocs is not a tiresome challenge (i.e. where to go looking for them). For example I just unzipped a couple of source jars whose packages are closely coupled, so their sources were in effect "merged" & then made a single Javadoc from them...

NB Swing is semi-officially DEAD. We should all be switching to JavaFX, which is helpfully bundled with Java 8 JDK, but in its own source file, javafx-src.zip.

Unzipped, this reveals 3 "root" packages: com, javafx and netscape (wha'?). These should be manually moved over the to appropriate places under the unzipped src directory (including the JavaFX com.sun packages under the Java com.sun strcture). Compiling all these Javadoc files took my machine a non-negligible time. I'd expect to see all the JavaFX source classes in with all the other source classes some time soon.


BTW, the same thinking applies to documenting any and all Java jars (with source) which you use. However, all versions of most jars will be found with their documentation available for download at Maven Central http://search.maven.org...

PS afterthought:
using Eclipse and the "Gradle STS" plugin: the "New Gradle STS Project" wizard will create a gradle.build file containing the line

include plugin: 'eclipse'

This magically downloads the source jar with the executable jar (under GRADLE_HOME) when you go

./gradlew build

[addendum 2020-01-13: if you have chosen not to include the Eclipse plugin in your build.gradle, it would appear that you can go (with the selection on your project in the Project Explorer) Right-click Gradle --> Refresh Gradle Project to get Eclipse to download the source files.]

... giving you an extra degree of certainty that you have got the right src and therefore the right javadoc for the dependency in question.

Splitting on first occurrence

>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'

How to create a shared library with cmake?

This minimal CMakeLists.txt file compiles a simple shared library:

cmake_minimum_required(VERSION 2.8)

project (test)
set(CMAKE_BUILD_TYPE Release)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
add_library(test SHARED src/test.cpp)

However, I have no experience copying files to a different destination with CMake. The file command with the COPY/INSTALL signature looks like it might be useful.

Keep CMD open after BAT file executes

Depending on how you are running the command, you can put /k after cmd to keep the window open.

cmd /k my_script.bat

Simply adding cmd /k to the end of your batch file will work too. Credit to Luigi D'Amico who posted about this in the comments below.

Eclipse error: 'Failed to create the Java Virtual Machine'

For me it solved by changing the JDK bin path in the Path environment variable. Put the JDK bin path which has jre/bin/client/jvm.dll under JDK home.

How do I hide the bullets on my list for the sidebar?

its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

add this to your css

ul{
     list-style:none;
}

How can I pass selected row to commandLink inside dataTable or ui:repeat?

As to the cause, the <f:attribute> is specific to the component itself (populated during view build time), not to the iterated row (populated during view render time).

There are several ways to achieve the requirement.

  1. If your servletcontainer supports a minimum of Servlet 3.0 / EL 2.2, then just pass it as an argument of action/listener method of UICommand component or AjaxBehavior tag. E.g.

     <h:commandLink action="#{bean.insert(item.id)}" value="insert" />
    

    In combination with:

     public void insert(Long id) {
         // ...
     }
    

    This only requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped.

    You can even pass the entire item object:

     <h:commandLink action="#{bean.insert(item)}" value="insert" />
    

    with:

     public void insert(Item item) {
         // ...
     }
    

    On Servlet 2.5 containers, this is also possible if you supply an EL implementation which supports this, like as JBoss EL. For configuration detail, see this answer.


  2. Use <f:param> in UICommand component. It adds a request parameter.

     <h:commandLink action="#{bean.insert}" value="insert">
         <f:param name="id" value="#{item.id}" />
     </h:commandLink>
    

    If your bean is request scoped, let JSF set it by @ManagedProperty

     @ManagedProperty(value="#{param.id}")
     private Long id; // +setter
    

    Or if your bean has a broader scope or if you want more fine grained validation/conversion, use <f:viewParam> on the target view, see also f:viewParam vs @ManagedProperty:

     <f:viewParam name="id" value="#{bean.id}" required="true" />
    

    Either way, this has the advantage that the datamodel doesn't necessarily need to be preserved for the form submit (for the case that your bean is request scoped).


  3. Use <f:setPropertyActionListener> in UICommand component. The advantage is that this removes the need for accessing the request parameter map when the bean has a broader scope than the request scope.

     <h:commandLink action="#{bean.insert}" value="insert">
         <f:setPropertyActionListener target="#{bean.id}" value="#{item.id}" />
     </h:commandLink>
    

    In combination with

     private Long id; // +setter
    

    It'll be just available by property id in action method. This only requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped.


  4. Bind the datatable value to DataModel<E> instead which in turn wraps the items.

     <h:dataTable value="#{bean.model}" var="item">
    

    with

     private transient DataModel<Item> model;
    
     public DataModel<Item> getModel() {
         if (model == null) {
             model = new ListDataModel<Item>(items);
         }
         return model;
     }
    

    (making it transient and lazily instantiating it in the getter is mandatory when you're using this on a view or session scoped bean since DataModel doesn't implement Serializable)

    Then you'll be able to access the current row by DataModel#getRowData() without passing anything around (JSF determines the row based on the request parameter name of the clicked command link/button).

     public void insert() {
         Item item = model.getRowData();
         Long id = item.getId();
         // ...
     }
    

    This also requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped.


  5. Use Application#evaluateExpressionGet() to programmatically evaluate the current #{item}.

     public void insert() {
         FacesContext context = FacesContext.getCurrentInstance();
         Item item = context.getApplication().evaluateExpressionGet(context, "#{item}", Item.class);
         Long id = item.getId();
         // ...
     }
    

Which way to choose depends on the functional requirements and whether the one or the other offers more advantages for other purposes. I personally would go ahead with #1 or, when you'd like to support servlet 2.5 containers as well, with #2.

How to call window.alert("message"); from C#?

It's a bit hard to give a definitive answer without a bit more information, but one usual way is to register a startup script:

try
{
  ...
}
catch(ApplicationException ex){
  Page.ClientScript.RegisterStartupScript(this.GetType(),"ErrorAlert","alert('Some text here - maybe ex.Message');",true);
}

How do I add an element to array in reducer of React native redux?

Two different options to add item to an array without mutation

case ADD_ITEM :
    return { 
        ...state,
        arr: [...state.arr, action.newItem]
    }

OR

case ADD_ITEM :
    return { 
        ...state,
        arr: state.arr.concat(action.newItem)
    }

Python Pandas - Missing required dependencies ['numpy'] 1

This worked in my anaconda environment, but I do not know why conda does not work. For some reason conda uninstall was not sufficient. This only worked with conda remove.

conda remove pandas
conda remove numpy
conda install pip
pip install pandas

*With help from this answer

This raises the following import warning in python 3.6 and 3.7:

ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__

If you with to ignore this warning (and maybe other ImportWarnings), add the following to your script before importing pandas:

import warnings
warnings.filterwarnings('ignore', category=ImportWarning, module='_bootstrap.py')

How to find the serial port number on Mac OS X?

mac os x don't use com numbers. you have to use something like 'ser:devicename' , 9600

How can I transition height: 0; to height: auto; using CSS?

There seems to be no proper solution. max-height approach is quite good but doesn't work well for the hide phase - there will be a noticeable delay unless you know the height of the content.

I think the best way is to use max-height but only for the show phase. And not to use any animation on hiding. For most cases it shouldn't be crucial.

max-height should be set to a quite huge value to ensure any content fits. Animation speed can be controlled using transition duration (speed = max-height / duration). Speed does not depend on the size of the content. The time it takes to show the whole content will depend on its size.

_x000D_
_x000D_
document.querySelector("button").addEventListener(_x000D_
  "click", _x000D_
  function(){_x000D_
    document.querySelector("div").classList.toggle("hide");_x000D_
  }_x000D_
)
_x000D_
div {    _x000D_
    max-height: 20000px;_x000D_
    transition: max-height 3000ms;_x000D_
    overflow-y: hidden;_x000D_
}_x000D_
_x000D_
.hide {_x000D_
    max-height: 0;_x000D_
    transition: none;_x000D_
}
_x000D_
<button>Toggle</button>_x000D_
<div class="hide">Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. Lorem ipsum dolor sit amet, ius solet dignissim honestatis ad. Mea quem tibique intellegat te. Insolens deterruisset cum ea. Te omnes percipit consulatu eos. Vix novum primis salutatus no, eam denique sensibus et, his ipsum senserit ne. _x000D_
</div>
_x000D_
_x000D_
_x000D_

What Vim command(s) can be used to quote/unquote words?

Here are some simple mappings that can be used to quote and unquote a word:

" 'quote' a word
nnoremap qw :silent! normal mpea'<Esc>bi'<Esc>`pl
" double "quote" a word
nnoremap qd :silent! normal mpea"<Esc>bi"<Esc>`pl
" remove quotes from a word
nnoremap wq :silent! normal mpeld bhd `ph<CR>

Get file path of image on Android

I am doing this on click of Button.

private static final int CAMERA_PIC_REQUEST = 1;

private View.OnClickListener  OpenCamera=new View.OnClickListener() {

            @Override
            public void onClick(View paramView) {
                // TODO Auto-generated method stub

                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                NewSelectedImageURL=null;
                //outfile where we are thinking of saving it
                Date date = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

                String newPicFile = RecipeName+ df.format(date) + ".png";


                String outPath =Environment.getExternalStorageDirectory() + "/myFolderName/"+ newPicFile ;
                File outFile = new File(outPath);               

                CapturedImageURL=outFile.toString();
                Uri outuri = Uri.fromFile(outFile);
                cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outuri);            
                startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  

            }
        };

You can get the URL of the recently Captured Image from variable CapturedImageURL

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  


    //////////////////////////////////////
    if (requestCode == CAMERA_PIC_REQUEST) {  
        // do something  

         if (resultCode == RESULT_OK) 
         {
             Uri uri = null;

             if (data != null) 
             {
                 uri = data.getData();
             }
             if (uri == null && CapturedImageURL != null) 
             {
                 uri = Uri.fromFile(new File(CapturedImageURL));
             }
             File file = new File(CapturedImageURL);
             if (!file.exists()) {
                file.mkdir();
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
            }




         }


    }

Differences between Oracle JDK and OpenJDK

According to the oracle blog, Oracle JDK Releases for Java 11 and Later

Starting with Java 11, Oracle will provide JDK releases under the open source GNU General Public License v2, with the Classpath Exception (GPLv2+CPE), and under a commercial license for those using the Oracle JDK as part of an Oracle product or service, or who do not wish to use open source software. This combination of using an open source license and a commercial license replaces the historical “BCL” license, which had a combination of free and paid commercial terms.

Different builds will be provided for each license, but these builds are functionally identical aside from some cosmetic and packaging differences, described in detail below.

From the BCL to the GPL

The Binary Code License for Oracle Java SE technologies (“BCL”) has been the primary license for Oracle Java SE technologies for well over a decade. The BCL permits use without license fees under certain conditions. To simplify things going forward, Oracle started providing open source licensed OpenJDK builds as of Java 9, using the same license model as the Linux platform. If you are used to getting Oracle Java SE binaries for free, you can simply continue doing so with Oracle’s OpenJDK builds available at jdk.java.net. If you are used to getting Oracle Java SE binaries as part of a commercial product or service from Oracle, then you can continue to get Oracle JDK releases through My Oracle Support (MOS), and other locations.

Functionally identical and interchangeable...

Oracle’s BCL-licensed JDK historically contained “commercial features” that were not available in OpenJDK builds. As promised, however, over the past year Oracle has contributed these features to the OpenJDK Community, including:

From Java 11 forward, therefore, Oracle JDK builds and OpenJDK builds will be essentially identical.

...yet with some cosmetic and packaging differences

There do remain a small number of differences, some intentional and cosmetic, and some simply because more time to discuss with OpenJDK contributors is warranted.

  • Oracle JDK 11 emits a warning when using the -XX:+UnlockCommercialFeatures option, whereas in OpenJDK builds this option results in an error. This option was never part of OpenJDK and it would not make sense to add it now, since there are no commercial features in OpenJDK. This difference remains in order to make it easier for users of Oracle JDK 10 and earlier releases to migrate to Oracle JDK 11 and later.
  • Oracle JDK 11 can be configured to provide usage log data to the “Advanced Management Console” tool, which is a separate commercial Oracle product. We will work with other OpenJDK contributors to discuss how such usage data may be useful in OpenJDK in future releases, if at all. This difference remains primarily to provide a consistent experience to Oracle customers until such decisions are made.
  • The javac --release command behaves differently for the Java 9 and Java 10 targets, since in those releases the Oracle JDK contained some additional modules that were not part of corresponding OpenJDK releases:
    • javafx.base
    • javafx.controls
    • javafx.fxml
    • javafx.graphics
    • javafx.media
    • javafx.web
    • java.jnlp
    • jdk.jfr
    • jdk.management.cmm
    • jdk.management.jfr
    • jdk.management.resource
    • jdk.packager.services
    • jdk.snmp

This difference remains in order to provide a consistent experience for specific kinds of legacy use. These modules are either now available separately as part of OpenJFX, are now in both OpenJDK and the Oracle JDK because they were commercial features which Oracle contributed to OpenJDK (e.g., Flight Recorder), or were removed from Oracle JDK 11 (e.g., JNLP).

  • The output of the java --version and java -fullversion commands will distinguish Oracle JDK builds from OpenJDK builds, so that support teams can diagnose any issues that may exist. Specifically, running java --version with an Oracle JDK 11 build results in:

java 11 2018-09-25

Java(TM) SE Runtime Environment 18.9 (build 11+28)

Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11+28, mixed mode)

And for an OpenJDK 11 build:

openjdk version "11" 2018-09-25

OpenJDK Runtime Environment 18.9 (build 11+28)

OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)

  • The Oracle JDK has always required third party cryptographic providers to be signed by a known certificate. The cryptography framework in OpenJDK has an open cryptographic interface, meaning it does not restrict which providers can be used. Oracle JDK 11 will continue to require a valid signature, and Oracle OpenJDK builds will continue to allow the use of either a valid signature or unsigned third party crypto provider.
  • Oracle JDK 11 will continue to include installers, branding and JRE packaging for an experience consistent with legacy desktop uses. Oracle OpenJDK builds are currently available as zip and tar.gz files, while alternative distribution formats are being considered.

Has an event handler already been added?

The only way that worked for me is creating a Boolean variable that I set to true when I add the event. Then I ask: If the variable is false, I add the event.

bool alreadyAdded = false;

This variable can be global.

if(!alreadyAdded)
{
    myClass.MyEvent += MyHandler;
    alreadyAdded = true;
}

Setting focus to a textbox control

Because you want to set it when the form loads, you have to first .Show() the form before you can call the .Focus() method. The form cannot take focus in the Load event until you show the form

Private Sub RibbonForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Me.Show()
    TextBox1.Select()
End Sub

Set up Python 3 build system with Sublime Text 3

first you need to find your python.exe location, to find location run this python script:

import sys
print(sys.executable)

Then you can create your custom python build:

{
"cmd": ["C:\\Users\\Sashi\\AppData\\Local\\Programs\\Python\\Python39\\python.exe", "-u", "$file"],
"file_regex": "^[ ]File \"(...?)\", line ([0-9]*)",
"selector": "source.python"}

You can change the location, In my case it is C:\Users\Sashi\AppData\Local\Programs\Python\Python39\python.exe

Then save your new build. Don't change the file extension while saving.

What is the difference between require() and library()?

Always use library. Never use require.

In a nutshell, this is because, when using require, your code might yield different, erroneous results, without signalling an error. This is rare but not hypothetical! Consider this code, which yields different results depending on whether {dplyr} can be loaded:

require(dplyr)

x = data.frame(y = seq(100))
y = 1
filter(x, y == 1)

This can lead to subtly wrong results. Using library instead of require throws an error here, signalling clearly that something is wrong. This is good.

It also makes debugging all other failures more difficult: If you require a package at the start of your script and use its exports in line 500, you’ll get an error message “object ‘foo’ not found” in line 500, rather than an error “there is no package called ‘bla’”.

The only acceptable use case of require is when its return value is immediately checked, as some of the other answers show. This is a fairly common pattern but even in these cases it is better (and recommended, see below) to instead separate the existence check and the loading of the package. That is: use requireNamespace instead of require in these cases.

More technically, require actually calls library internally (if the package wasn’t already attached — require thus performs a redundant check, because library also checks whether the package was already loaded). Here’s a simplified implementation of require to illustrate what it does:

require = function (package) {
    already_attached = paste('package:', package) %in% search()
    if (already_attached) return(TRUE)
    maybe_error = try(library(package, character.only = TRUE)) 
    success = ! inherits(maybe_error, 'try-error')
    if (! success) cat("Failed")
    success
}

Experienced R developers agree:

Yihui Xie, author of {knitr}, {bookdown} and many other packages says:

Ladies and gentlemen, I've said this before: require() is the wrong way to load an R package; use library() instead

Hadley Wickham, author of more popular R packages than anybody else, says

Use library(x) in data analysis scripts. […] You never need to use require() (requireNamespace() is almost always better)

What is the best way to filter a Java Collection?

With the ForEach DSL you may write

import static ch.akuhn.util.query.Query.select;
import static ch.akuhn.util.query.Query.$result;
import ch.akuhn.util.query.Select;

Collection<String> collection = ...

for (Select<String> each : select(collection)) {
    each.yield = each.value.length() > 3;
}

Collection<String> result = $result();

Given a collection of [The, quick, brown, fox, jumps, over, the, lazy, dog] this results in [quick, brown, jumps, over, lazy], ie all strings longer than three characters.

All iteration styles supported by the ForEach DSL are

  • AllSatisfy
  • AnySatisfy
  • Collect
  • Counnt
  • CutPieces
  • Detect
  • GroupedBy
  • IndexOf
  • InjectInto
  • Reject
  • Select

For more details, please refer to https://www.iam.unibe.ch/scg/svn_repos/Sources/ForEach

Clicking a button within a form causes page refresh

You can keep <button type="submit">, but must remove the attribute action="" of <form>.

Django CSRF check failing with an Ajax POST request

The {% csrf_token %} put in html templates inside <form></form>

translates to something like:

<input type='hidden' name='csrfmiddlewaretoken' value='Sdgrw2HfynbFgPcZ5sjaoAI5zsMZ4wZR' />

so why not just grep it in your JS like this:

token = $("#change_password-form").find('input[name=csrfmiddlewaretoken]').val()

and then pass it e.g doing some POST, like:

$.post( "/panel/change_password/", {foo: bar, csrfmiddlewaretoken: token}, function(data){
    console.log(data);
});

DateTimePicker time picker in 24 hour but displaying in 12hr?

Meridian pertains to AM/PM, by setting it to false you're indicating you don't want AM/PM, therefore you want 24-hour clock implicitly.

$('#timepicker1').timepicker({showMeridian:false});

How to get the first day of the current week and month?

I have created some methods for this:

public static String catchLastDayOfCurrentWeek(String pattern) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);

    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());

    return calendarToString(cal, pattern);
}

public static String catchLastDayOfCurrentWeek(String pattern) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);

    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());

    cal.add(Calendar.WEEK_OF_YEAR, 1);
    cal.add(Calendar.MILLISECOND, -1);

    return calendarToString(cal, pattern);
}

public static String catchTheFirstDayOfThemonth(Integer month, pattern padrao) {
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    return calendarToString(cal, pattern);
}

public static String catchTheLastDayOfThemonth(Integer month, String pattern) {
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(new Date());
    cal.set(cal.get(Calendar.YEAR), month, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

    return calendarToString(cal, pattern);
}

public static String calendarToString(Calendar calendar, String pattern) {
    if (calendar == null) {
        return "";
    }
    SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
    return format.format(calendar.getTime());
}

You can see more here.

How to use JavaScript with Selenium WebDriver Java

You can also try clicking by JavaScript:

WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);

Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.

Which HTTP methods match up to which CRUD methods?

Generally speaking, this is the pattern I use:

  • HTTP GET - SELECT/Request
  • HTTP PUT - UPDATE
  • HTTP POST - INSERT/Create
  • HTTP DELETE - DELETE

How to find the array index with a value?

Use indexOf

imageList.indexOf(200)

Windows batch: formatted date into variable

Check this one..

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" & set "MS=%dt:~15,3%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%-%MS%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

How to use underscore.js as a template engine?

with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :

npm install consolidate --save

then you should change the default engine to html template by this:

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

register the underscore template engine for the html extension:

app.engine('html', require('consolidate').underscore);

it's done !

Now for load for example an template called 'index.html':

res.render('index', { title : 'my first page'});

maybe you will need to install the underscore module.

npm install underscore --save

I hope this helped you!

C# Checking if button was clicked

i am very new to this website. I am an undergraduate student, doing my Bachelor Of Computer Application. I am doing a simple program in Visual Studio using C# and I came across the same problem, how to check whether a button is clicked? I wanted to do this,

if(-button1 is clicked-) then
{
this should happen;
}
if(-button2 is clicked-) then
{
this should happen;
}

I didn't know what to do, so I tried searching for the solution in the internet. I got many solutions which didn't help me. So, I tried something on my own and did this,

int i;
private void button1_Click(object sender, EventArgs e)
        {
            i = 1;
            label3.Text = "Principle";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Simple Interest";
        }


private void button2_Click(object sender, EventArgs e)
        {
            i = 2;
            label3.Text = "SI";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Principle";
        }
private void button5_Click(object sender, EventArgs e)
        {

            try
            {
                if (i == 1)
                {
                    si = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text)) / 100;
                    textBox4.Text = Convert.ToString(si);
                }
                if (i == 2)
                {
                    p = (Convert.ToInt32(textBox1.Text) * 100) / (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text));
                    textBox4.Text = Convert.ToString(p);
                }

I declared a variable "i" and assigned it with different values in different buttons and checked the value of i in the if function. It worked. Give your suggestions if any. Thank you.

Nginx not running with no error message

One case you check that nginx hold on 80 number port in system by default , check if you have any server like as apache or anything exist on system that block 80 number port thats the problem occurred.

1 .You change port number on nginx by this way,

sudo vim /etc/nginx/sites-available/default

Change 80 to 81 or anything,

  1. Check everything is ok by ,

sudo nginx -t

  1. Restart server

sudo service nginx start

  1. Check the status of nginx:

sudo service nginx status

Hope that will work

mysqli_real_connect(): (HY000/2002): No such file or directory

I had the same problem. In my /etc/mysql/my.cnf was no path more to mysqld.sock defined. So I started a search to find it with: find / -type s | grep mysqld.sock but it could not be found. I reinstalled mysql with: apt install mysql-server-5.7 (please check before execute the current sql-server-version).

This solved my problem.

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

All has great answer on the question, and yes this is only applicable when running it on the current directory not unless you include the absolute path. See my samples below.

Also, the (dot-slash) made sense to me when I've the command on the child folder tmp2 (/tmp/tmp2) and it uses (double dot-slash).

SAMPLE:

[fifiip-172-31-17-12 tmp]$ ./StackO.sh

Hello Stack Overflow

[fifi@ip-172-31-17-12 tmp]$ /tmp/StackO.sh

Hello Stack Overflow

[fifi@ip-172-31-17-12 tmp]$ mkdir tmp2

[fifi@ip-172-31-17-12 tmp]$ cd tmp2/

[fifi@ip-172-31-17-12 tmp2]$ ../StackO.sh

Hello Stack Overflow

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

If you are using ASP.NET MVC Core 3 or newer, IHostingEnvironment has been deprecated and replaced with IWebHostEnvironment

public Startup(IWebHostEnvironment webHostEnvironment)
{
    var webRootPath = webHostEnvironment.WebRootPath;
}

Phone: numeric keyboard for text input

I have found that, at least for "passcode"-like fields, doing something like <input type="tel" /> ends up producing the most authentic number-oriented field and it also has the benefit of no autoformatting. For example, in a mobile application I developed for Hilton recently, I ended up going with this:

iPhone Web Application Display with an Input Tag Having a Type of TEL which Produces a very Decent Numeric Keyboard as Opposed to Type Number which is Autoformatted and Has a Somewhat Less Intuitive Input Configuration

... and my client was very impressed.

_x000D_
_x000D_
<form>_x000D_
  <input type="tel" />_x000D_
  <button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

C#: Dynamic runtime cast

Best I got so far:

dynamic DynamicCast(object entity, Type to)
{
    var openCast = this.GetType().GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic);
    var closeCast = openCast.MakeGenericMethod(to);
    return closeCast.Invoke(entity, new[] { entity });
}
static T Cast<T>(object entity) where T : class
{
    return entity as T;
}

Tomcat base URL redirection

Name your webapp WAR “ROOT.war” or containing folder “ROOT”

Is there an equivalent method to C's scanf in Java?

You can format your output in Java as described in below code snippet.

public class TestFormat {

    public static void main(String[] args) {
      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"
   }
}

You can read more here.

batch to copy files with xcopy

You must specify your file in the copy:

xcopy C:\source\myfile.txt C:\target

Or if you want to copy all txt files for example

xcopy C:\source\*.txt C:\target

How to insert values in table with foreign key using MySQL?

Case 1

INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('dan red', 
           (SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')

it is advisable to store your values in lowercase to make retrieval easier and less error prone

Case 2

mysql docs

INSERT INTO tab_teacher (name_teacher) 
    VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('rich man', LAST_INSERT_ID())

Regular Expressions and negating a whole character group

Yes its called negative lookahead. It goes like this - (?!regex here). So abc(?!def) will match abc not followed by def. So it'll match abce, abc, abck, etc.

Similarly there is positive lookahead - (?=regex here). So abc(?=def) will match abc followed by def.

There are also negative and positive lookbehind - (?<!regex here) and (?<=regex here) respectively

One point to note is that the negative lookahead is zero-width. That is, it does not count as having taken any space.

So it may look like a(?=b)c will match "abc" but it won't. It will match 'a', then the positive lookahead with 'b' but it won't move forward into the string. Then it will try to match the 'c' with 'b' which won't work. Similarly ^a(?=b)b$ will match 'ab' and not 'abb' because the lookarounds are zero-width (in most regex implementations).

More information on this page

How to make circular background using css?

Gradients?

div {
  width: 400px; height: 400px;
  background: radial-gradient(ellipse at center,  #f73134 0%,#ff0000 47%,#ff0000 47%,#23bc2b 47%,#23bc2b 48%);
}

https://fiddle.jshell.net/su5oyd4L/

How to format LocalDate to string?

Could be short as:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

Is there a better way to compare dictionary values

If your dictionaries are deeply nested and if they contain different types of collections, you could convert them to json string and compare.

import json
match = (json.dumps(dict1) == json.dumps(dict2))

caveat- this solution may not work if your dictionaries have binary strings in the values as this is not json serializable

open a url on click of ok button in android

String url = "https://www.murait.com/";
if (url.startsWith("https://") || url.startsWith("http://")) {
    Uri uri = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}else{
    Toast.makeText(mContext, "Invalid Url", Toast.LENGTH_SHORT).show();
}

You have to check that the URL is valid or not. If URL is invalid application may crash so that you have to check URL is valid or not by this method.

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

global variable for all controller and views

In Laravel 5+, to set a variable just once and access it 'globally', I find it easiest to just add it as an attribute to the Request:

$request->attributes->add(['myVar' => $myVar]);

Then you can access it from any of your controllers using:

$myVar = $request->get('myVar');

and from any of your blades using:

{{ Request::get('myVar') }}

How can we redirect a Java program console output to multiple files?

Go to run as and choose Run Configurations -> Common and in the Standard Input and Output you can choose a File also.

Unordered List (<ul>) default indent

Most html tags have some default properties. A css reset will help you change the default properties.

What I usually do is:

{ padding: 0; margin: 0; font-face:Arial; }

Although the font is up to you!

How to compare DateTime without time via LINQ?

I found that in my case this is the only way working: (in my application I want to remove old log entries)

 var filterDate = dtRemoveLogs.SelectedDate.Value.Date;
 var loadOp = context.Load<ApplicationLog>(context.GetApplicationLogsQuery()
              .Where(l => l.DateTime.Year <= filterDate.Year
                       && l.DateTime.Month <= filterDate.Month
                       && l.DateTime.Day <= filterDate.Day));

I don't understand why the Jon's solution is not working ....

Reloading the page gives wrong GET request with AngularJS HTML5 mode

There are few things to set up so your link in the browser will look like http://yourdomain.com/path and these are your angular config + server side

1) AngularJS

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true);

2) server side, just put .htaccess inside your root folder and paste this

RewriteEngine On 
Options FollowSymLinks

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]

More interesting stuff to read about html5 mode in angularjs and the configuration required per different environment https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode Also this question might help you $location / switching between html5 and hashbang mode / link rewriting

Powershell send-mailmessage - email to multiple recipients

to send a .NET / C# powershell eMail use such a structure:

for best behaviour create a class with a method like this

 using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddCommand("Send-MailMessage")
                                  .AddParameter("SMTPServer", "smtp.xxx.com")
                                  .AddParameter("From", "[email protected]")
                                  .AddParameter("Subject", "xxx Notification")
                                  .AddParameter("Body", body_msg)
                                  .AddParameter("BodyAsHtml")
                                  .AddParameter("To", recipients);

                // invoke execution on the pipeline (ignore output) --> nothing will be displayed
                PowerShellInstance.Invoke();
            }              

Whereby these instance is called in a function like:

        public void sendEMailPowerShell(string body_msg, string[] recipients)

Never forget to use a string array for the recepients, which can be look like this:

string[] reportRecipient = { 
                        "xxx <[email protected]>",
                        "xxx <[email protected]>"
                        };

body_msg

this message can be overgiven as parameter to the method itself, HTML coding enabled!!

recipients

never forget to use a string array in case of multiple recipients, otherwise only the last address in the string will be used!!!

calling the function can look like this:

        mail reportMail = new mail(); //instantiate from class
        reportMail.sendEMailPowerShell(reportMessage, reportRecipient); //msg + email addresses

ThumbUp

How to add headers to a multicolumn listbox in an Excel userform using VBA

Simple answer: no.

What I've done in the past is load the headings into row 0 then set the ListIndex to 0 when displaying the form. This then highlights the "headings" in blue, giving the appearance of a header. The form action buttons are ignored if the ListIndex remains at zero, so these values can never be selected.

Of course, as soon as another list item is selected, the heading loses focus, but by this time their job is done.

Doing things this way also allows you to have headings that scroll horizontally, which is difficult/impossible to do with separate labels that float above the listbox. The flipside is that the headings do not remain visible if the listbox needs to scroll vertically.

Basically, it's a compromise that works in the situations I've been in.

Specify multiple attribute selectors in CSS

Simple input[name=Sex][value=M] would do pretty nice. And it's actually well-described in the standard doc:

Multiple attribute selectors can be used to refer to several attributes of an element, or even several times to the same attribute.

Here, the selector matches all SPAN elements whose "hello" attribute has exactly the value "Cleveland" and whose "goodbye" attribute has exactly the value "Columbus":

span[hello="Cleveland"][goodbye="Columbus"] { color: blue; }

As a side note, using quotation marks around an attribute value is required only if this value is not a valid identifier.

JSFiddle Demo

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

phpMyAdmin allow remote users

The other answers so far seem to advocate the complete replacement of the <Directory/> block, this is not needed and may remove extra settings like the 'AddDefaultCharset UTF-8' now included.

To allow remote access you need to add 1 line to the 2.4 config block or change 2 lines in the 2.2 (depending on your apache version):

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       #ADD following line:
       Require all granted
       Require ip 127.0.0.1
       Require ip ::1
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     #CHANGE following 2 lines:
     Order Allow,Deny
     Allow from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

Cannot drop database because it is currently in use

before dropping a database, you drop the connection to that database first.

I have found a solution at http://www.kodyaz.com/articles/kill-all-processes-of-a-database.aspx

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'YOUR_DABASE_NAME'

DECLARE @SQL varchar(max)

SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

--SELECT @SQL 
EXEC(@SQL)

How to install a plugin in Jenkins manually

Sometimes when you download plugins you may get (.zip) files then just rename with (.hpi) and then extract all the plugins and move to <jenkinsHome>/plugins/ directory.

Install a Python package into a different directory using pip?

If you are using brew with python, unfortunately, pip/pip3 ships with very limited options. You do not have --install-option, --target, --user options as mentioned above.

Note on pip install --user
The normal pip install --user is disabled for brewed Python. This is because of a bug in distutils, because Homebrew writes a distutils.cfg which sets the package prefix. A possible workaround (which puts executable scripts in ~/Library/Python/./bin) is: python -m pip install --user --install-option="--prefix=" <package-name>

You might find this line very cumbersome. I suggest use pyenv for management. If you are using

brew upgrade python python3

Ironically you are actually downgrade pip functionality.

(I post this answer, simply because pip in my mac osx does not have --target option, and I have spent hours fixing it)

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

How to urlencode a querystring in Python?

for future references (ex: for python3)

>>> import urllib.request as req
>>> query = 'eventName=theEvent&eventDescription=testDesc'
>>> req.pathname2url(query)
>>> 'eventName%3DtheEvent%26eventDescription%3DtestDesc'

Best way to check for "empty or null value"

A lot of the answers are the shortest way, not the necessarily the best way if the column has lots of nulls. Breaking the checks up allows the optimizer to evaluate the check faster as it doesn't have to do work on the other condition.

(stringexpression IS NOT NULL AND trim(stringexpression) != '')

The string comparison doesn't need to be evaluated since the first condition is false.

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Alphabet range in Python

This is the easiest way I can figure out:

#!/usr/bin/python3
for i in range(97, 123):
    print("{:c}".format(i), end='')

So, 97 to 122 are the ASCII number equivalent to 'a' to and 'z'. Notice the lowercase and the need to put 123, since it will not be included).

In print function make sure to set the {:c} (character) format, and, in this case, we want it to print it all together not even letting a new line at the end, so end=''would do the job.

The result is this: abcdefghijklmnopqrstuvwxyz

How do I auto-submit an upload form when a file is selected?

HTML

<form id="xtarget" action="upload.php">
<input type="file" id="xfilename">
</form>

JAVASCRIPT PURE

<script type="text/javascript">
window.onload = function() {
    document.getElementById("xfilename").onchange = function() {
        document.getElementById("xtarget").submit();
    }
};
</script>

phpmailer: Reply using only "Reply To" address

At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.

    $mail->ClearReplyTos();
    $mail->addReplyTo([email protected], 'EXAMPLE');

how to setup ssh keys for jenkins to publish via ssh

You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.

Step 1, generate public and private key on build server as user jenkins

build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...] 
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw-------  1 jenkins  jenkins  1679 Feb 28 11:55 id_rsa
-rw-r--r--  1 jenkins  jenkins   411 Feb 28 11:55 id_rsa.pub 
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]

Step 2, paste the pub file contents onto the target server.

target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)

Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644

Step 3, configure Jenkins

  1. In the jenkins web control panel, nagivate to "Manage Jenkins" -> "Configure System" -> "Publish over SSH"
  2. Either enter the path of the file e.g. "var/lib/jenkins/.ssh/id_rsa", or paste in the same content as on the target server.
  3. Enter your passphrase, server and user details, and you are good to go!

Root user/sudo equivalent in Cygwin?

Based on @mat-khor's answer, I took the syswin su.exe, saved it as manufacture-syswin-su.exe, and wrote this wrapper script. It handles redirection of the command's stdout and stderr, so it can be used in a pipe, etc. Also, the script exits with the status of the given command.

Limitations:

  • The syswin-su options are currently hardcoded to use the current user. Prepending env USERNAME=... to the script invocation overrides it. If other options were needed, the script would have to distinguish between syswin-su and command arguments, e.g. splitting at the first --.
  • If the UAC prompt is cancelled or declined, the script hangs.

.

#!/bin/bash
set -e

# join command $@ into a single string with quoting (required for syswin-su)
cmd=$( ( set -x; set -- "$@"; ) 2>&1 | perl -nle 'print $1 if /\bset -- (.*)/' )

tmpDir=$(mktemp -t -d -- "$(basename "$0")_$(date '+%Y%m%dT%H%M%S')_XXX")
mkfifo -- "$tmpDir/out"
mkfifo -- "$tmpDir/err"

cat >> "$tmpDir/script" <<-SCRIPT
    #!/bin/env bash
    $cmd > '$tmpDir/out' 2> '$tmpDir/err'
    echo \$? > '$tmpDir/status'
SCRIPT

chmod 700 -- "$tmpDir/script"

manufacture-syswin-su -s bash -u "$USERNAME" -m -c "cygstart --showminimized bash -c '$tmpDir/script'" > /dev/null &
cat -- "$tmpDir/err" >&2 &
cat -- "$tmpDir/out"
wait $!
exit $(<"$tmpDir/status")

simple custom event

Like has been mentioned already the progress field needs the keyword event

public event EventHandler<Progress> progress;

But I don't think that's where you actually want your event. I think you actually want the event in TestClass. How does the following look? (I've never actually tried setting up static events so I'm not sure if the following will compile or not, but I think this gives you an idea of the pattern you should be aiming for.)

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        TestClass.progress += SetStatus;
    }

    private void SetStatus(object sender, Progress e)
    {
        label1.Text = e.Status;
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
         TestClass.Func();
    }

 }

public class TestClass
{
    public static event EventHandler<Progress> progress; 

    public static void Func()
    {
        //time consuming code
        OnProgress(new Progress("current status"));
        // time consuming code
        OnProgress(new Progress("some new status"));            
    }

    private static void OnProgress(EventArgs e) 
    {
       if (progress != null)
          progress(this, e);
    }
}


public class Progress : EventArgs
{
    public string Status { get; private set; }

    private Progress() {}

    public Progress(string status)
    {
        Status = status;
    }
}

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

Could pandas use column as index?

You can change the index as explained already using set_index. You don't need to manually swap rows with columns, there is a transpose (data.T) method in pandas that does it for you:

> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                    ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> newdf = df.set_index('Locality').T
> newdf

Locality    ABBOTSFORD  ABERFELDIE
2005        427000      534000
2006        448000      600000

then you can fetch the dataframe column values and transform them to a list:

> newdf['ABBOTSFORD'].values.tolist()

[427000, 448000]

Java generics: multiple generic parameters?

You can declare multiple type variables on a type or method. For example, using type parameters on the method:

<P, Q> int f(Set<P>, Set<Q>) {
  return 0;
}

How to Round to the nearest whole number in C#

var roundedVal = Math.Round(2.5, 0);

It will give result:

var roundedVal = 3

Print range of numbers on same line

Same can be achieved by using stdout.

>>> from sys import stdout
>>> for i in range(1,11):
...     stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10 

Alternatively, same can be done by using reduce() :

>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>

Get HTML code from website in C#

Getting HTML code from a website. You can use code like this.

string urlAddress = "http://google.com";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;

  if (String.IsNullOrWhiteSpace(response.CharacterSet))
     readStream = new StreamReader(receiveStream);
  else
     readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

  string data = readStream.ReadToEnd();

  response.Close();
  readStream.Close();
}

This will give you the returned HTML code from the website. But find text via LINQ is not that easy. Perhaps it is better to use regular expression but that does not play well with HTML code

How do I prevent a Gateway Timeout with FastCGI on Nginx

In http nginx section (/etc/nginx/nginx.conf) add or modify:

keepalive_timeout 300s

In server nginx section (/etc/nginx/sites-available/your-config-file.com) add these lines:

client_max_body_size 50M;
fastcgi_buffers 8 1600k;
fastcgi_buffer_size 3200k;
fastcgi_connect_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;

In php file in the case 127.0.0.1:9000 (/etc/php/7.X/fpm/pool.d/www.conf) modify:

request_terminate_timeout = 300

I hope help you.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

Correct your Code like this:

try
{ //method try starts  
  String sql = "INSERT into TblName (col1, col2) VALUES(?, ?)";
  pStmt = obj.getConnection().prepareStatement(sql);
  pStmt.setLong(1, subscriberID);
  for (String language : additionalLangs) {
    pStmt.setInt(2, Integer.parseInt(language));
    pStmt.execute();
  }
} //method/try ends
finally
{ //finally starts
   pStmt.close()
} 

Are you sure, that you're really closing your pStatements, connections and results?

To analyze open objects you can implment a delegator pattern, which wraps code around your statemant, connection and result objects. So you'll see, if an object will successfully closed.

An Example for: pStmt = obj.getConnection().prepareStatement(sql);

    class obj{ 

    public Connection getConnection(){
    return new ConnectionDelegator(...here create your connection object and put it into ...);

    } 
}


class ConnectionDelegator implements Connection{
    Connection delegates;

    public ConnectionDelegator(Connection con){
       this.delegates = con;
    }

    public Statement prepareStatement(String sql){
        return delegates.prepareStatement(sql);
    }

    public void close(){
        try{
           delegates.close();
        }finally{
           log.debug(delegates.toString() + " was closed");
        }
    }
}

How can I parse a YAML file from a Linux shell script?

Hard to say because it depends on what you want the parser to extract from your YAML document. For simple cases, you might be able to use grep, cut, awk etc. For more complex parsing you would need to use a full-blown parsing library such as Python's PyYAML or YAML::Perl.

Submit form using AJAX and jQuery

This is what ended up working.

$("select").change(function(){
    $.get("/page.html?" + $(this).parent("form").find(":input").serialize()); 
});

Can't install via pip because of egg_info error

See this : What Python version can I use with Django?¶ https://docs.djangoproject.com/en/2.0/faq/install/

if you are using python27 you must to set django version :

try: $pip install django==1.9

Include files from parent or other directory

Here's something I wrote with that problem in mind:

<?
function absolute_include($file)
         {
         /*
         $file is the file url relative to the root of your site.
         Yourdomain.com/folder/file.inc would be passed as
         "folder/file.inc"
         */

         $folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");

         if($folder_depth == false)
            $folder_depth = 1;

         include(str_repeat("../", $folder_depth - 1) . $file);
         }
?>

hope it helps.

How to implement and do OCR in a C# project?

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
  2. Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):

Program.cs

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}

Java random number with given length

try this:

public int getRandomNumber(int min, int max) {
    return (int) Math.floor(Math.random() * (max - min + 1)) + min;
}

How to exit from the application and show the home screen?

(I tried previous answers but they lacks in some points. For example if you don't do a return; after finishing activity, remaining activity code runs. Also you need to edit onCreate with return. If you doesn't run super.onCreate() you will get a runtime error)

Say you have MainActivity and ChildActivity.

Inside ChildActivity add this:

Intent intent = new Intent(ChildActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
return true;

Inside MainActivity's onCreate add this:

@Override
public void onCreate(Bundle savedInstanceState) {

    mContext = getApplicationContext();

    super.onCreate(savedInstanceState);

    if (getIntent().getBooleanExtra("EXIT", false)) {
        finish();
        return;
    }
    // your current codes
    // your current codes
}

Run batch file from Java code

import java.lang.Runtime;

Process run = Runtime.getRuntime().exec("cmd.exe", "/c", "Start", "path of the bat file");

This will work for you and is easy to use.

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

Two options:

  • Install Oracle client on the PC you want to run your program on

  • Use Oracle.ManagedDataAccess.dll

You can get it on NuGet (search 'oracle managed') or download ODP.NET_Managed.zip (link is to a beta version, but points you in the right direction)

I use this so that the computers I deploy onto don't need Oracle client installed.

N.B. in my opinion this is good for console apps but annoying if you intend to install your application, so I install the client in that case.

How can I have a newline in a string in sh?

Disclaimer: I first wrote this and then stumbled upon this question. I thought this solution wasn't yet posted, and saw that tlwhitec did post a similar answer. Still I'm posting this because I hope it's a useful and thorough explanation.

Short answer:

This seems quite a portable solution, as it works on quite some shells (see comment).
This way you can get a real newline into a variable.

The benefit of this solution is that you don't have to use newlines in your source code, so you can indent your code any way you want, and the solution still works. This makes it robust. It's also portable.

# Robust way to put a real newline in a variable (bash, dash, ksh, zsh; indentation-resistant).
nl="$(printf '\nq')"
nl=${nl%q}

Longer answer:

Explanation of the above solution:

The newline would normally lost due to command substitution, but to prevent that, we add a 'q' and remove it afterwards. (The reason for the double quotes is explained further below.)

We can prove that the variable contains an actual newline character (0x0A):

printf '%s' "$nl" | hexdump -C
00000000  0a  |.|
00000001

(Note that the '%s' was needed, otherwise printf will translate a literal '\n' string into an actual 0x0A character, meaning we would prove nothing.)

Of course, instead of the solution proposed in this answer, one could use this as well (but...):

nl='
'

... but that's less robust and can be easily damaged by accidentally indenting the code, or by forgetting to dedent it afterwards, which makes it inconvenient to use in (indented) functions, whereas the earlier solution is robust.

Now, as for the double quotes:
The reason for the double quotes " surrounding the command substitution as in nl="$(printf '\nq')" is that you can then even prefix the variable assignment with the local keyword or builtin (such as in functions), and it will still work on all shells, whereas otherwise the dash shell would have trouble, in the sense that dash would otherwise lose the 'q' and you'd end up with an empty 'nl' variable (again, due to command substitution).
That issue is better illustrated with another example:

dash_trouble_example() {
    e=$(echo hello world) # Not using 'local'.
    echo "$e" # Fine. Outputs 'hello world' in all shells.

    local e=$(echo hello world) # But now, when using 'local' without double quotes ...:
    echo "$e" # ... oops, outputs just 'hello' in dash,
              # ... but 'hello world' in bash and zsh.

    local f="$(echo hello world)" # Finally, using 'local' and surrounding with double quotes.
    echo "$f" # Solved. Outputs 'hello world' in dash, zsh, and bash.

    # So back to our newline example, if we want to use 'local', we need
    # double quotes to surround the command substitution:
    # (If we didn't use double quotes here, then in dash the 'nl' variable
    # would be empty.)
    local nl="$(printf '\nq')"
    nl=${nl%q}
}

Practical example of the above solution:

# Parsing lines in a for loop by setting IFS to a real newline character:

nl="$(printf '\nq')"
nl=${nl%q}

IFS=$nl

for i in $(printf '%b' 'this is line 1\nthis is line 2'); do
    echo "i=$i"
done

# Desired output:
# i=this is line 1
# i=this is line 2

# Exercise:
# Try running this example without the IFS=$nl assignment, and predict the outcome.

How to set Apache Spark Executor memory

You can build command using following example

 spark-submit    --jars /usr/share/java/postgresql-jdbc.jar    --class com.examples.WordCount3  /home/vaquarkhan/spark-scala-maven-project-0.0.1-SNAPSHOT.jar --jar  --num-executors 3 --driver-memory 10g **--executor-memory 10g** --executor-cores 1  --master local --deploy-mode client  --name wordcount3 --conf "spark.app.id=wordcount" 

How to get a list of images on docker registry v2

This threads dates back a long time, the most recents tools that one should consider are skopeo and crane.

skopeo supports signing and has many other features, while crane is a bit more minimalistic and I found it easier to integrate with in a simple shell script.

What does `m_` variable prefix mean?

The m_ prefix is often used for member variables - I think its main advantage is that it helps create a clear distinction between a public property and the private member variable backing it:

int m_something

public int Something => this.m_something; 

It can help to have a consistent naming convention for backing variables, and the m_ prefix is one way of doing that - one that works in case-insensitive languages.

How useful this is depends on the languages and the tools that you're using. Modern IDEs with strong refactor tools and intellisense have less need for conventions like this, and it's certainly not the only way of doing this, but it's worth being aware of the practice in any case.

node.js: cannot find module 'request'

I was running into the same problem, here is how I got it working..

open terminal:

mkdir testExpress
cd testExpress
npm install request

or

sudo npm install -g request // If you would like to globally install.

now don't use

node app.js or node test.js, you will run into this problem doing so. You can also print the problem that is being cause by using this command.. "node -p app.js"

The above command to start nodeJs has been deprecated. Instead use

npm start

You should see this..

[email protected] start /Users/{username}/testExpress
node ./bin/www

Open your web browser and check for localhost:3000

You should see Express install (Welcome to Express)

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

How to sort by Date with DataTables jquery plugin?

You should make use of the HTML5 Data Attributes. https://www.datatables.net/examples/advanced_init/html5-data-attributes.html

Just add the data-order element to your td element.
No plugins required.

<table class="table" id="exampleTable">
    <thead>
        <tr>
            <th>Firstname</th>
            <th>Sign Up Date</th>
        </tr>
    </thead>

    <tbody>

        <tr>
            <td>Peter</td>
            <td data-order="2015-11-13 12:00">13. November 2015</td>
        </tr>
        <tr>
            <td>Daniel</td>
            <td data-order="2015-08-06 13:44">06. August 2015</td>
        </tr>
        <tr>
            <td>Michael</td>
            <td data-order="2015-10-14 16:12">14. October 2015</td>
        </tr>
    </tbody>
</table>


<script>
    $(document).ready(function() {
        $('#exampleTable').DataTable();
    });
</script>

Difference between innerText, innerHTML and value?

to add to the list, innerText will keep your text-transform, innerHTML wont

How to get current PHP page name

In your case you can use __FILE__ variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php

Android Overriding onBackPressed()

Yes. Only override it in that one Activity with

@Override
public void onBackPressed()
{
     // code here to show dialog
     super.onBackPressed();  // optional depending on your needs
}

don't put this code in any other Activity

Permission to write to the SD card

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory();

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

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

Difference between string and text in rails?

Use string for shorter field, like names, address, phone, company

Use Text for larger content, comments, content, paragraphs.

My general rule, if it's something that is more than one line, I typically go for text, if it's a short 2-6 words, I go for string.

The official rule is 255 for a string. So, if your string is more than 255 characters, go for text.

Invalid length parameter passed to the LEFT or SUBSTRING function

Something else you can use is isnull:

isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)

Inline comments for Bash?

$(: ...) is a little less ugly, but still not good.

Compare two date formats in javascript/jquery

To comapre dates of string format (mm-dd-yyyy).

    var job_start_date = "10-1-2014"; // Oct 1, 2014
    var job_end_date = "11-1-2014"; // Nov 1, 2014
    job_start_date = job_start_date.split('-');
    job_end_date = job_end_date.split('-');

    var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
    var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);

    if(new_end_date <= new_start_date) {
      // your code
    }

Common elements comparison between 2 lists

Use a generator:

common = (x for x in list1 if x in list2)

The advantage here is that this will return in constant time (nearly instant) even when using huge lists or other huge iterables.

For example,

list1 =  list(range(0,10000000))
list2=list(range(1000,20000000))
common = (x for x in list1 if x in list2)

All other answers here will take a very long time with these values for list1 and list2.

You can then iterate the answer with

for i in common: print(i)

Or convert it to a list with

list(i)

Java Reflection: How to get the name of a variable?

All you need to do is make an array of fields and then set it to the class you want like shown below.

Field fld[] = (class name).class.getDeclaredFields();   
for(Field x : fld)
{System.out.println(x);}

For example if you did

Field fld[] = Integer.class.getDeclaredFields();
          for(Field x : fld)
          {System.out.println(x);}

you would get

public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
static final char[] java.lang.Integer.digits
static final char[] java.lang.Integer.DigitTens
static final char[] java.lang.Integer.DigitOnes
static final int[] java.lang.Integer.sizeTable
private static java.lang.String java.lang.Integer.integerCacheHighPropValue
private final int java.lang.Integer.value
public static final int java.lang.Integer.SIZE
private static final long java.lang.Integer.serialVersionUID

Open window in JavaScript with HTML inserted

You can use window.open to open a new window/tab(according to browser setting) in javascript.

By using document.write you can write HTML content to the opened window.

Multipart forms from C# client

In the version of .NET I am using you also have to do this:

System.Net.ServicePointManager.Expect100Continue = false;

If you don't, the HttpWebRequest class will automatically add the Expect:100-continue request header which fouls everything up.

Also I learned the hard way that you have to have the right number of dashes. whatever you say is the "boundary" in the Content-Type header has to be preceded by two dashes

--THEBOUNDARY

and at the end

--THEBOUNDARY--

exactly as it does in the example code. If your boundary is a lot of dashes followed by a number then this mistake won't be obvious by looking at the http request in a proxy server

How to maintain aspect ratio using HTML IMG tag

The poster is showing a dimension constrained by height in most cases he posted >>> (256x256, 1024x768, 500x400, 205x246, etc.) but fitting a 64px max height pixel dimension, typical of most landscape "photos". So my guess is he wants an image that is always 64 pixels in height. To achieve that, do the following:

<img id="photo1" style="height:64px;width:auto;" src="photo.jpg" height="64" />

This solution guarantees the images are all 64 pixels max in height and allows width to extend or shrink based on each image's aspect ratio. Setting height to 64 in the img height attribute reserves a space in the browser's Rendertree layout as images download, so the content doesn't shift waiting for images to download. Also, the new HTML5 standard does not always honor width and height attributes. They are dimensional "hints" only, not final dimensions of the image. If in your style sheet you reset or change the image height and width, the actual values in the images attributes get reset to either your CSS value or the images native default dimensions. Setting the CSS height to "64px" and the width to "auto" forces width to start with the native image width (not image attribute width) and then calculate a new aspect-ratio using the CSS style for height. That gets you a new width. So the height and width "img" attributes are really not needed here and just force the browser to do extra calculations.

How do I read the first line of a file using cat?

Adding one more obnoxious alternative to the list:

perl -pe'$.<=1||last' file
# or 
perl -pe'$.<=1||last' < file
# or
cat file | perl -pe'$.<=1||last'

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

[HttpPost] 
public ActionResult SubmitAction(FormCollection collection)
{
     // Get Post Params Here
 string var1 = collection["var1"];
}

You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

//Defined in another file
class MyForm
{
  public string var1 { get; set; }
}

[HttpPost]
public ActionResult SubmitAction(MyForm form)
{      
  string var1 = form1.Var1;
}

How to hide column of DataGridView when using custom DataSource?

Set that particular column's Visible property = false

dataGridView[ColumnName or Index].Visible = false;

Edit sorry missed the Columns Property dataGridView.Columns[ColumnName or Index].Visible = false;

Add a list item through javascript

If you want to create a li element for each input/name, then you have to create it, with document.createElement [MDN].

Give the list the ID:

<ol id="demo"></ol>

and get a reference to it:

var list = document.getElementById('demo');

In your event handler, create a new list element with the input value as content and append to the list with Node.appendChild [MDN]:

var firstname = document.getElementById('firstname').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);

DEMO

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

You are probably targeting a server without built-in JSTL support (e.g. some version of Tomcat.) You will need to provision your own JSTL tag library.

Call PHP function from jQuery?

This is exactly what ajax is for. See here:

http://api.jquery.com/load/

Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.

$('#result').load('ajax/test.php');

Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).

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

Tnx @Raj_89 , Your trick was very good , can be better , only by use extra style , that make it on other dom objects , exactly like a common select option tag in html ...

select{
 position:absolute;
}

u can see result here : http://jsfiddle.net/aTzc2/

git-upload-pack: command not found, when cloning remote Git repo

Matt's solution didn't work for me on OS X, but Paul's did.

The short version from Paul's link is:

Created /usr/local/bin/ssh_session with the following text:

#!/bin/bash
export SSH_SESSION=1
if [ -z "$SSH_ORIGINAL_COMMAND" ] ; then
    export SSH_LOGIN=1
    exec login -fp "$USER"
else
    export SSH_LOGIN=
    [ -r /etc/profile ] && source /etc/profile
    [ -r ~/.profile ] && source ~/.profile
    eval exec "$SSH_ORIGINAL_COMMAND"
fi

Execute:

chmod +x /usr/local/bin/ssh_session

Add the following to /etc/sshd_config:

ForceCommand /usr/local/bin/ssh_session