Programs & Examples On #Wpftoolkit

The WPF Toolkit is a collection of WPF features and components that are being made available outside of the normal .NET Framework ship cycle. The WPF Toolkit not only allows users to get new functionality more quickly, but allows an efficient means for giving feedback to the product team.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

It took me ages to work this one out, so for the benefit of searchers:

I had a bizarre issue whereby the application worked in debug, but gave the XamlParseException once released.

After fixing the x86/x64 issue as detailed by Katjoek, the issue remained.

The issue was that a CEF tutorial said to bring down System.Windows.Interactivity from NuGet (even thought it's in the Extensions section of references in .NET) and bringing down from NuGet sets specific version to true.

Once deployed, a different version of System.Windows.Interactivity was being packed by a different application.

It's refusal to use a different version of the dll caused the whole application to crash with XamlParseException.

"ssl module in Python is not available" when installing package with pip3

I had the same issue trying to install python3.7 on an ubuntu14.04 machine. The issue was that I had some custom folders in my PKG_CONFIG_PATH and in my LD_LIBRARY_PATH, which prevented the python build process to find the system openssl libraries.

so try to clear them and see what happens:

export PKG_CONFIG_PATH=""
export LD_LIBRARY_PATH=""

Executing multi-line statements in the one-line command-line?

The problem is not with the import statement. The problem is that the control flow statements don't work inlined in a python command. Replace that import statement with any other statement and you'll see the same problem.

Think about it: python can't possibly inline everything. It uses indentation to group control-flow.

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

You have to add

<script>jQuery.noConflict();</script>

after

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Transpose a matrix in Python

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Angular 4.3 - HttpClient set params

My helper class (ts) to convert any complex dto object (not only "string dictionary") to HttpParams:

import { HttpParams } from "@angular/common/http";

export class HttpHelper {
  static toHttpParams(obj: any): HttpParams {
    return this.addToHttpParams(new HttpParams(), obj, null);
  }

  private static addToHttpParams(params: HttpParams, obj: any, prefix: string): HttpParams {    
    for (const p in obj) {
      if (obj.hasOwnProperty(p)) {
        var k = p;
        if (prefix) {
          if (p.match(/^-{0,1}\d+$/)) {
            k = prefix + "[" + p + "]";
          } else {
            k = prefix + "." + p;
          }
        }        
        var v = obj[p];
        if (v !== null && typeof v === "object" && !(v instanceof Date)) {
          params = this.addToHttpParams(params, v, k);
        } else if (v !== undefined) {
          if (v instanceof Date) {
            params = params.set(k, (v as Date).toISOString()); //serialize date as you want
          }
          else {
            params = params.set(k, v);
          }

        }
      }
    }
    return params;
  }
}

console.info(
  HttpHelper.toHttpParams({
    id: 10,
    date: new Date(),
    states: [1, 3],
    child: {
      code: "111"
    }
  }).toString()
); // id=10&date=2019-08-02T13:19:09.014Z&states%5B0%5D=1&states%5B1%5D=3&child.code=111

How do I change JPanel inside a JFrame on the fly?

On the user action:

// you have to do something along the lines of

myJFrame.getContentPane().removeAll()
myJFrame.getContentPane().invalidate()

myJFrame.getContentPane().add(newContentPanel)
myJFrame.getContentPane().revalidate()

Then you can resize your wndow as needed.

Open CSV file via VBA (performance)

This may help you, also it depends how your CSV file is formated.

  1. Open your excel sheet & go to menu Data > Import External Data > Import Data.
  2. Choose your CSV file.
  3. Original data type: choose Fixed width, then Next.
  4. It will autmaticall delimit your columns. then, you may check the splitted columns in Data preview panel.
  5. Then Finish & see.

Note: you may also go with Delimited as Original data type. In that case, you need to key-in your delimiting character.

HTH!

How do I convert a TimeSpan to a formatted string?

This is the shortest solution.

timeSpan.ToString(@"hh\:mm");

How to create cron job using PHP?

In the same way you are trying to run cron.php, you can run another PHP script. You will have to do so via the CLI interface though.

#!/usr/bin/env php
<?php
# This file would be say, '/usr/local/bin/run.php'
// code
echo "this was run from CRON";

Then, add an entry to the crontab:

* * * * * /usr/bin/php -f /usr/local/bin/run.php &> /dev/null

If the run.php script had executable permissions, it could be listed directly in the crontab, without the /usr/bin/php part as well. The 'env php' part, in the script, would find the appropriate program to actually run the PHP code. So, for the 'executable' version - add executable permission to the file:

chmod +x /usr/local/bin/run.php

and then, add the following entry into crontab:

* * * * * /usr/local/bin/run.php &> /dev/null

SQL Server 2008: How to query all databases sizes?

please find more deatils or download the script from below link https://gallery.technet.microsoft.com/SIZE-OF-ALL-DATABASES-IN-0337f6d5#content

 DECLARE @spacetable table
 (
 database_name varchar(50) ,
 total_size_data int,
 space_util_data int,
 space_data_left int,
 percent_fill_data float,
 total_size_data_log int,
 space_util_log int,
 space_log_left int,
 percent_fill_log char(50),
 [total db size] int,
 [total size used] int,
 [total size left] int
 )
 insert into  @spacetable
 EXECUTE master.sys.sp_MSforeachdb 'USE [?];
 select x.[DATABASE NAME],x.[total size data],x.[space util],x.[total size data]-x.[space util] [space left data],
 x.[percent fill],y.[total size log],y.[space util],
 y.[total size log]-y.[space util] [space left log],y.[percent fill],
 y.[total size log]+x.[total size data] ''total db size''
 ,x.[space util]+y.[space util] ''total size used'',
 (y.[total size log]+x.[total size data])-(y.[space util]+x.[space util]) ''total size left''
  from (select DB_NAME() ''DATABASE NAME'',
 sum(size*8/1024) ''total size data'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
 ,case when sum(size*8/1024)=0 then ''less than 1% used'' else
 substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
 from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=0
 group by type_desc  ) as x ,
 (select 
 sum(size*8/1024) ''total size log'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
 ,case when sum(size*8/1024)=0 then ''less than 1% used'' else
 substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
 from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=1
 group by type_desc  )y'
 select * from @spacetable
 order by database_name

Pandas get the most frequent values of a column

You could try argmax like this:

dataframe['name'].value_counts().argmax() Out[13]: 'alex'

The value_counts will return a count object of pandas.core.series.Series and argmax could be used to achieve the key of max values.

Default argument values in JavaScript functions

You cannot add default values for function parameters. But you can do this:

function tester(paramA, paramB){
 if (typeof paramA == "undefined"){
   paramA = defaultValue;
 }
 if (typeof paramB == "undefined"){
   paramB = defaultValue;
 }
}

JavaScript click event listener on class

With modern JavaScript it can be done like this:

_x000D_
_x000D_
const divs = document.querySelectorAll('.a');

divs.forEach(el => el.addEventListener('click', event => {
  console.log(event.target.getAttribute("data-el"));
}));
_x000D_
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example</title>
  <style>
    .a {
      background-color:red;
      height: 33px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      cursor: pointer;
    }
    
    .b {
      background-color:#00AA00;
      height: 50px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div class="a" data-el="1">1</div>
  <div class="b" data-el="no-click-handler">2</div>
  <div class="a" data-el="3">11</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

  1. Gets all elements by class name
  2. Loops over all elements with using forEach
  3. Attach an event listener on each element
  4. Uses event.target to retrieve more information for specific element

How to base64 encode image in linux bash / shell

You need to use cat to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.

test="$(cat DSC_0251.JPG | base64)"

However, base64 can read from the file itself:

test=$( base64 DSC_0251.JPG )

Dart SDK is not configured

Run this command:

$ echo "$(dirname $(which flutter))/cache/dart-sdk"

You'll get something like:

/home/lex/opt/flutter/bin/cache/dart-sdk

Enter that value as your Dart SDK path.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Deny all, allow only one IP through htaccess

Slightly modified version of the above, including a custom page to be displayed to those who get denied access:

ErrorDocument 403 /specific_page.html
order deny,allow
deny from all
allow from 111.222.333.444

...and that way those requests not coming from 111.222.333.444 will see specific_page.html

(posting this as comment looked terrible because new lines get lost)

Best practices for catching and re-throwing .NET exceptions

When you throw ex, you're essentially throwing a new exception, and will miss out on the original stack trace information. throw is the preferred method.

Firebug like plugin for Safari browser

Why do you want to use Firebug if Safari already comes with great Developer tools? :)

As Matt said, you can enable them from the preferences menu.

Here you will find an overview, summarized, of the Safari's Web inspector, and how to use it:

With block equivalent in C#?

About 3/4 down the page in the "Using Objects" section:

VB:

With hero 
  .Name = "SpamMan" 
  .PowerLevel = 3 
End With 

C#:

//No "With" construct
hero.Name = "SpamMan"; 
hero.PowerLevel = 3; 

How do I get the current date in JavaScript?

Use new Date() to generate a new Date object containing the current date and time.

_x000D_
_x000D_
var today = new Date();_x000D_
var dd = String(today.getDate()).padStart(2, '0');_x000D_
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!_x000D_
var yyyy = today.getFullYear();_x000D_
_x000D_
today = mm + '/' + dd + '/' + yyyy;_x000D_
document.write(today);
_x000D_
_x000D_
_x000D_

This will give you today's date in the format of mm/dd/yyyy.

Simply change today = mm +'/'+ dd +'/'+ yyyy; to whatever format you wish.

Replace transparency in PNG images with white background

It's -alpha off, NOT -alpha remove! iOS app store upload fails when there is an alpha channel in any icon!!

Here's how to do it: mogrify -alpha off *.png

How do I create an abstract base class in JavaScript?

I think All Those answers specially first two (by some and jordão) answer the question clearly with conventional prototype base JS concept.
Now as you want the animal class constructor to behave according to the passed parameter to the construction, I think this is very much similar to basic behavior of Creational Patterns for example Factory Pattern.

Here i made a little approach to make it work that way.

var Animal = function(type) {
    this.type=type;
    if(type=='dog')
    {
        return new Dog();
    }
    else if(type=="cat")
    {
        return new Cat();
    }
};



Animal.prototype.whoAreYou=function()
{
    console.log("I am a "+this.type);
}

Animal.prototype.say = function(){
    console.log("Not implemented");
};




var Cat =function () {
    Animal.call(this);
    this.type="cat";
};

Cat.prototype=Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

Cat.prototype.say=function()
{
    console.log("meow");
}



var Dog =function () {
    Animal.call(this);
    this.type="dog";
};

Dog.prototype=Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.say=function()
{
    console.log("bark");
}


var animal=new Animal();


var dog = new Animal('dog');
var cat=new Animal('cat');

animal.whoAreYou(); //I am a undefined
animal.say(); //Not implemented


dog.whoAreYou(); //I am a dog
dog.say(); //bark

cat.whoAreYou(); //I am a cat
cat.say(); //meow

Combine two arrays

Just use:

$output = array_merge($array1, $array2);

That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite proceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.

Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...

A workaround is to recreate the keys.

$output = array_combine($output, $output);

Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)

$output = $array1 + $array2;

All of this can be seen in: http://php.net/manual/en/function.array-merge.php

How can I get the class name from a C++ object?

To get class name without mangling stuff you can use func macro in constructor:

class MyClass {
    const char* name;
    MyClass() {
        name = __func__;
    }
}

docker command not found even though installed with apt-get

sudo apt-get install docker # DO NOT do this

is a different library on ubuntu.

Use sudo apt-get install docker-ce to install the correct docker.

Laravel Unknown Column 'updated_at'

In the model, write the below code;

public $timestamps = false;

This would work.

Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.

How to randomize two ArrayLists in the same fashion?

You could do this with maps:

Map<String, String> fileToImg:
List<String> fileList = new ArrayList(fileToImg.keySet());
Collections.shuffle(fileList);
for(String item: fileList) {
    fileToImf.get(item);
}

This will iterate through the images in the random order.

Is it better to return null or empty collection?

Empty Collection. If you're using C#, the assumption is that maximizing system resources is not essential. While less efficient, returning Empty Collection is much more convenient for the programmers involved (for the reason Will outlined above).

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

I had the same issue because the XML file I was uploading was encoded using UTF-8-BOM (UTF-8 byte-order mark).

Switched the encoding to UTF-8 in Notepad++ and was able to load the XML file in code.

How to change a TextView's style at runtime

TextView tvCompany = (TextView)findViewById(R.layout.tvCompany);
tvCompany.setTypeface(null,Typeface.BOLD);

You an set it from code. Typeface

Merging Cells in Excel using C#

Using the Interop you get a range of cells and call the .Merge() method on that range.

eWSheet.Range[eWSheet.Cells[1, 1], eWSheet.Cells[4, 1]].Merge();

How to bind DataTable to Datagrid

In cs file

DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;

In xaml file

<DataGrid Name="gridEmployees" ItemsSource="{Binding}">

Does React Native styles support gradients?

React Native hasn't provided the gradient color yet. But still, you can do it with a nmp package called react-native-linear-gradient or you can click here for more info

  1. npm install react-native-linear-gradient --save
  2. use import LinearGradient from 'react-native-linear-gradient'; in your application file
  3.         <LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']}>
              <Text>
                Your Text Here
              </Text>
            </LinearGradient> 

SQL Server Creating a temp table for this query

If you want to just create a temp table inside the query that will allow you to do something with the results that you deposit into it you can do something like the following:

DECLARE @T1 TABLE (
Item 1 VARCHAR(200)
, Item 2 VARCHAR(200)
, ...
, Item n VARCHAR(500)
)

On the top of your query and then do an

INSERT INTO @T1
SELECT
FROM
(...)

List of all users that can connect via SSH

Any user with a valid shell in /etc/passwd can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.

To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.

How to stop a vb script running in windows

Start Task Manager, click on the Processes tab, right-click on wscript.exe and select End Process, and confirm in the dialog that follows. This will terminate the wscript.exe that is executing your script.

htaccess redirect all pages to single page

This will direct everything from the old host to the root of the new host:

RewriteEngine on
RewriteCond %{http_host} ^www.old.com [NC,OR]
RewriteCond %{http_host} ^old.com [NC]
RewriteRule ^(.*)$ http://www.thenewdomain.org/ [R=301,NC,L]

Display all dataframe columns in a Jupyter Python Notebook

If you want to show all the rows set like bellow

pd.options.display.max_rows = None

If you want to show all columns set like bellow

pd.options.display.max_columns = None

Oracle TNS names not showing when adding new connection to SQL Developer

In Sql Developer, navidate to Tools->preferences->Datababae->advanced->Set Tnsname directory to the directory containing tnsnames.ora

How do I launch a Git Bash window with particular working directory using a script?

Windows 10

This is basically @lengxuehx's answer, but updated for Win 10, and it assumes your bash installation is from Git Bash for Windows from git's official downloads.

cmd /c (start /b "%cd%" "C:\Program Files\GitW\git-bash.exe") && exit

I ended up using this after I lost my context-menu items for Git Bash as my command to run from the registry settings. In case you're curious about that, I did this:

  1. Create a new key called Bash in the shell key at HKEY_CLASSES_ROOT\Directory\Background\shell
  2. Add a string value to Icon (not a new key!) that is the full path to your git-bash.exe, including the git-bash.exe part. You might need to wrap this in quotes.
  3. Edit the default value of Bash to the text you want to use in the context menu enter image description here
  4. Add a sub-key to Bash called command
  5. Modify command's default value to cmd /c (start /b "%cd%" "C:\Program Files\GitW\git-bash.exe") && exit enter image description here

Then you should be able to close the registry and start using Git Bash from anywhere that's a real directory. For example, This PC is not a real directory.

enter image description here

How do you reindex an array in PHP but with indexes starting from 1?

A more elegant solution:

$list = array_combine(range(1, count($list)), array_values($list));

Deleting all files in a directory with Python

Use os.chdir to change directory . Use glob.glob to generate a list of file names which end it '.bak'. The elements of the list are just strings.

Then you could use os.unlink to remove the files. (PS. os.unlink and os.remove are synonyms for the same function.)

#!/usr/bin/env python
import glob
import os
directory='/path/to/dir'
os.chdir(directory)
files=glob.glob('*.bak')
for filename in files:
    os.unlink(filename)

CSS height 100% percent not working

Night's answer is correct

 html, body {margin:0;padding:0;height:100%;}

Also check that your div or element is NOT inside another one (with height less than 100%) Hope this helps someone else.

Maximize a window programmatically and prevent the user from changing the windows state

When I do this, I get a very small square screen instead of a maxed screen. Yet, when I only use the FormWindowState.Maximized, it does give me a full screen. Why is that?

        public partial class Testscherm : Form
    {
            public Testscherm()

            {

                    this.WindowState = FormWindowState.Maximized;
                    this.MaximizeBox = false;
                    this.MinimizeBox = false;
                    this.MinimumSize = this.Size;
                    this.MaximumSize = this.Size;
                    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                    InitializeComponent();


            }

ORA-30926: unable to get a stable set of rows in the source tables

This is usually caused by duplicates in the query specified in USING clause. This probably means that TABLE_A is a parent table and the same ROWID is returned several times.

You could quickly solve the problem by using a DISTINCT in your query (in fact, if 'Y' is a constant value you don't even need to put it in the query).

Assuming your query is correct (don't know your tables) you could do something like this:

  MERGE INTO table_1 a
      USING 
      (SELECT distinct ta.ROWID row_id
              FROM table_1 a ,table_2 b ,table_3 c
              WHERE a.mbr = c.mbr
              AND b.head = c.head
              AND b.type_of_action <> '6') src
              ON ( a.ROWID = src.row_id )
  WHEN MATCHED THEN UPDATE SET in_correct = 'Y';

Ping all addresses in network, windows

for /l %%a in (254, -1, 1) do ( 
    for /l %%b in (1, 1, 254) do (
        for %%c in (20, 168) do (
            for %%e in (172, 192) do (
                ping /n 1 %%e.%%c.%%b.%%a>>ping.txt
            )
        )
    )
)
pause>nul

Does Python have a ternary conditional operator?

a if condition else b

Just memorize this pyramid if you have trouble remembering:

     condition
  if           else
a                   b 

return in for loop or outside loop

The code is valid (i.e, will compile and execute) in both cases.

One of my lecturers at Uni told us that it is not desirable to have continue, return statements in any loop - for or while. The reason for this is that when examining the code, it is not not immediately clear whether the full length of the loop will be executed or the return or continue will take effect.

See Why is continue inside a loop a bad idea? for an example.

The key point to keep in mind is that for simple scenarios like this it doesn't (IMO) matter but when you have complex logic determining the return value, the code is 'generally' more readable if you have a single return statement instead of several.

With regards to the Garbage Collection - I have no idea why this would be an issue.

How to select the first element with a specific attribute using XPath

for ex.

<input b="demo">

And

(input[@b='demo'])[1]

sql try/catch rollback/commit - preventing erroneous commit after rollback

In your first example, you are correct. The batch will hit the commit transaction, regardless of whether the try block fires.

In your second example, I agree with other commenters. Using the success flag is unnecessary.

I consider the following approach to be, essentially, a light weight best practice approach.

If you want to see how it handles an exception, change the value on the second insert from 255 to 256.

CREATE TABLE #TEMP ( ID TINYINT NOT NULL );
INSERT  INTO #TEMP( ID ) VALUES  ( 1 )

BEGIN TRY
    BEGIN TRANSACTION

    INSERT  INTO #TEMP( ID ) VALUES  ( 2 )
    INSERT  INTO #TEMP( ID ) VALUES  ( 255 )

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    DECLARE 
        @ErrorMessage NVARCHAR(4000),
        @ErrorSeverity INT,
        @ErrorState INT;
    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();
    RAISERROR (
        @ErrorMessage,
        @ErrorSeverity,
        @ErrorState    
        );
    ROLLBACK TRANSACTION
END CATCH

SET NOCOUNT ON

SELECT ID
FROM #TEMP

DROP TABLE #TEMP

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Here is the ng repeat with ng click function and to append with slider

<script>
var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope) {
        $scope.employees = [
            { 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
            { 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
            { 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
            { 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
            { 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
        ]

            //This will hide the DIV by default.
                $scope.IsVisible = false;
            $scope.ShowHide = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsVisible = $scope.IsVisible ? false : true;
            }
        });
</script>
</head>

<body>

<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
                    <div class="MS-content">
                        <div class="item"  ng-repeat="emps in employees"  ng-show = "IsVisible">
                          <div class="subitem">
        <p>{{emps.id}}</p>
        <p>{{emps.name}}</p>
        <p>{{emps.age}}</p>
        </div>
                        </div>


                    </div>
                    <div class="MS-controls">
                        <button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
                        <button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
                    </div>
                </div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
<script src="js/multislider.js"></script> 
<script>

        $('#mixedSlider').multislider({
            duration: 750,
            interval: false
        });
</script>

Test if characters are in a string

You can use grep

grep("es", "Test")
[1] 1
grep("et", "Test")
integer(0)

Difference between using Throwable and Exception in a try catch

By catching Throwable it includes things that subclass Error. You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong. It would be more typical in a framework type application (for example an application server or a testing framework) where it can be running unknown code and should not be affected by anything that goes wrong with that code, as much as possible.

Java Returning method which returns arraylist?

If Foo is the class enclose this method

class Foo{
  public ArrayList<Integer> myNumbers()    {
     //code code code
  }
}

then

new Foo().myNumbers();

How to write a simple Html.DropDownListFor()?

@using (Html.BeginForm()) {
    <p>Do you like pizza?
        @Html.DropDownListFor(x => x.likesPizza, new[] {
            new SelectListItem() {Text = "Yes", Value = bool.TrueString},
            new SelectListItem() {Text = "No", Value = bool.FalseString}
        }, "Choose an option") 
    </p>
    <input type = "submit" value = "Submit my answer" />
} 

I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.

Some notes for beginners:

  • Don't worry about what 'x' is called - it is created here, for the first time, and doesn't link to anything else anywhere else in the MVC app, so you can call it what you want - 'x', 'model', 'm' etc.
  • The placeholder that users will see in the dropdown list is "Choose an option", so you can change this if you want.
  • There's a bit of text preceding the drop down which says "Do you like pizza?"
  • This should be complete text for a form, including a submit button, I think

Hope this helps someone,

Laravel - Route::resource vs Route::controller

For route controller method we have to define only one route. In get or post method we have to define the route separately.

And the resources method is used to creates multiple routes to handle a variety of Restful actions.

Here the Laravel documentation about this.

Replace new lines with a comma delimiter with Notepad++?

fapDaddy's answer using a macro pointed me in the right direction.

Here's precisely what worked for me.

  1. Place the cursor after the first data item. enter image description here

  2. Click 'Macro > Start Recording' in the menu. enter image description here

  3. Type this sequence: Comma, Space, Delete, End. enter image description here

  4. Click 'Macro > Stop recording' in the menu. enter image description here

  5. Click 'Macro > Run a Macro Multiple Times...' in the menu. enter image description here

  6. Click 'Run until the end of file' and click 'Run'. enter image description here

  7. Remove any trailing characters. enter image description here

  8. Done!

enter image description here

What is the best way to give a C# auto-property an initial value?

In addition to the answer already accepted, for the scenario when you want to define a default property as a function of other properties you can use expression body notation on C#6.0 (and higher) for even more elegant and concise constructs like:

public class Person{

    public string FullName  => $"{First} {Last}"; // expression body notation

    public string First { get; set; } = "First";
    public string Last { get; set; } = "Last";
}

You can use the above in the following fashion

    var p = new Person();

    p.FullName; // First Last

    p.First = "Jon";
    p.Last = "Snow";

    p.FullName; // Jon Snow

In order to be able to use the above "=>" notation, the property must be read only, and you do not use the get accessor keyword.

Details on MSDN

Fastest way to count exact number of rows in a very large table?

Is there a better way to get the EXACT count of the number of rows of a table?

To answer your question simply, No.

If you need a DBMS independent way of doing this, the fastest way will always be:

SELECT COUNT(*) FROM TableName

Some DBMS vendors may have quicker ways which will work for their systems only. Some of these options are already posted in other answers.

COUNT(*) should be optimized by the DBMS (at least any PROD worthy DB) anyway, so don't try to bypass their optimizations.

On a side note:
I am sure many of your other queries also take a long time to finish because of your table size. Any performance concerns should probably be addressed by thinking about your schema design with speed in mind. I realize you said that it is not an option to change but it might turn out that 10+ minute queries aren't an option either. 3rd NF is not always the best approach when you need speed, and sometimes data can be partitioned in several tables if the records don't have to be stored together. Something to think about...

Temporary tables in stored procedures

Use @temp tables whenever possible--that is, you only need one primary key and you do not need to access the data from a subordinate stored proc.

Use #temp tables if you need to access the data from a subordinate stored proc (it is an evil global variable to the stored proc call chain) and you have no other clean way to pass the data between stored procs. Also use it if you need a secondary index (although, really ask yourself if it is a #temp table if you need more than one index)

If you do this, always declare your #temp table at the top of the function. SQL will force a recompile of your stored proc when it sees the create table statement....so if you have the #temp table declaration in the middle of the stored proc, you stored proc must stop processing and recompile.

JPA and Hibernate - Criteria vs. JPQL or HQL

I mostly prefer Criteria Queries for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.

On the other hand I'm using HQL for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a bit more powerful, I think, e.g. for different join types.

Find element's index in pandas Series

If you use numpy, you can get an array of the indecies that your value is found:

import numpy as np
import pandas as pd
myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
np.where(myseries == 7)

This returns a one element tuple containing an array of the indecies where 7 is the value in myseries:

(array([3], dtype=int64),)

Drawing an SVG file on a HTML5 canvas

EDIT Dec 16th, 2019

Path2D is supported by all major browsers now

EDIT November 5th, 2014

You can now use ctx.drawImage to draw HTMLImageElements that have a .svg source in some but not all browsers. Chrome, IE11, and Safari work, Firefox works with some bugs (but nightly has fixed them).

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";

Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg> element inserted into the DOM for reference.

You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:

var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);

Live example of that here.


Old posterity answer:

There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.

I'd suggest looking in to canvg:

http://code.google.com/p/canvg/

http://canvg.googlecode.com/svn/trunk/examples/index.htm

When to use DataContract and DataMember attributes?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Many .NET Framework types also have existing data contracts.

You can find the full article here.

How can I create a product key for my C# application?

There are some tools and API's available for it. However, I do not think you'll find one for free ;)

There is for instance the OLicense suite: http://www.olicense.de/index.php?lang=en

Configuring ObjectMapper in Spring

SOLUTION 1

First working solution (tested) useful especially when using @EnableWebMvc:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this won't add a 2nd MappingJackson2HttpMessageConverter 
        // as the SOLUTION 2 is doing but also might seem complicated
        converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> {
            // check default included objectMapper._registeredModuleTypes,
            // e.g. Jdk8Module, JavaTimeModule when creating the ObjectMapper
            // without Jackson2ObjectMapperBuilder
            ((MappingJackson2HttpMessageConverter) c).setObjectMapper(this.objectMapper);
        });
    }

SOLUTION 2

Of course the common approach below works too (also working with @EnableWebMvc):

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this will add a 2nd MappingJackson2HttpMessageConverter 
        // (additional to the default one) but will work and you 
        // won't lose the default converters as you'll do when overwriting
        // configureMessageConverters(List<HttpMessageConverter<?>> converters)
        // 
        // you still have to check default included
        // objectMapper._registeredModuleTypes, e.g.
        // Jdk8Module, JavaTimeModule when creating the ObjectMapper
        // without Jackson2ObjectMapperBuilder
        converters.add(new MappingJackson2HttpMessageConverter(this.objectMapper));
    }

Why @EnableWebMvc usage is a problem?

@EnableWebMvc is using DelegatingWebMvcConfiguration which extends WebMvcConfigurationSupport which does this:

if (jackson2Present) {
    Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
    if (this.applicationContext != null) {
        builder.applicationContext(this.applicationContext);
    }
    messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}

which means that there's no way of injecting your own ObjectMapper with the purpose of preparing it to be used for creating the default MappingJackson2HttpMessageConverter when using @EnableWebMvc.

vbscript output to console

Create a .vbs with the following code, which will open your main .vbs:

Set objShell = WScript.CreateObject("WScript.shell") 
objShell.Run "cscript.exe ""C:\QuickTestb.vbs"""

Here is my main .vbs

Option Explicit
Dim i
for i = 1 To 5
     Wscript.Echo i
     Wscript.Sleep 5000
Next

Render HTML in React Native

 <WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />

This worked for me :) I have html text aboutus file.

How to break out of nested loops?

int i = 0, j= 0;

for(i;i< 1000; i++){    
    for(j; j< 1000; j++){
        if(condition){
            i = j = 1001;
            break;
        }
    }
}

Will break both the loops.

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

I don't want to include the Support library just for getColor, so I'm using something like

public static int getColorWrapper(Context context, int id) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return context.getColor(id);
    } else {
        //noinspection deprecation
        return context.getResources().getColor(id);
    }
}

I guess the code should work just fine, and the deprecated getColor cannot disappear from API < 23.

And this is what I'm using in Kotlin:

/**
 * Returns a color associated with a particular resource ID.
 *
 * Wrapper around the deprecated [Resources.getColor][android.content.res.Resources.getColor].
 */
@Suppress("DEPRECATION")
@ColorInt
fun getColorHelper(context: Context, @ColorRes id: Int) =
    if (Build.VERSION.SDK_INT >= 23) context.getColor(id) else context.resources.getColor(id);

Mobile website "WhatsApp" button to send message to a specific number

Format to send a WhatsApp message to a specific number (updated Nov 2018)

<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>

where

whatsappphonenumber is a full phone number in international format

urlencodedtext is the URL-encoded pre-filled message.


Example:

  1. Create a link with a pre-filled message that will automatically appear in the text field of a chat, to be sent to a specific number

    Send I am interested in your car for sale to +001-(555)1234567

    https://wa.me/15551234567?text=I%20am%20interested%20in%20your%20car%20for%20sale

    Note :

    Use: https://wa.me/15551234567

    Don't use: https://wa.me/+001-(555)1234567

  2. Create a link with just a pre-filled message that will automatically appear in the text field of a chat, number will be chosen by the user

    Send I am enquiring about the apartment listing

    https://wa.me/?text=I%20am%20enquiring%20about%20the%20apartment%20listing

    After clicking on the link, user will be shown a list of contacts they can send the pre-filled message to.

For more information, see https://www.whatsapp.com/faq/en/general/26000030

--

P.S : Older format (before updation) for reference

<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>

PHP Get Site URL Protocol - http vs https

short way

$scheme = $_SERVER['REQUEST_SCHEME'] . '://';

How to prevent line-break in a column of a table cell (not a single cell)?

Use the nowrap style:

<td style="white-space:nowrap;">...</td>

It's CSS!

c++ Read from .csv file

That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r

and, using c/c++ to parse text is not a good idea. try awk:

 $awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
 ID=0   Name=Filipe Age=19  Gender=M
 ID=1   Name=Maria  Age=20  Gender=F
 ID=2   Name=Walter Age=60  Gender=M

Include another HTML file in a HTML file

Most of the solutions works but they have issue with jquery:

The issue is following code $(document).ready(function () { alert($("#includedContent").text()); } alerts nothing instead of alerting included content.

I write the below code, in my solution you can access to included content in $(document).ready function:

(The key is loading included content synchronously).

index.htm:

<html>
    <head>
        <script src="jquery.js"></script>

        <script>
            (function ($) {
                $.include = function (url) {
                    $.ajax({
                        url: url,
                        async: false,
                        success: function (result) {
                            document.write(result);
                        }
                    });
                };
            }(jQuery));
        </script>

        <script>
            $(document).ready(function () {
                alert($("#test").text());
            });
        </script>
    </head>

    <body>
        <script>$.include("include.inc");</script>
    </body>

</html>

include.inc:

<div id="test">
    There is no issue between this solution and jquery.
</div>

jquery include plugin on github

Enter key press in C#

private void Ctrl_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        this.SelectNextControl((Control)sender, true, true, true, true);
    }
}

Select all required textboxes; type in new Events name Ctrl_KeyUp.

See YouTube by BTNT TV: https://www.bing.com/videos/searchq=c%23+how+to+move+to+next+textbox+after+enterkey&view=detail&mid=999E8CAFC15140E867C0999E8CAFC15140E867C0&FORM=VIRE

How to call a vue.js function on page load

you can also do this using mounted

https://vuejs.org/v2/guide/migration.html#ready-replaced

....
methods:{
    getUnits: function() {...}
},
mounted: function(){
    this.$nextTick(this.getUnits)
}
....

HTML embedded PDF iframe

Try this out.

_x000D_
_x000D_
<iframe src="https://docs.google.com/viewerng/viewer?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" frameborder="0" height="100%" width="100%">_x000D_
</iframe>
_x000D_
_x000D_
_x000D_

Accessing Imap in C#

There is no .NET framework support for IMAP. You'll need to use some 3rd party component.

Try https://www.limilabs.com/mail, it's very affordable and easy to use, it also supports SSL:

using(Imap imap = new Imap())
{
    imap.ConnectSSL("imap.company.com");
    imap.Login("user", "password");

    imap.SelectInbox();
    List<long> uids = imap.SearchFlag(Flag.Unseen);
    foreach (long uid in uids)
    {
        string eml = imap.GetMessageByUID(uid);
        IMail message = new MailBuilder()
            .CreateFromEml(eml);

        Console.WriteLine(message.Subject);
        Console.WriteLine(message.TextDataString);
    }
    imap.Close(true);
}

Please note that this is a commercial product I've created.

You can download it here: https://www.limilabs.com/mail.

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

Creating a simple login form

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>Login Page</title>
      <style>
         /* Basics */
         html, body {
         width: 100%;
         height: 100%;
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         color: #444;
         -webkit-font-smoothing: antialiased;
         background: #f0f0f0;
         }
         #container {
         position: fixed;
         width: 340px;
         height: 280px;
         top: 50%;
         left: 50%;
         margin-top: -140px;
         margin-left: -170px;
         background: #fff;
         border-radius: 3px;
         border: 1px solid #ccc;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
         }
         form {
         margin: 0 auto;
         margin-top: 20px;
         }
         label {
         color: #555;
         display: inline-block;
         margin-left: 18px;
         padding-top: 10px;
         font-size: 14px;
         }
         p a {
         font-size: 11px;
         color: #aaa;
         float: right;
         margin-top: -13px;
         margin-right: 20px;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         p a:hover {
         color: #555;
         }
         input {
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         font-size: 12px;
         outline: none;
         }
         input[type=text],
         input[type=password] ,input[type=time]{
         color: #777;
         padding-left: 10px;
         margin: 10px;
         margin-top: 12px;
         margin-left: 18px;
         width: 290px;
         height: 35px;
         border: 1px solid #c7d0d2;
         border-radius: 2px;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         input[type=text]:hover,
         input[type=password]:hover,input[type=time]:hover {
         border: 1px solid #b6bfc0;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
         }
         input[type=text]:focus,
         input[type=password]:focus,input[type=time]:focus {
         border: 1px solid #a8c9e4;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
         }
         #lower {
         background: #ecf2f5;
         width: 100%;
         height: 69px;
         margin-top: 20px;
         box-shadow: inset 0 1px 1px #fff;
         border-top: 1px solid #ccc;
         border-bottom-right-radius: 3px;
         border-bottom-left-radius: 3px;
         }
         input[type=checkbox] {
         margin-left: 20px;
         margin-top: 30px;
         }
         .check {
         margin-left: 3px;
         font-size: 11px;
         color: #444;
         text-shadow: 0 1px 0 #fff;
         }
         input[type=submit] {
         float: right;
         margin-right: 20px;
         margin-top: 20px;
         width: 80px;
         height: 30px;
         font-size: 14px;
         font-weight: bold;
         color: #fff;
         background-color: #acd6ef; /*IE fallback*/
         background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         border-radius: 30px;
         border: 1px solid #66add6;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
         cursor: pointer;
         }
         input[type=submit]:hover {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         }
         input[type=submit]:active {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
         background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         }
      </style>
   </head>
   <body>
      <!-- Begin Page Content -->
      <div id="container">
         <form action="login_process.php" method="post">
            <label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php  echo @$_GET['msg'];?></label>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
            <div id="lower">
               <input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
               <input type="submit" value="Login">
            </div>
            <!--/ lower-->
         </form>
      </div>
      <!--/ container-->
      <!-- End Page Content -->
   </body>
</html>

Android Imagebutton change Image OnClick

That is because imgButton is null. Try this instead:

findViewById(R.id.imgButton).setBackgroundResource(R.drawable.ic_action_search);

or much easier to read:

imgButton = (Button) findViewById(R.id.imgButton);
imgButton.setOnClickListener(imgButtonHandler);

then in onClick: imgButton.setBackgroundResource(R.drawable.ic_action_search);

Zoom to fit all markers in Mapbox or Leaflet

To fit to the visible markers only, I've this method.

fitMapBounds() {
    // Get all visible Markers
    const visibleMarkers = [];
    this.map.eachLayer(function (layer) {
        if (layer instanceof L.Marker) {
            visibleMarkers.push(layer);
        }
    });

    // Ensure there's at least one visible Marker
    if (visibleMarkers.length > 0) {

        // Create bounds from first Marker then extend it with the rest
        const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
        visibleMarkers.forEach((marker) => {
            markersBounds.extend(marker.getLatLng());
        });

        // Fit the map with the visible markers bounds
        this.map.flyToBounds(markersBounds, {
            padding: L.point(36, 36), animate: true,
        });
    }
}

How to multiply duration by integer?

You have to cast it to a correct format Playground.

yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)

If you will check documentation for sleep, you see that it requires func Sleep(d Duration) duration as a parameter. Your rand.Int31n returns int32.

The line from the example works (time.Sleep(100 * time.Millisecond)) because the compiler is smart enough to understand that here your constant 100 means a duration. But if you pass a variable, you should cast it.

'node' is not recognized as an internal or external command

Node is missing from the SYSTEM PATH, try this in your command line

SET PATH=C:\Program Files\Nodejs;%PATH%

and then try running node

To set this system wide you need to set in the system settings - cf - http://banagale.com/changing-your-system-path-in-windows-vista.htm

To be very clean, create a new system variable NODEJS

NODEJS="C:\Program Files\Nodejs"

Then edit the PATH in system variables and add %NODEJS%

PATH=%NODEJS%;...

Creating JSON on the fly with JObject

Simple way of creating newtonsoft JObject from Properties.

This is a Sample User Properties

public class User
{
    public string Name;
    public string MobileNo;
    public string Address;
}

and i want this property in newtonsoft JObject is:

JObject obj = JObject.FromObject(new User()
{
    Name = "Manjunath",
    MobileNo = "9876543210",
    Address = "Mumbai, Maharashtra, India",
});

Output will be like this:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}

Calling a function when ng-repeat has finished

I'm very surprised not to see the most simple solution among the answers to this question. What you want to do is add an ngInit directive on your repeated element (the element with the ngRepeat directive) checking for $last (a special variable set in scope by ngRepeat which indicates that the repeated element is the last in the list). If $last is true, we're rendering the last element and we can call the function we want.

ng-init="$last && test()"

The complete code for your HTML markup would be:

<div ng-app="testApp" ng-controller="myC">
    <p ng-repeat="t in ta" ng-init="$last && test()">{{t}}</p>
</div>

You don't need any extra JS code in your app besides the scope function you want to call (in this case, test) since ngInit is provided by Angular.js. Just make sure to have your test function in the scope so that it can be accessed from the template:

$scope.test = function test() {
    console.log("test executed");
}

convert php date to mysql format

$date = mysql_real_escape_string($_POST['intake_date']);

1. If your MySQL column is DATE type:

$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

2. If your MySQL column is DATETIME type:

$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

You haven't got to work strototime(), because it will not work with dash - separators, it will try to do a subtraction.


Update, the way your date is formatted you can't use strtotime(), use this code instead:

$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date);
echo $date;

Output:

2009-07-02 00:07:00

How to convert a Collection to List?

List list = new ArrayList(coll);
Collections.sort(list);

As Erel Segal Halevi says below, if coll is already a list, you can skip step one. But that would depend on the internals of TreeBidiMap.

List list;
if (coll instanceof List)
  list = (List)coll;
else
  list = new ArrayList(coll);

How to make a phone call using intent in Android?

This demo will helpful for you...

On call button click:

Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "Your Phone_number"));
startActivity(intent);

Permission in Manifest:

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

Client to send SOAP request and receive response

I wrote a more general helper class which accepts a string-based dictionary of custom parameters, so that they can be set by the caller without having to hard-code them. It goes without saying that you should only use such method when you want (or need) to manually issue a SOAP-based web service: in most common scenarios the recommended approach would be using the Web Service WSDL together with the Add Service Reference Visual Studio feature instead.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;

namespace Ryadel.Web.SOAP
{
    /// <summary>
    /// Helper class to send custom SOAP requests.
    /// </summary>
    public static class SOAPHelper
    {
        /// <summary>
        /// Sends a custom sync SOAP request to given URL and receive a request
        /// </summary>
        /// <param name="url">The WebService endpoint URL</param>
        /// <param name="action">The WebService action name</param>
        /// <param name="parameters">A dictionary containing the parameters in a key-value fashion</param>
        /// <param name="soapAction">The SOAPAction value, as specified in the Web Service's WSDL (or NULL to use the url parameter)</param>
        /// <param name="useSOAP12">Set this to TRUE to use the SOAP v1.2 protocol, FALSE to use the SOAP v1.1 (default)</param>
        /// <returns>A string containing the raw Web Service response</returns>
        public static string SendSOAPRequest(string url, string action, Dictionary<string, string> parameters, string soapAction = null, bool useSOAP12 = false)
        {
            // Create the SOAP envelope
            XmlDocument soapEnvelopeXml = new XmlDocument();
            var xmlStr = (useSOAP12)
                ? @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
                      xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                      xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
                      <soap12:Body>
                        <{0} xmlns=""{1}"">{2}</{0}>
                      </soap12:Body>
                    </soap12:Envelope>"
                : @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" 
                        xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
                        xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                        <soap:Body>
                           <{0} xmlns=""{1}"">{2}</{0}>
                        </soap:Body>
                    </soap:Envelope>";
            string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
            var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
            soapEnvelopeXml.LoadXml(s);

            // Create the web request
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", soapAction ?? url);
            webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" : "text/xml;charset=\"utf-8\"";
            webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
            webRequest.Method = "POST";

            // Insert SOAP envelope
            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }

            // Send request and retrieve result
            string result;
            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    result = rd.ReadToEnd();
                }
            }
            return result;
        }
    }
}

For additional info & details regarding this class you can also read this post on my blog.

GenyMotion Unable to start the Genymotion virtual device

After you have updated the latest GenyMotion Version to 2.10 from 2.02...

  1. Open GenyMotion
  2. Go to the List of your 2.02 Devices
  3. Left click the item and then right click on the menu to **Delete all your 2.02 Virtual Devices
  4. Click the Add button at the top to add a New Device. Log into your account
  5. Select the device you want. You can only select one device at a time
  6. Click the Next button. Notice the Version number says - 2.10. There is other info about the device here.
  7. Your device will start downloading to your GenyMotion Folder on the Drive **C. 8 After you download it, double click it to open up the Virtual Device like you normally would.
  8. Repeat for other device you want

** C:\%Users%\AppData\Local\Genymobile\Genymotion\deployed

Convert or extract TTC font to TTF - how to?

If you've got a Mac the easiest way to split those would be to use DfontSplitter, available at https://peter.upfold.org.uk/projects/dfontsplitter

The Windows version they provide doesn't work with ttc files.

How do I install Python OpenCV through Conda?

Windows only solution. OpenCV 3.x pip install for Python 3.x

Download .whl file (cpMN where you have Python M.N). contrib includes OpenCV-extra packages. For example, assuming you have Python 3.6 and Windows 64-bit, you might download opencv_python-3.2.0+contrib-cp36-cp36m-win_amd64.whl

From command prompt type:

pip install opencv_python-3.2.0+contrib-cp36-cp36m-win_amd64.whl

You'll have a package in your conda list : opencv-python 3.2.0+contrib <pip>

Now you could test it (no errors):

>>> import cv2
>>>

Original source page where I took the information is here.

Fetch the row which has the Max value for a column

SELECT a.* 
FROM user a INNER JOIN (SELECT userid,Max(date) AS date12 FROM user1 GROUP BY userid) b  
ON a.date=b.date12 AND a.userid=b.userid ORDER BY a.userid;

How can I make Jenkins CI with Git trigger on pushes to master?

My solution for a local git server: go to your local git server hook directory, ignore the existing update.sample and create a new file literally named as "update", such as:

gituser@me:~/project.git/hooks$ pwd
/home/gituser/project.git/hooks
gituser@me:~/project.git/hooks$ cat update
#!/bin/sh
echo "XXX from  update file"
curl -u admin:11f778f9f2c4d1e237d60f479974e3dae9 -X POST http://localhost:8080/job/job4_pullsrc_buildcontainer/build?token=11f778f9f2c4d1e237d60f479974e3dae9

exit 0
gituser@me:~/project.git/hooks$ 

The echo statement will be displayed under your git push result, token can be taken from your jenkins job configuration, browse to find it. If the file "update" is not called, try some other files with the same name without extension "sample".

That's all you need

SQL JOIN vs IN performance?

A interesting writeup on the logical differences: SQL Server: JOIN vs IN vs EXISTS - the logical difference

I am pretty sure that assuming that the relations and indexes are maintained a Join will perform better overall (more effort goes into working with that operation then others). If you think about it conceptually then its the difference between 2 queries and 1 query.

You need to hook it up to the Query Analyzer and try it and see the difference. Also look at the Query Execution Plan and try to minimize steps.

Properly embedding Youtube video into bootstrap 3.0 page

There is a Bootstrap3 native solution: http://getbootstrap.com/components/#responsive-embed

since Bootstrap 3.2.0!

If you are using Bootstrap < v3.2.0 so look into "responsive-embed.less" file of v3.2.0 - possibly you can use/copy this code in your case (it works for me in v3.1.1).

What is the perfect counterpart in Python for "while not EOF"

You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.

line = obj.readlines()

Can I do Android Programming in C++, C?

You can take a look also at C++ Builder XE6, and XE7 supports android in c++ code, and with Firemonkey library.

http://www.embarcadero.com/products/cbuilder

Pretty easy way to start, and native code. But the binaries have a big size.

Where is HttpContent.ReadAsAsync?

You can write extention method:

public static async Task<Tout> ReadAsAsync<Tout>(this System.Net.Http.HttpContent content) {
    return Newtonsoft.Json.JsonConvert.DeserializeObject<Tout>(await content.ReadAsStringAsync());
}

How to fetch data from local JSON file on react native?

Use this

import data from './customData.json';

How Do I Uninstall Yarn

In case you installed yarn globally like this

$ sudo npm install -g yarn

Just run this in terminal

$ sudo npm uninstall -g yarn

Tested now on my local machine running Ubuntu. Works perfect!

JOptionPane YES/No Options Confirm Dialog Box Issue

int opcion = JOptionPane.showConfirmDialog(null, "Realmente deseas salir?", "Aviso", JOptionPane.YES_NO_OPTION);

if (opcion == 0) { //The ISSUE is here
   System.out.print("si");
} else {
   System.out.print("no");
}

How to append multiple items in one line in Python

You could also:

newlist += mylist[i:i+22]

How to revert a "git rm -r ."?

I had exactly the same issue: was cleaning up my folders, rearranging and moving files. I entered: git rm . and hit enter; and then felt my bowels loosen a bit. Luckily, I didn't type in git commit -m "" straightaway.

However, the following command

git checkout .

restored everything, and saved my life.

How to check if the request is an AJAX request with PHP

From PHP 7 with null coalescing operator it will be shorter:

$is_ajax = 'xmlhttprequest' == strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );

Rails 3 execute custom sql query without a model

How about this :

@client = TinyTds::Client.new(
      :adapter => 'mysql2',
      :host => 'host',
      :database => 'siteconfig_development',
      :username => 'username',
      :password => 'password'

sql = "SELECT * FROM users"

result = @client.execute(sql)

results.each do |row|
puts row[0]
end

You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record

Data binding to SelectedItem in a WPF Treeview

I bring you my solution which offers the following features:

  • Supports 2 ways binding

  • Auto updates the TreeViewItem.IsSelected properties (according to the SelectedItem)

  • No TreeView subclassing

  • Items bound to ViewModel can be of any type (even null)

1/ Paste the following code in your CS:

public class BindableSelectedItem
{
    public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.RegisterAttached(
        "SelectedItem", typeof(object), typeof(BindableSelectedItem), new PropertyMetadata(default(object), OnSelectedItemPropertyChangedCallback));

    private static void OnSelectedItemPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var treeView = d as TreeView;
        if (treeView != null)
        {
            BrowseTreeViewItems(treeView, tvi =>
            {
                tvi.IsSelected = tvi.DataContext == e.NewValue;
            });
        }
        else
        {
            throw new Exception("Attached property supports only TreeView");
        }
    }

    public static void SetSelectedItem(DependencyObject element, object value)
    {
        element.SetValue(SelectedItemProperty, value);
    }

    public static object GetSelectedItem(DependencyObject element)
    {
        return element.GetValue(SelectedItemProperty);
    }

    public static void BrowseTreeViewItems(TreeView treeView, Action<TreeViewItem> onBrowsedTreeViewItem)
    {
        var collectionsToVisit = new System.Collections.Generic.List<Tuple<ItemContainerGenerator, ItemCollection>> { new Tuple<ItemContainerGenerator, ItemCollection>(treeView.ItemContainerGenerator, treeView.Items) };
        var collectionIndex = 0;
        while (collectionIndex < collectionsToVisit.Count)
        {
            var itemContainerGenerator = collectionsToVisit[collectionIndex].Item1;
            var itemCollection = collectionsToVisit[collectionIndex].Item2;
            for (var i = 0; i < itemCollection.Count; i++)
            {
                var tvi = itemContainerGenerator.ContainerFromIndex(i) as TreeViewItem;
                if (tvi == null)
                {
                    continue;
                }

                if (tvi.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
                {
                    collectionsToVisit.Add(new Tuple<ItemContainerGenerator, ItemCollection>(tvi.ItemContainerGenerator, tvi.Items));
                }

                onBrowsedTreeViewItem(tvi);
            }

            collectionIndex++;
        }
    }

}

2/ Example of use in your XAML file

<TreeView myNS:BindableSelectedItem.SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" />  

How to find where javaw.exe is installed?

For the sake of completeness, let me mention that there are some places (on a Windows PC) to look for javaw.exe in case it is not found in the path: (Still Reimeus' suggestion should be your first attempt.)

1.
Java usually stores it's location in Registry, under the following key:
HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome

2.
Newer versions of JRE/JDK, seem to also place a copy of javaw.exe in 'C:\Windows\System32', so one might want to check there too (although chances are, if it is there, it will be found in the path as well).

3.
Of course there are the "usual" install locations:

  • 'C:\Program Files\Java\jre*\bin'
  • 'C:\Program Files\Java\jdk*\bin'
  • 'C:\Program Files (x86)\Java\jre*\bin'
  • 'C:\Program Files (x86)\Java\jdk*\bin'

[Note, that for older versions of Windows (XP, Vista(?)), this will only help on english versions of the OS. Fortunately, on later version of Windows "Program Files" will point to the directory regardless of its "display name" (which is language-specific).]

A little while back, I wrote this piece of code to check for javaw.exe in the aforementioned places. Maybe someone finds it useful:

static protected String findJavaw() {
    Path pathToJavaw = null;
    Path temp;

    /* Check in Registry: HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome */
    String keyNode = "HKLM\\Software\\JavaSoft\\Java Runtime Environment";
    List<String> output = new ArrayList<>();
    executeCommand(new String[] {"REG", "QUERY", "\"" + keyNode + "\"", 
                                 "/v", "CurrentVersion"}, 
                   output);
    Pattern pattern = Pattern.compile("\\s*CurrentVersion\\s+\\S+\\s+(.*)$");
    for (String line : output) {
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            keyNode += "\\" + matcher.group(1);
            List<String> output2 = new ArrayList<>();
            executeCommand(
                    new String[] {"REG", "QUERY", "\"" + keyNode + "\"", 
                                  "/v", "JavaHome"}, 
                    output2);
            Pattern pattern2 
                    = Pattern.compile("\\s*JavaHome\\s+\\S+\\s+(.*)$");
            for (String line2 : output2) {
                Matcher matcher2 = pattern2.matcher(line2);
                if (matcher2.find()) {
                    pathToJavaw = Paths.get(matcher2.group(1), "bin", 
                                            "javaw.exe");
                    break;
                }
            }
            break;
        }
    }
    try {
        if (Files.exists(pathToJavaw)) {
            return pathToJavaw.toString();
        }
    } catch (Exception ignored) {}

    /* Check in 'C:\Windows\System32' */
    pathToJavaw = Paths.get("C:\\Windows\\System32\\javaw.exe");
    try {
        if (Files.exists(pathToJavaw)) {
            return pathToJavaw.toString();
        }
    } catch (Exception ignored) {}

    /* Check in 'C:\Program Files\Java\jre*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jre*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JRE version
                }                    
            }
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
            }
        } catch (Exception ignored) {}
    }

    /* Check in 'C:\Program Files (x86)\Java\jre*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files (x86)\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jre*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JRE version
                }                    
            }
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
            }
        } catch (Exception ignored) {}
    }

    /* Check in 'C:\Program Files\Java\jdk*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jdk*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JDK version
                }                    
            }
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
            }
        } catch (Exception ignored) {}
    }

    /* Check in 'C:\Program Files (x86)\Java\jdk*' */
    pathToJavaw = null;
    temp = Paths.get("C:\\Program Files (x86)\\Java");
    if (Files.exists(temp)) {
        try (DirectoryStream<Path> dirStream 
                = Files.newDirectoryStream(temp, "jdk*")) {
            for (Path path : dirStream) {
                temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
                if (Files.exists(temp)) {
                    pathToJavaw = temp;
                    // Don't "break", in order to find the latest JDK version
                }                    
            }
            if (pathToJavaw != null) {
                return pathToJavaw.toString();
            }
        } catch (Exception ignored) {}
    }

    return "javaw.exe";   // Let's just hope it is in the path :)
}

RecyclerView vs. ListView

In my opinion RecyclerView was made to address the problem with the recycle pattern used in listviews because it was making developer's life more difficult. All the other you could handle more or less. For instance I use the same adapter for ListView and GridView it doesn't matter in both views the getView, getItemCount, getTypeCount is used so it's the same. RecyclerView isn't needed if ListView with ListAdapter or GridView with grid adapters is already working for you. If you have implemented correctly the ViewHolder pattern in your listviews then you won't see any big improvement over RecycleView.

Hard reset of a single file

You can use the following command:

git checkout filename

If you have a branch with the same file name you have to use this command:

git checkout -- filename

How can I update my ADT in Eclipse?

I had the same problem where there's no files under Generated Java files, BuildConfig and R.java were missing. The automatic build option is not generating.
In Eclipse under Project, uncheck Build Automatically. Then under Project select Build Project. You may need to fix the projec

How to install php-curl in Ubuntu 16.04

In Ubuntu 16.04 default PHP version is 7.0, if you want to use different version then you need to install PHP package according to PHP version:

  • PHP 7.4: sudo apt-get install php7.4-curl
  • PHP 7.3: sudo apt-get install php7.3-curl
  • PHP 7.2: sudo apt-get install php7.2-curl
  • PHP 7.1: sudo apt-get install php7.1-curl
  • PHP 7.0: sudo apt-get install php7.0-curl
  • PHP 5.6: sudo apt-get install php5.6-curl
  • PHP 5.5: sudo apt-get install php5.5-curl

How can I enter latitude and longitude in Google Maps?

First is latitude, second longitude. Different than many constructors in mapbox.

Here are examples of formats that work:

  • Degrees, minutes, and seconds (DMS): 41°24'12.2"N 2°10'26.5"E
  • Degrees and decimal minutes (DMM): 41 24.2028, 2 10.4418
  • Decimal degrees (DD): 41.40338, 2.17403

Tips for formatting your coordinates

  • Use the degree symbol instead of “d”.
  • Use periods as decimals, not commas.
    • Incorrect: 41,40338, 2,17403.
    • Correct: 41.40338, 2.17403.
  • List your latitude coordinates before longitude coordinates.
  • Check that the first number in your latitude coordinate is between -90 and 90 and the first number in your longitude coordinate is between -180 and 180.

https://support.google.com/maps/answer/18539

How to convert enum names to string in c

In a situation where you have this:

enum fruit {
    apple, 
    orange, 
    grape,
    banana,
    // etc.
};

I like to put this in the header file where the enum is defined:

static inline char *stringFromFruit(enum fruit f)
{
    static const char *strings[] = { "apple", "orange", "grape", "banana", /* continue for rest of values */ };

    return strings[f];
}

How to append elements into a dictionary in Swift?

For whoever reading this for swift 5.1+

  // 1. Using updateValue to update the given key or add new if doesn't exist


    var dictionary = [Int:String]()    
    dictionary.updateValue("egf", forKey: 3)



 // 2. Using a dictionary[key]

    var dictionary = [Int:String]()    
    dictionary[key] = "value"



 // 3. Using subscript and mutating append for the value

    var dictionary = [Int:[String]]()

    dictionary[key, default: ["val"]].append("value")

Reading DataSet

DataSet resembles database. DataTable resembles database table, and DataRow resembles a record in a table. If you want to add filtering or sorting options, you then do so with a DataView object, and convert it back to a separate DataTable object.

If you're using database to store your data, then you first load a database table to a DataSet object in memory. You can load multiple database tables to one DataSet, and select specific table to read from the DataSet through DataTable object. Subsequently, you read a specific row of data from your DataTable through DataRow. Following codes demonstrate the steps:

SqlCeDataAdapter da = new SqlCeDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();

da.SelectCommand = new SqlCommand(@"SELECT * FROM FooTable", connString);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];

foreach (DataRow dr in dt.Rows)
{
    MessageBox.Show(dr["Column1"].ToString());
}

To read a specific cell in a row:

int rowNum // row number
string columnName = "DepartureTime";  // database table column name
dt.Rows[rowNum][columnName].ToString();

Swift how to sort array of custom objects by property value

You return a sorted array from the fileID property by following way:

Swift 2

let sortedArray = images.sorted({ $0.fileID > $1.fileID })

Swift 3 OR 4

let sortedArray = images.sorted(by: { $0.fileID > $1.fileID })

Swift 5.0

let sortedArray = images.sorted {
    $0.fileID < $1.fileID
}

Url.Action parameters?

This works for MVC 5:

<a href="@Url.Action("ActionName", "ControllerName", new { paramName1 = item.paramValue1, paramName2 = item.paramValue2 })" >
    Link text
</a>

How to execute a stored procedure within C# program

Please check out Crane (I'm the author)

https://www.nuget.org/packages/Crane/

SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
var result = sqlAccess.Command().ExecuteNonQuery("StoredProcedureName");

Also has a bunch of other features you might like.

Array of an unknown length in C#

A little background information:

As said, if you want to have a dynamic collection of things, use a List<T>. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List, it's added to the array. Initially, the List starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List may appear dynamic to the outside observer, internally it has to comply to the rules as well.

And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.

How to export collection to CSV in MongoDB?

works for me remoting to a docker container with mongo:4.2.6

mongoexport -h mongodb:27017 --authenticationDatabase=admin -u username -p password -d database -c collection -q {"created_date": { "$gte": { "$date": "2020-08-03T00:00:00.000Z" }, "$lt": { "$date": "2020-08-09T23:59:59.999Z" } } } --fields=somefield1,somefield2 --type=csv --out=/archive.csv

Android Button click go to another xml page

Change your FirstyActivity to:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_go=(Button)findViewById(R.id.YOUR_BUTTON_ID);
            btn_go.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                  Log.i("clicks","You Clicked B1");
              Intent i=new Intent(
                     MainActivity.this,
                     MainActivity2.class);
              startActivity(i);
            }
        }
    });

}

Hope it will help you.

How can I remove an element from a list, with lodash?

you can do it with _pull.

_.pull(obj["subTopics"] , {"subTopicId":2, "number":32});

check the reference

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

Source

Install (if not found):

pip install mysql.connector

Settings:

'default': {
    'ENGINE': 'mysql.connector.django',
    'NAME': '...',
    'HOST': '...',
    'PORT': '3306',
    'USER': '...',
    'PASSWORD': '...',
}

How to set custom location for local installation of npm package?

On Windows 7 for example, the following set of commands/operations could be used.

Create an personal environment variable, double backslashes are mandatory:

  • Variable name: %NPM_HOME%
  • Variable value: C:\\SomeFolder\\SubFolder\\

Now, set the config values to the new folders (examplary file names):

  • Set the npm folder

npm config set prefix "%NPM_HOME%\\npm"

  • Set the npm-cache folder

npm config set cache "%NPM_HOME%\\npm-cache"

  • Set the npm temporary folder

npm config set tmp "%NPM_HOME%\\temp"

Optionally, you can purge the contents of the original folders before the config is changed.

  • Delete the npm-cache npm cache clear

  • List the npm modules npm -g ls

  • Delete the npm modules npm -g rm name_of_package1 name_of_package2

Insert into ... values ( SELECT ... FROM ... )

In informix it works as Claude said:

INSERT INTO table (column1, column2) 
VALUES (value1, value2);    

A function to convert null to string

It is possible to use the "?." (null conditional member access) with the "??" (null-coalescing operator) like this:

public string EmptyIfNull(object value)
{
    return value?.ToString() ?? string.Empty;
}

This method can also be written as an extension method for an object:

public static class ObjectExtensions
{
    public static string EmptyIfNull(this object value)
    {
        return value?.ToString() ?? string.Empty;
    }
}

And you can write same methods using "=>" (lambda operator):

public string EmptyIfNull(object value)
    => value?.ToString() ?? string.Empty;

Format numbers in JavaScript similar to C#

To get a decimal with 2 numbers after the comma, you could just use:

function nformat(a) {
   var b = parseInt(parseFloat(a)*100)/100;
   return b.toFixed(2);
}

ExpressionChangedAfterItHasBeenCheckedError Explained

I hope this helps someone coming here: We make service calls in ngOnInit in the following manner and use a variable displayMain to control the Mounting of the elements to the DOM.

component.ts

  displayMain: boolean;
  ngOnInit() {
    this.displayMain = false;
    // Service Calls go here
    // Service Call 1
    // Service Call 2
    // ...
    this.displayMain = true;
  }

and component.html

<div *ngIf="displayMain"> <!-- This is the Root Element -->
 <!-- All the HTML Goes here -->
</div>

Select columns from result set of stored procedure

If you are able to modify your stored procedure, you can easily put the required columns definitions as a parameter and use an auto-created temporary table:

CREATE PROCEDURE sp_GetDiffDataExample
      @columnsStatement NVARCHAR(MAX) -- required columns statement (e.g. "field1, field2")
AS
BEGIN
    DECLARE @query NVARCHAR(MAX)
    SET @query = N'SELECT ' + @columnsStatement + N' INTO ##TempTable FROM dbo.TestTable'
    EXEC sp_executeSql @query
    SELECT * FROM ##TempTable
    DROP TABLE ##TempTable
END

In this case you don't need to create a temp table manually - it is created automatically. Hope this helps.

New Intent() starts new instance with Android: launchMode="singleTop"

This should do the trick.

<activity ... android:launchMode="singleTop" />

When you create an intent to start the app use:

Intent intent= new Intent(context, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

This is that should be needed.

Counting the Number of keywords in a dictionary in python

Calling len() directly on your dictionary works, and is faster than building an iterator, d.keys(), and calling len() on it, but the speed of either will negligible in comparison to whatever else your program is doing.

d = {x: x**2 for x in range(1000)}

len(d)
# 1000

len(d.keys())
# 1000

%timeit len(d)
# 41.9 ns ± 0.244 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit len(d.keys())
# 83.3 ns ± 0.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

What is getattr() exactly and how do I use it?

I have tried in Python2.7.17

Some of the fellow folks already answered. However I have tried to call getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.

Example Code:

Example 1:

    class GETATT_VERIFY():
       name = "siva"
       def __init__(self):
           print "Ok"
       def set_value(self):
           self.value = "myself"
           print "oooh"
    obj = GETATT_VERIFY()
    print getattr(GETATT_VERIFY, 'name')
    getattr(obj, 'set_value')()
    print obj.value

asynchronous vs non-blocking

Blocking: control returns to invoking precess after processing of primitive(sync or async) completes

Non blocking: control returns to process immediately after invocation

how to inherit Constructor from super class to sub class

Say if you have

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

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

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

and

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

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

How can I do a case insensitive string comparison?

Please use this for comparison:

string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);

PHP read and write JSON from file

If you want to display the JSON data in well defined formate you can modify the code as:

file_put_contents($file, json_encode($json,TRUE));


$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));

$context=stream_context_create($headers);

$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);

$str1=utf8_encode($str);

$str1=json_decode($str1,true);



foreach($str1 as $key=>$value)
{

    echo "key is: $key.\n";

    echo "values are: \t";
        foreach ($value as $k) {

        echo " $k. \t";
        # code...
    }
        echo "<br></br>";
        echo "\n";

}

How do I activate a virtualenv inside PyCharm's terminal?

I had the same problem with venv in PyCharm. But It is not big problem! Just do:

  1. enter in your terminal venv directory( cd venv/Scripts/ )
  2. You will see activate.bat
  3. Just enter activate.bat in your terminal after this you will see YOUR ( venv )

Calculating difference between two timestamps in Oracle in milliseconds

I know that this has been exhaustively answered, but I wanted to share my FUNCTION with everyone. It gives you the option to choose if you want your answer to be in days, hours, minutes, seconds, or milliseconds. You can modify it to fit your needs.

CREATE OR REPLACE FUNCTION Return_Elapsed_Time (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
    FUNCTION Core (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
        day_ VARCHAR2(7); /* This means this FUNCTION only supports up to 99 days */
        hour_ VARCHAR2(9); /* This means this FUNCTION only supports up to 999 hours, which is over 41 days */
        minute_ VARCHAR2(12); /* This means this FUNCTION only supports up to 9999 minutes, which is over 17 days */
        second_ VARCHAR2(18); /* This means this FUNCTION only supports up to 999999 seconds, which is over 11 days */
        msecond_ VARCHAR2(22); /* This means this FUNCTION only supports up to 999999999 milliseconds, which is over 11 days */
        d1_ NUMBER;
        h1_ NUMBER;
        m1_ NUMBER;
        s1_ NUMBER;
        ms_ NUMBER;
        /* If you choose 1, you only get seconds. If you choose 2, you get minutes and seconds etc. */
        precision_ NUMBER; /* 0 => milliseconds; 1 => seconds; 2 => minutes; 3 => hours; 4 => days */
        format_ VARCHAR2(2) := ', ';
        return_ VARCHAR2(50);
    BEGIN
        IF (syntax_ IS NULL) THEN
            precision_ := 0;
        ELSE
            IF (syntax_ = 0) THEN
                precision_ := 0;
            ELSIF (syntax_ = 1) THEN
                precision_ := 1;
            ELSIF (syntax_ = 2) THEN
                precision_ := 2;
            ELSIF (syntax_ = 3) THEN
                precision_ := 3;
            ELSIF (syntax_ = 4) THEN
                precision_ := 4;
            ELSE 
                precision_ := 0;
            END IF;
        END IF;
        SELECT EXTRACT(DAY FROM (end_ - start_)) INTO d1_ FROM DUAL;
        SELECT EXTRACT(HOUR FROM (end_ - start_)) INTO h1_ FROM DUAL;
        SELECT EXTRACT(MINUTE FROM (end_ - start_)) INTO m1_ FROM DUAL;
        SELECT EXTRACT(SECOND FROM (end_ - start_)) INTO s1_ FROM DUAL;
        IF (precision_ = 4) THEN
            IF (d1_ = 1) THEN
                day_ := ' day';
            ELSE
                day_ := ' days';
            END IF;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := d1_ || day_ || format_ || h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 3) THEN
            h1_ := (d1_ * 24) + h1_;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 2) THEN
            m1_ := (((d1_ * 24) + h1_) * 60) + m1_;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 1) THEN
            s1_ := (((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := s1_ || second_;
            RETURN return_;
        ELSE
            ms_ := ((((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_) * 1000;
            IF (ms_ = 1) THEN
                msecond_ := ' millisecond';
            ELSE
                msecond_ := ' milliseconds';
            END IF;
            return_ := ms_ || msecond_;
            RETURN return_;
        END IF;
    END Core;
BEGIN
    RETURN(Core(start_, end_, syntax_));
END Return_Elapsed_Time;

For example, if I called this function right now (12.10.2018 11:17:00.00) using Return_Elapsed_Time(TO_TIMESTAMP('12.04.2017 12:00:00.00', 'DD.MM.YYYY HH24:MI:SS.FF'),SYSTIMESTAMP), it should return something like:

47344620000 milliseconds

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem with 'org.codehaus.mojo'-'jaxws-maven-plugin': could not resolve dependencies. Fortunately, I was able to do a Project > Clean in Eclipse, which resolved the issue.

How to check if a query string value is present via JavaScript?

This should help:

function getQueryParams(){
    try{
        url = window.location.href;
        query_str = url.substr(url.indexOf('?')+1, url.length-1);
        r_params = query_str.split('&');
        params = {}
        for( i in r_params){
            param = r_params[i].split('=');
            params[ param[0] ] = param[1];
        }
        return params;
    }
    catch(e){
       return {};
    }
}

Is it possible to listen to a "style change" event?

I think the best answer if from Mike in the case you can't launch your event because is not from your code. But I get some errors when I used it. So I write a new answer for show you the code that I use.

Extension

// Extends functionality of ".css()"
// This could be renamed if you'd like (i.e. "$.fn.cssWithListener = func ...")
(function() {
    orig = $.fn.css;
    $.fn.css = function() {
        var result = orig.apply(this, arguments);
        $(this).trigger('stylechanged');
        return result;
    }
})();

Usage

// Add listener
$('element').on('stylechanged', function () {
    console.log('css changed');
});

// Perform change
$('element').css('background', 'red');

I got error because var ev = new $.Event('style'); Something like style was not defined in HtmlDiv.. I removed it, and I launch now $(this).trigger("stylechanged"). Another problem was that Mike didn't return the resulto of $(css, ..) then It can make problems in some cases. So I get the result and return it. Now works ^^ In every css change include from some libs that I can't modify and trigger an event.

Android Studio: Default project directory

File -> Other Settings -> Default settings... -> Terminal --> Project setting --> Start Directory --> ("Browse or Set Your Project Directory Path")

Now Close current Project and Start New Project Then Let Your eyes see Project Location

Syntax for a single-line Bash infinite while loop

You don't even need to use do and done. For infinite loops I find it more readable to use for with curly brackets. For example:

for ((;;)) { date ; sleep 1 ; }

This works in bash and zsh. Doesn't work in sh.

Xcode 5 and iOS 7: Architecture and Valid architectures

My understanding from Apple Docs.

  • What is Architectures (ARCHS) into Xcode build-settings?
    • Specifies architecture/s to which the binary is TARGETED. When specified more that one architecture, the generated binary may contain object code for each of the specified architecture.
  • What is Valid Architectures (VALID_ARCHS) into Xcode build-settings?

    • Specifies architecture/s for which the binary may be BUILT.
    • During build process, this list is intersected with ARCHS and the resulting list specifies the architectures the binary can run on.
  • Example :- One iOS project has following build-settings into Xcode.

    • ARCHS = armv7 armv7s
    • VALID_ARCHS = armv7 armv7s arm64
    • In this case, binary will be built for armv7 armv7s arm64 architectures. But the same binary will run on ONLY ARCHS = armv7 armv7s.

How do I search for an object by its ObjectId in the mongo console?

Once you opened the mongo CLI, connected and authorized on the right database.

The following example shows how to find the document with the _id=568c28fffc4be30d44d0398e from a collection called “products”:

db.products.find({"_id": ObjectId("568c28fffc4be30d44d0398e")})

C# HttpClient 4.5 multipart/form-data upload

Here's a complete sample that worked for me. The boundary value in the request is added automatically by .NET.

var url = "http://localhost/api/v1/yourendpointhere";
var filePath = @"C:\path\to\image.jpg";

HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();

FileStream fs = File.OpenRead(filePath);
var streamContent = new StreamContent(fs);

var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

form.Add(imageContent, "image", Path.GetFileName(filePath));
var response = httpClient.PostAsync(url, form).Result;

MySQL error: key specification without a key length

Add another varChar(255) column (with default as empty string not null) to hold the overflow when 255 chars are not enough, and change this PK to use both columns. This does not sound like a well designed database schema however, and I would recommend getting a data modeler to look at what you have with a view towards refactoring it for more Normalization.

How do I turn off the mysql password validation?

Here is what I do to remove the validate password plugin:

  1. Login to the mysql server as root mysql -h localhost -u root -p
  2. Run the following sql command: uninstall plugin validate_password;
  3. If last line doesn't work (new mysql release), you should execute UNINSTALL COMPONENT 'file://component_validate_password';

I would not recommend this solution for a production system. I used this solution on a local mysql instance for development purposes only.

Is it possible to have different Git configuration for different projects?

There are 3 levels of git config; project, global and system.

  • project: Project configs are only available for the current project and stored in .git/config in the project's directory.
  • global: Global configs are available for all projects for the current user and stored in ~/.gitconfig.
  • system: System configs are available for all the users/projects and stored in /etc/gitconfig.

Create a project specific config, you have to execute this under the project's directory:

$ git config user.name "John Doe" 

Create a global config:

$ git config --global user.name "John Doe"

Create a system config:

$ git config --system user.name "John Doe" 

And as you may guess, project overrides global and global overrides system.

Note: Project configs are local to just one particular copy/clone of this particular repo, and need to be reapplied if the repo is recloned clean from the remote. It changes a local file that is not sent to the remote with a commit/push.

How can I convert an image into Base64 string using JavaScript?

Try this code:

For a file upload change event, call this function:

$("#fileproof").on('change', function () {
    readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });
});

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;

    if (files && files[0]) {
        var fr = new FileReader();
        fr.onload = function (e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL(files[0]);
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

Store Base64 data in hidden filed to use.

Align <div> elements side by side

Beware float: left

…there are many ways to align elements side-by-side.

Below are the most common ways to achieve two elements side-by-side…

Demo: View/edit all the below examples on Codepen


Basic styles for all examples below…

Some basic css styles for parent and child elements in these examples:

.parent {
  background: mediumpurple;
  padding: 1rem;
}
.child {
  border: 1px solid indigo;
  padding: 1rem;
}

float:left

Using the float solution my have unintended affect on other elements. (Hint: You may need to use a clearfix.)

html

<div class='parent'>
  <div class='child float-left-child'>A</div>
  <div class='child float-left-child'>B</div>
</div>

css

.float-left-child {
  float: left;
}

display:inline-block

html

<div class='parent'>
  <div class='child inline-block-child'>A</div>
  <div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

Note: the space between these two child elements can be removed, by removing the space between the div tags:

display:inline-block (no space)

html

<div class='parent'>
  <div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

display:flex

html

<div class='parent flex-parent'>
  <div class='child flex-child'>A</div>
  <div class='child flex-child'>B</div>
</div>

css

.flex-parent {
  display: flex;
}
.flex-child {
  flex: 1;
}

display:inline-flex

html

<div class='parent inline-flex-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.inline-flex-parent {
  display: inline-flex;
}

display:grid

html

<div class='parent grid-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.grid-parent {
  display: grid;
  grid-template-columns: 1fr 1fr
}

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

In my case it was a breakpoint set in my own page source. If I removed or disabled the breakpoint then the error would clear up.

The breakpoint was in a moderately complex chunk of rendering code. Other breakpoints in different parts of the page had no such effect. I was not able to work out a simple test case that always trigger this error.

from list of integers, get number closest to a given value

Iterate over the list and compare the current closest number with abs(currentNumber - myNumber):

def takeClosest(myList, myNumber):
    closest = myList[0]
    for i in range(1, len(myList)):
        if abs(i - myNumber) < closest:
            closest = i
    return closest

Setting a property by reflection with a string value

Are you looking to play around with Reflection or are you looking to build a production piece of software? I would question why you're using reflection to set a property.

Double new_latitude;

Double.TryParse (value, out new_latitude);
ship.Latitude = new_latitude;

LINQ Joining in C# with multiple conditions

If you need not equal object condition use cross join sequences:

var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]

How do I check if the Java JDK is installed on Mac?

  • Open terminal.
  • run command to see:

    javac -version

  • Also you can verify manually by going to the specific location and then check. To do this run below command in the mac terminal

    cd /Library/Java/JavaVirtualMachines/

Then run ls command in the terminal again. Now you can see the jdk version & package if exists in your computer.

How can I do time/hours arithmetic in Google Spreadsheet?

So much simpler: look at this

B2: 23:00
C2:  1:37
D2: = C2 - B2 + ( B2 > C2 )

Why it works, time is a fraction of a day, the comparison B2>C2 returns True (1) or False (0), if true 1 day (24 hours) is added. http://www.excelforum.com/excel-general/471757-calculating-time-difference-over-midnight.html

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

C free(): invalid pointer

You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.

There are two main types of memory you seem to be confusing - stack memory and heap memory.

  • Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main, it sets aside some memory for your variables you've declared (p,token, and so on).

  • Heap memory lives from when you malloc it to when you free it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!

You have a few errors:

  • You're trying to free memory that's not heap memory. Don't do that.

  • You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.

For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).

EDIT: The malloc function does allocate heap memory*.

"9.9.1 The malloc and free Functions

The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."

~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011

EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.

Deleting array elements in JavaScript - delete vs splice

IndexOf accepts also a reference type. Suppose the following scenario:

_x000D_
_x000D_
var arr = [{item: 1}, {item: 2}, {item: 3}];_x000D_
var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]_x000D_
var l = found.length;_x000D_
_x000D_
while(l--) {_x000D_
   var index = arr.indexOf(found[l])_x000D_
      arr.splice(index, 1);_x000D_
   }_x000D_
   _x000D_
console.log(arr.length); //1
_x000D_
_x000D_
_x000D_

Differently:

var item2 = findUnique(2); //will return {item: 2}
var l = arr.length;
var found = false;
  while(!found && l--) {
  found = arr[l] === item2;
}

console.log(l, arr[l]);// l is index, arr[l] is the item you look for

Hiding button using jQuery

You can use the .hide() function bound to a click handler:

$('#Comanda').click(function() {
    $(this).hide();
});

Convert byte to string in Java

You have to construct a new string out of a byte array. The first element in your byteArray should be 0x63. If you want to add any more letters, make the byteArray longer and add them to the next indices.

byte[] byteArray = new byte[1];
byteArray[0] = 0x63;

try {
    System.out.println("string " + new String(byteArray, "US-ASCII"));
} catch (UnsupportedEncodingException e) {
    // TODO: Handle exception.
    e.printStackTrace();
}

Note that specifying the encoding will eventually throw an UnsupportedEncodingException and you must handle that accordingly.

Pass value to iframe from a window

First, you need to understand that you have two documents: The frame and the container (which contains the frame).

The main obstacle with manipulating the frame from the container is that the frame loads asynchronously. You can't simply access it any time, you must know when it has finished loading. So you need a trick. The usual solution is to use window.parent in the frame to get "up" (into the document which contains the iframe tag).

Now you can call any method in the container document. This method can manipulate the frame (for example call some JavaScript in the frame with the parameters you need). To know when to call the method, you have two options:

  1. Call it from body.onload of the frame.

  2. Put a script element as the last thing into the HTML content of the frame where you call the method of the container (left as an exercise for the reader).

So the frame looks like this:

<script>
function init() { window.parent.setUpFrame(); return true; }
function yourMethod(arg) { ... }
</script>
<body onload="init();">...</body>

And the container like this:

<script>
function setUpFrame() { 
    var frame = window.frames['frame-id'];
    frame.yourMethod('hello');
}
</script>
<body><iframe name="frame-id" src="..."></iframe></body>

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

How to split and modify a string in NodeJS?

var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
    arr[i] = ++arr[i];
}

Redirecting to a certain route based on condition

1. Set global current user.

In your authentication service, set the currently authenticated user on the root scope.

// AuthService.js

  // auth successful
  $rootScope.user = user

2. Set auth function on each protected route.

// AdminController.js

.config(function ($routeProvider) {
  $routeProvider.when('/admin', {
    controller: 'AdminController',
    auth: function (user) {
      return user && user.isAdmin
    }
  })
})

3. Check auth on each route change.

// index.js

.run(function ($rootScope, $location) {
  $rootScope.$on('$routeChangeStart', function (ev, next, curr) {
    if (next.$$route) {
      var user = $rootScope.user
      var auth = next.$$route.auth
      if (auth && !auth(user)) { $location.path('/') }
    }
  })
})

Alternatively you can set permissions on the user object and assign each route a permission, then check the permission in the event callback.

Difference between HashSet and HashMap?

Basically in HashMap, user has to provide both Key and Value, whereas in HashSet you provide only Value, the Key is derived automatically from Value by using hash function. So after having both Key and Value, HashSet can be stored as HashMap internally.

java.lang.RuntimeException: Uncompilable source code - what can cause this?

Add selenium-server-standalone-3.4.0.jar. It works to me. Download Link

How to merge 2 JSON objects from 2 files using jq?

Who knows if you still need it, but here is the solution.

Once you get to the --slurp option, it's easy!

--slurp/-s:
    Instead of running the filter for each JSON object in the input,
    read the entire input stream into a large array and run the filter just once.

Then the + operator will do what you want:

jq -s '.[0] + .[1]' config.json config-user.json

(Note: if you want to merge inner objects instead of just overwriting the left file ones with the right file ones, you will need to do it manually)

How to use <md-icon> in Angular Material?

As the other answers didn't address my concern I decided to write my own answer.

The path given in the icon attribute of the md-icon directive is the URL of a .png or .svg file lying somewhere in your static file directory. So you have to put the right path of that file in the icon attribute. p.s put the file in the right directory so that your server could serve it.

Remember md-icon is not like bootstrap icons. Currently they are merely a directive that shows a .svg file.

Update

Angular material design has changed a lot since this question was posted.

Now there are several ways to use md-icon

The first way is to use SVG icons.

<md-icon md-svg-src = '<url_of_an_image_file>'></md-icon>

Example:

<md-icon md-svg-src = '/static/img/android.svg'></md-icon>

or

<md-icon md-svg-src = '{{ getMyIcon() }}'></md-icon>

:where getMyIcon is a method defined in $scope.

or <md-icon md-svg-icon="social:android"></md-icon>

to use this you have to the $mdIconProvider service to configure your application with svg iconsets.

angular.module('appSvgIconSets', ['ngMaterial'])  
  .controller('DemoCtrl', function($scope) {})  
  .config(function($mdIconProvider) {
    $mdIconProvider
      .iconSet('social', 'img/icons/sets/social-icons.svg', 24)
      .defaultIconSet('img/icons/sets/core-icons.svg', 24);    
  });

The second way is to use font icons.

<md-icon md-font-icon="android" alt="android"></md-icon>

<md-icon md-font-icon="fa-magic" class="fa" alt="magic wand"></md-icon>

prior to doing this you have to load the font library like this..

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

or use font icons with ligatures

<md-icon md-font-library="material-icons">face</md-icon>

<md-icon md-font-library="material-icons">#xE87C;</md-icon>

<md-icon md-font-library="material-icons" class="md-light md-48">face</md-icon>

For further details check our

Angular Material mdIcon Directive documentation

$mdIcon Service Documentation

$mdIconProvider Service Documentation

Failed to install *.apk on device 'emulator-5554': EOF

adb is very crazy, after several attempts I found out I was with many devices (emulators and devices) connected , so I removed all devices and it back to work again

jQuery select all except first

My answer is focused to a extended case derived from the one exposed at top.

Suppose you have group of elements from which you want to hide the child elements except first. As an example:

<html>
  <div class='some-group'>
     <div class='child child-0'>visible#1</div>
     <div class='child child-1'>xx</div>
     <div class='child child-2'>yy</div>
  </div>
  <div class='some-group'>
     <div class='child child-0'>visible#2</div>
     <div class='child child-1'>aa</div>
     <div class='child child-2'>bb</div>
  </div>
</html>
  1. We want to hide all .child elements on every group. So this will not help because will hide all .child elements except visible#1:

    $('.child:not(:first)').hide();
    
  2. The solution (in this extended case) will be:

    $('.some-group').each(function(i,group){
        $(group).find('.child:not(:first)').hide();
    });
    

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

Cross join :Cross Joins produce results that consist of every combination of rows from two or more tables. That means if table A has 3 rows and table B has 2 rows, a CROSS JOIN will result in 6 rows. There is no relationship established between the two tables – you literally just produce every possible combination.

Full outer Join : A FULL OUTER JOIN is neither "left" nor "right"— it's both! It includes all the rows from both of the tables or result sets participating in the JOIN. When no matching rows exist for rows on the "left" side of the JOIN, you see Null values from the result set on the "right." Conversely, when no matching rows exist for rows on the "right" side of the JOIN, you see Null values from the result set on the "left."

Get text from pressed button

If you're sure that the OnClickListener instance is applied to a Button, then you could just cast the received view to a Button and get the text:

public void onClick(View view){
Button b = (Button)view;
String text = b.getText().toString();
}

What's the difference between a method and a function?

'method' is the object-oriented word for 'function'. That's pretty much all there is to it (ie., no real difference).

Unfortunately, I think a lot of the answers here are perpetuating or advancing the idea that there's some complex, meaningful difference.

Really - there isn't all that much to it, just different words for the same thing.

[late addition]


In fact, as Brian Neal pointed out in a comment to this question, the C++ standard never uses the term 'method' when refering to member functions. Some people may take that as an indication that C++ isn't really an object-oriented language; however, I prefer to take it as an indication that a pretty smart group of people didn't think there was a particularly strong reason to use a different term.

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());

This works for me.

Using an image caption in Markdown Jekyll

If you don't want to use any plugins (which means you can push it to GitHub directly without generating the site first), you can create a new file named image.html in _includes:

<figure class="image">
  <img src="{{ include.url }}" alt="{{ include.description }}">
  <figcaption>{{ include.description }}</figcaption>
</figure>

And then display the image from your markdown with:

{% include image.html url="/images/my-cat.jpg" description="My cat, Robert Downey Jr." %}

What are all the escape characters?

These are escape characters which are used to manipulate string.

\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a form feed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

Read more about them from here.

http://docs.oracle.com/javase/tutorial/java/data/characters.html

How do I use the conditional operator (? :) in Ruby?

The code condition ? statement_A : statement_B is equivalent to

if condition == true
  statement_A
else
  statement_B
end

anaconda - graphviz - can't import after installation

I am using anaconda for the same.

I installed graphviz using conda install graphviz in anaconda prompt. and then installed pip install graphviz in the same command prompt. It worked for me.

How to make a cross-module variable?

Global variables are usually a bad idea, but you can do this by assigning to __builtins__:

__builtins__.foo = 'something'
print foo

Also, modules themselves are variables that you can access from any module. So if you define a module called my_globals.py:

# my_globals.py
foo = 'something'

Then you can use that from anywhere as well:

import my_globals
print my_globals.foo

Using modules rather than modifying __builtins__ is generally a cleaner way to do globals of this sort.

Detect If Browser Tab Has Focus

Surprising to see nobody mentioned document.hasFocus

if (document.hasFocus()) console.log('Tab is active')

MDN has more information.

Can I use break to exit multiple nested 'for' loops?

A code example using goto and a label to break out of a nested loop:

for (;;)
  for (;;)
    goto theEnd;
theEnd:

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

Array.push() if does not exist?

Like this?

var item = "Hello World";
var array = [];
if (array.indexOf(item) === -1) array.push(item);

With object

var item = {name: "tom", text: "tasty"}
var array = [{}]
if (!array.find(o => o.name === 'tom' && o.text === 'tasty'))
    array.push(item)

Let JSON object accept bytes or let urlopen output strings

I used below program to use of json.loads()

import urllib.request
import json
endpoint = 'https://maps.googleapis.com/maps/api/directions/json?'
api_key = 'AIzaSyABbKiwfzv9vLBR_kCuhO7w13Kseu68lr0'
origin = input('where are you ?').replace(' ','+')
destination = input('where do u want to go').replace(' ','+')
nav_request = 'origin={}&destination={}&key={}'.format(origin,destination,api_key)
request = endpoint + nav_request
response = urllib.request.urlopen(request).read().decode('utf-8')
directions = json.loads(response)
print(directions)

java.util.zip.ZipException: error in opening zip file

In my case SL4j-api.jar with multiple versions are conflicting in the maven repo. Than I deleted the entire SL4j-api folder in m2 maven repo and updated maven project, build maven project than ran the project in JBOSS server. issue got resolved.

Declare a variable as Decimal

The best way is to declare the variable as a Single or a Double depending on the precision you need. The data type Single utilizes 4 Bytes and has the range of -3.402823E38 to 1.401298E45. Double uses 8 Bytes.

You can declare as follows:

Dim decAsdf as Single

or

Dim decAsdf as Double

Here is an example which displays a message box with the value of the variable after calculation. All you have to do is put it in a module and run it.

Sub doubleDataTypeExample()
Dim doubleTest As Double


doubleTest = 0.0000045 * 0.005 * 0.01

MsgBox "doubleTest = " & doubleTest
End Sub

how does unix handle full path name with space and arguments?

I would also like to point out that in case you are using command line arguments as part of a shell script (.sh file), then within the script, you would need to enclose the argument in quotes. So if your command looks like

>scriptName.sh arg1 arg2

And arg1 is your path that has spaces, then within the shell script, you would need to refer to it as "$arg1" instead of $arg1

Here are the details

What does -1 mean in numpy reshape?

It simply means that you are not sure about what number of rows or columns you can give and you are asking numpy to suggest number of column or rows to get reshaped in.

numpy provides last example for -1 https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

check below code and its output to better understand about (-1):

CODE:-

import numpy
a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
print("Without reshaping  -> ")
print(a)
b = numpy.reshape(a, -1)
print("HERE We don't know about what number we should give to row/col")
print("Reshaping as (a,-1)")
print(b)
c = numpy.reshape(a, (-1,2))
print("HERE We just know about number of columns")
print("Reshaping as (a,(-1,2))")
print(c)
d = numpy.reshape(a, (2,-1))
print("HERE We just know about number of rows")
print("Reshaping as (a,(2,-1))")
print(d)

OUTPUT :-

Without reshaping  -> 
[[1 2 3 4]
 [5 6 7 8]]
HERE We don't know about what number we should give to row/col
Reshaping as (a,-1)
[[1 2 3 4 5 6 7 8]]
HERE We just know about number of columns
Reshaping as (a,(-1,2))
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
HERE We just know about number of rows
Reshaping as (a,(2,-1))
[[1 2 3 4]
 [5 6 7 8]]