Programs & Examples On #Prism

Prism is a framework for building loosely coupled, maintainable, and testable XAML applications in WPF, Windows 10 UWP, and Xamarin Forms.

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

Buddy,
If every this is up-to-date, even then you are having this problem, then
try running this command from the terminal directly instead of running from eclipse.
$ mvn clean install

and make sure these things:

  • maven is in system path
  • all maven dependencies are avaialble at `.m2/repository`
  • java is in system path


How to solve java.lang.NoClassDefFoundError?

I'm developing an Eclipse based application also known as RCP (Rich Client Platform). And I have been facing this problem after refactoring (moving one class from an plugIn to a new one).

Cleaning the project and Maven update didn't help.

The problem was caused by the Bundle-Activator which haven't been updated automatically. Manual update of the Bundle-Activator under MANIFEST.MF in the new PlugIn has fixed my problem.

How do I use a pipe to redirect the output of one command to the input of another?

Try this. Copy this into a batch file - such as send.bat - and then simply run send.bat to send the message from the temperature program to the prismcom program.

temperature.exe > msg.txt
set /p msg= < msg.txt
prismcom.exe usb "%msg%"

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

There is not official api support which means that it is not documented for the public and the libraries may change at any time. I realize you don't want to leave the application but here's how you do it with an intent for anyone else wondering.

public void sendData(int num){
    String fileString = "..."; //put the location of the file here
    Intent mmsIntent = new Intent(Intent.ACTION_SEND);
    mmsIntent.putExtra("sms_body", "text");
    mmsIntent.putExtra("address", num);
    mmsIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(fileString)));
    mmsIntent.setType("image/jpeg");
    startActivity(Intent.createChooser(mmsIntent, "Send"));

}

I haven't completely figured out how to do things like track the delivery of the message but this should get it sent.

You can be alerted to the receipt of mms the same way as sms. The intent filter on the receiver should look like this.

<intent-filter>
    <action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
    <data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>

XCOPY switch to create specified directory if it doesn't exist?

Try /E

To get a full list of options: xcopy /?

Passing multiple argument through CommandArgument of Button in Asp.net

A little more elegant way of doing the same adding on to the above comment ..

<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
                           AutoGenerateColumns="false"
                            OnRowDeleting="deleteRow"
                         GridLines="Vertical">
      <asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
      <asp:BoundField DataField="EntityId" HeaderText="EntityId"  />
    <asp:TemplateField ShowHeader="false">
        <ItemTemplate>
           <asp:LinkButton ID="lnkCustomize" Text="Delete"  CommandName="Delete"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
           </asp:LinkButton>   
        </ItemTemplate>   
    </asp:TemplateField>
     </asp:GridView>

And on the server side:

protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
    string IdTemplate= e.Values["IdTemplate"].ToString();
    string EntityId = e.Values["EntityId"].ToString();

   // Do stuff..
}

Unable to ping vmware guest from another vmware guest

  1. Make network setting as Bridged.
  2. Enable VMCI (this enables hosts , guests to communicate with each other)

Expand and collapse with angular js

I just wrote a simple zippy/collapsable using Angular using ng-show, ng-click and ng-init. Its implemented to one level but can be expanded to multiple levels easily.

Assign a boolean variable to ng-show and toggle it on click of header.

Check it out here enter image description here

How to export settings?

Often there are questions about the java settings in vsCode. This is a big question and can involve advanced user knowledge to accmplish. But there is simple way to get the existing java settings from vsCode and copy these setting for use on another PC. This post is using recent versions of vsCode and JDK in mid-December 2020.

There are several screen shots (below) that accompany this post which should provide enough information for the visual learners.

First things first, open vsCode and either open an existing java folder-file or create a new java file in vsCode. Then look at the lower right corner of vsCode (on the blue command bar). The vsCode should be displaying an icon showing the version of the Java Standard Edition ( Java SE ) being used. The version being on this PC today is JavaSE-15. (link 1)

Click on that icon (JAVASE-15) which then opens a new window named "java.configuration.runtimes". There should be two tabs below this name: User and Workspace. Below these tabs is a link named, "Edit in settings.json". Click on that link. (link 2)

Two json files should then open: Default settings and settings.json. This post only focuses on the "settings.json" file. The settings.json file shows various settings used for coding different programming languages (Python, R, and java). Near the bottom of the settings.json file shows the settings this User uses in vsCode for programming java.

These java settings are the settings that can be "backed up" - meaning these settings get copied and pasted to another PC for creating a java programming environment similar to the java programming environment on this PC. (link 3)

link 1

link 2

link 3

mongodb count num of distinct values per field/key

You can leverage on Mongo Shell Extensions. It's a single .js import that you can append to your $HOME/.mongorc.js, or programmatically, if you're coding in Node.js/io.js too.

Sample

For each distinct value of field counts the occurrences in documents optionally filtered by query

> db.users.distinctAndCount('name', {name: /^a/i})

{
  "Abagail": 1,
  "Abbey": 3,
  "Abbie": 1,
  ...
}

The field parameter could be an array of fields

> db.users.distinctAndCount(['name','job'], {name: /^a/i})

{
  "Austin,Educator" : 1,
  "Aurelia,Educator" : 1,
  "Augustine,Carpenter" : 1,
  ...
}

How to change the status bar background color and text color on iOS 7?

Swift code

            let statusBarView = UIView(frame: CGRect(x: 0, y: 0, width: view.width, height: 20.0))
            statusBarView.backgroundColor = UIColor.red
            self.navigationController?.view.addSubview(statusBarView)

Access Form - Syntax error (missing operator) in query expression

Try making the field names legal by removing spaces. It's a long shot but it has actually helped me before.

Truncate (not round) decimal places in SQL Server

ROUND(number, decimals, operation)

number => Required. The number to be rounded
decimals => Required. The number of decimal places to round number to
operation => Optional. If 0, it rounds the result to the number of decimal. If another value than 0, it truncates the result to the number of decimals. Default value is 0

SELECT ROUND(235.415, 2, 1)

will give you 235.410

SELECT ROUND(235.415, 0, 1)

will give you 235.000

But now trimming0 you can use cast

SELECT CAST(ROUND(235.415, 0, 1) AS INT)

will give you 235

Telling gcc directly to link a library statically

It is possible of course, use -l: instead of -l. For example -l:libXYZ.a to link with libXYZ.a. Notice the lib written out, as opposed to -lXYZ which would auto expand to libXYZ.

Hide options in a select list using jQuery

This works in Firefox 3.0, but not in MSIE 8, nor in Opera 9.62:

jQuery('#destinations').children('option[value="1"]').hide();
jQuery('#destinations').children('option[value="1"]').css('display','none');

But rather hiding an option, one can simply disable it:

jQuery('#destinations').val('2'); 
jQuery('#destinations').children('option[value="1"]').attr('disabled','disabled');

The first of the the two lines above is for Firefox and pass focus to the 2nd option (assuming it has value="2"). If we omit it, the option is disabled, but the still displays the "enabled" option before we drop it down. Hence, we pass focus to another option to avoid this.

How to open mail app from Swift

You can use simple mailto: links in iOS to open the mail app.

let email = "[email protected]"
if let url = URL(string: "mailto:\(email)") {
  if #available(iOS 10.0, *) {
    UIApplication.shared.open(url)
  } else {
    UIApplication.shared.openURL(url)
  }    
}

Scroll back to the top of scrollable div

This worked for me :

document.getElementById('yourDivID').scrollIntoView();

Sort array of objects by object fields

reference answer of Demodave to eating multi key

 function array_sort_by(array $arr, $keys){

    if(!is_array($keys))
        $keyList = explode(',', $keys);
    $keyList = array_keys(array_flip($keyList)); // array_unique 
    $keyList = array_reverse($keyList);

    $result = &$arr;
    foreach ($keyList as $key) {
        if(array_key_exists($key, $arr))
            $result = usort($result, function($a, $b) use ($key) { return strcmp($a->{$key}, $b->{$key}); });
    }
    return $result;
}

Angular2 *ngIf check object array length in template

<div class="row" *ngIf="teamMembers?.length > 0">

This checks first if teamMembers has a value and if teamMembers doesn't have a value, it doesn't try to access length of undefined because the first part of the condition already fails.

How to ping multiple servers and return IP address and Hostnames using batch script?

Well, it's unfortunate that you didn't post your own code too, so that it could be corrected.
Anyway, here's my own solution to this:

@echo off
setlocal enabledelayedexpansion

set OUTPUT_FILE=result.txt
>nul copy nul %OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
    set SERVER_ADDRESS=ADDRESS N/A
    for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
        if %%x==Pinging set SERVER_ADDRESS=%%y
        if %%x==Reply set SERVER_ADDRESS=%%z
        if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
)

The outer loop iterates through the hosts and the inner loop parses the ping output. The first two if statements handle the two possible cases of IP address resolution:

  1. The host name is the host IP address.
  2. The host IP address can be resolved from its name.

If the host IP address cannot be resolved, the address is set to "ADDRESS N/A".

Hope this helps.

How does lock work exactly?

Its simpler than you think.

According to Microsoft: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

The lock keyword calls Enter at the start of the block and Exit at the end of the block. lock keyword actually handles Monitor class at back end.

For example:

private static readonly Object obj = new Object();

lock (obj)
{
    // critical section
}

In the above code, first the thread enters a critical section, and then it will lock obj. When another thread tries to enter, it will also try to lock obj, which is already locked by the first thread. Second thread will have to wait for the first thread to release obj. When the first thread leaves, then another thread will lock obj and will enter the critical section.

How to parse XML using shellscript?

A rather new project is the xml-coreutils package featuring xml-cat, xml-cp, xml-cut, xml-grep, ...

http://xml-coreutils.sourceforge.net/contents.html

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

How to use WPF Background Worker

using System;  
using System.ComponentModel;   
using System.Threading;    
namespace BackGroundWorkerExample  
{   
    class Program  
    {  
        private static BackgroundWorker backgroundWorker;  

        static void Main(string[] args)  
        {  
            backgroundWorker = new BackgroundWorker  
            {  
                WorkerReportsProgress = true,  
                WorkerSupportsCancellation = true  
            };  

            backgroundWorker.DoWork += backgroundWorker_DoWork;  
            //For the display of operation progress to UI.    
            backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;  
            //After the completation of operation.    
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;  
            backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");  

            Console.ReadLine();  

            if (backgroundWorker.IsBusy)  
            { 
                backgroundWorker.CancelAsync();  
                Console.ReadLine();  
            }  
        }  

        static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)  
        {  
            for (int i = 0; i < 200; i++)  
            {  
                if (backgroundWorker.CancellationPending)  
                {  
                    e.Cancel = true;  
                    return;  
                }  

                backgroundWorker.ReportProgress(i);  
                Thread.Sleep(1000);  
                e.Result = 1000;  
            }  
        }  

        static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
        {  
            Console.WriteLine("Completed" + e.ProgressPercentage + "%");  
        }  

        static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
        {  

            if (e.Cancelled)  
            {  
                Console.WriteLine("Operation Cancelled");  
            }  
            else if (e.Error != null)  
            {  
                Console.WriteLine("Error in Process :" + e.Error);  
            }  
            else  
            {  
                Console.WriteLine("Operation Completed :" + e.Result);  
            }  
        }  
    }  
} 

Also, referr the below link you will understand the concepts of Background:

http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/

Refresh Part of Page (div)

$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request. among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .

boto3 client NoRegionError: You must specify a region error only sometimes

you can also set environment variables in the script itself, rather than passing region_name parameter

os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'

case sensitivity may matter.

What's the best way to select the minimum value from several columns?

SELECT ID, Col1, Col2, Col3, 
    (SELECT MIN(Col) FROM (VALUES (Col1), (Col2), (Col3)) AS X(Col)) AS TheMin
FROM Table

Get value of div content using jquery

$('#field-function_purpose') will get you the element with ID field-function_purpose, which is your div element. text() returns you the content of the div.

var x = $('#field-function_purpose').text();

add new row in gridview after binding C#, ASP.net

If you are using dataset to bind in a Grid, you can add the row after you fill in the sql data adapter:

adapter.Fill(ds);
ds.Tables(0).Rows.Add();

Changing project port number in Visual Studio 2013

This has proved to be elusive for me (WebSite Project) until I figured out the following procedure, which combines the solution provided by @Jimmy, with the added step of checking out the solution from Source Control

Steps: (if using VS2013+ with website project and SourceControl)

  1. Check out the Solution file only (from sourceControl) (this can be tricky. the easiest way to do this is to make a small change in the Solution file properties/settings and then undo if necessary)
  2. Locate the solution file (e.g. solution.sln) in exploer, and open in text editor.
  3. Locate the entry: VWDPort = ...... and change to desired port: (example: "60000" - depends on your IISExpress Settings)
  4. save the change (will prompt to reload solution)

TCPDF output without saving file

This is what I found out in the documentation.

  • I : send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.
  • D : send to the browser and force a file download with the name given by name.
  • F : save to a local server file with the name given by name.
  • S : return the document as a string (name is ignored).
  • FI : equivalent to F + I option
  • FD : equivalent to F + D option
  • E : return the document as base64 mime multi-part email attachment (RFC 2045)

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

We released a package, roperators, to help with this kind of thing. You can read more about it here: https://happylittlescripts.blogspot.com/2018/09/make-your-r-code-nicer-with-roperators.html

install.packages('roperators')
require(roperators)

x <- 1:3
x %+=% 1; x
x %-=% 3; x
y <- c('a', 'b', 'c')
y %+=% 'text'; y
y %-=% 'text'; y

# etc

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

PHP display current server path

echo $_SERVER["DOCUMENT_ROOT"];

'DOCUMENT_ROOT' The document root directory under which the current script is executing, as defined in the server's configuration file.

http://php.net/manual/en/reserved.variables.server.php

How do I completely rename an Xcode project (i.e. inclusive of folders)?

There is a GitHub project called Xcode Project Renamer:

It should be executed from inside root of Xcode project directory and called with two string parameters: $OLD_PROJECT_NAME & $NEW_PROJECT_NAME

Script goes through all the files and directories recursively, including Xcode project or workspace file and replaces all occurrences of $OLD_PROJECT_NAME string with $NEW_PROJECT_NAME string (both in each file's name and content).

DON'T FORGET TO BACKUP YOUR PROJECT!

Xcode Project Renamer

Html table tr inside td

Just add a new table in the td you want. Example: http://jsfiddle.net/AbE3Q/

_x000D_
_x000D_
<table border="1">
  <tr>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
  </tr>
  <tr>
    <td>Item1</td>
    <td>Item2</td>
    <td>
      <table border="1">
        <tr>
          <td>qweqwewe</td>
          <td>qweqwewe</td>
        </tr>
        <tr>
          <td>qweqwewe</td>
          <td>qweqwewe</td>
        </tr>
        <tr>
          <td>qweqwewe</td>
          <td>qweqwewe</td>
        </tr>
      </table>
    </td>
    <td>Item3</td>
  </tr>
  <tr>
  </tr>
  <tr>
  </tr>
  <tr>
  </tr>
  <tr>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

ORA-01843 not a valid month- Comparing Dates

You are comparing a date column to a string literal. In such a case, Oracle attempts to convert your literal to a date, using the default date format. It's a bad practice to rely on such a behavior, as this default may change if the DBA changes some configuration, Oracle breaks something in a future revision, etc.

Instead, you should always explicitly convert your literal to a date and state the format you're using:

SELECT * FROM MYTABLE WHERE MYTABLE.DATEIN = TO_DATE('23/04/49','MM/DD/YY');

how do I loop through a line from a csv file in powershell

A slightly other way of iterating through each column of each line of a CSV-file would be

$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path

foreach($line in $csv)
{ 
    $properties = $line | Get-Member -MemberType Properties
    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $columnvalue = $line | Select -ExpandProperty $column.Name

        # doSomething $column.Name $columnvalue 
        # doSomething $i $columnvalue 
    }
} 

so you have the choice: you can use either $column.Name to get the name of the column, or $i to get the number of the column

Why does python use 'else' after for and while loops?

The easiest way I found to 'get' what the for/else did, and more importantly, when to use it, was to concentrate on where the break statement jumps to. The For/else construct is a single block. The break jumps out of the block, and so jumps 'over' the else clause. If the contents of the else clause simply followed the for clause, it would never be jumped over, and so the equivalent logic would have to be provided by putting it in an if. This has been said before, but not quite in these words, so it may help somebody else. Try running the following code fragment. I'm wholeheartedly in favour of the 'no break' comment for clarity.

for a in range(3):
    print(a)
    if a==4: # change value to force break or not
        break
else: #no break  +10 for whoever thought of this decoration
    print('for completed OK')

print('statement after for loop')

Reporting Services export to Excel with Multiple Worksheets

To late for the original asker of the question, but with SQL Server 2008 R2 this is now possible:

Set the property "Pagebreak" on the tablix or table or other element to force a new tab, and then set the property "Pagename" on both the element before the pagebreak and the element after the pagebreak. These names will appear on the tabs when the report is exported to Excel.

Read about it here: http://technet.microsoft.com/en-us/library/dd255278.aspx

How to link a folder with an existing Heroku app

for existing repository

type in terminal

$ heroku git:remote -a example

enter image description here

Youtube autoplay not working on mobile devices with embedded HTML5 player

Have a look on code below. Tested and found working on Mobile and Tablet devices.

<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

What is the maximum size of a web browser's cookie's key?

Not completely entirely a direct answer to the original question, but relevant for the curious quickly trying to visually understand their cookie information storage planning without implementing a complex limiter algorithm, this string is 4096 ASCII character bytes:

"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn"

Switch in Laravel 5 - Blade

To overcome the space in 'switch ()', you can use code :

Blade::extend(function($value, $compiler){
    $value = preg_replace('/(\s*)@switch[ ]*\((.*)\)(?=\s)/', '$1<?php switch($2):', $value);
    $value = preg_replace('/(\s*)@endswitch(?=\s)/', '$1endswitch; ?>', $value);
    $value = preg_replace('/(\s*)@case[ ]*\((.*)\)(?=\s)/', '$1case $2: ?>', $value);
    $value = preg_replace('/(?<=\s)@default(?=\s)/', 'default: ?>', $value);
    $value = preg_replace('/(?<=\s)@breakswitch(?=\s)/', '<?php break;', $value);
    return $value;
  });

Shortcut to Apply a Formula to an Entire Column in Excel

Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).

Reading a registry key in C#

You're looking for the cunningly named Registry.GetValue method.

Count number of rows by group using dplyr

There's a special function n() in dplyr to count rows (potentially within groups):

library(dplyr)
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(n = n())
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

But dplyr also offers a handy count function which does exactly the same with less typing:

count(mtcars, cyl, gear)          # or mtcars %>% count(cyl, gear)
#Source: local data frame [8 x 3]
#Groups: cyl [?]
#
#    cyl  gear     n
#  (dbl) (dbl) (int)
#1     4     3     1
#2     4     4     8
#3     4     5     2
#4     6     3     2
#5     6     4     4
#6     6     5     1
#7     8     3    12
#8     8     5     2

Jquery function return value

I'm not entirely sure of the general purpose of the function, but you could always do this:

function getMachine(color, qty) {
    var retval;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            retval = thisArray[3];
            return false;
        }
    });
    return retval;
}

var retval = getMachine(color, qty);

how to call a variable in code behind to aspx page

I would create a property to access the variable, like this:

protected string Test
{
    get; set;
}

And in your markup:

<%= this.Test %>

Enter key pressed event handler

The KeyDown event only triggered at the standard TextBox or MaskedTextBox by "normal" input keys, not ENTER or TAB and so on.

One can get special keys like ENTER by overriding the IsInputKey method:

public class CustomTextBox : System.Windows.Forms.TextBox
{
    protected override bool IsInputKey(Keys keyData)
    {
        if (keyData == Keys.Return)
            return true;
        return base.IsInputKey(keyData);
    }
}

Then one can use the KeyDown event in the following way:

CustomTextBox ctb = new CustomTextBox();
ctb.KeyDown += new KeyEventHandler(tb_KeyDown);

private void tb_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
          //Enter key is down

          //Capture the text
          if (sender is TextBox)
          {
              TextBox txb = (TextBox)sender;
              MessageBox.Show(txb.Text);
          }
    }
}

Is it possible to change a UIButtons background color?

[myButton setBackgroundColor:[UIColor blueColor]]; [myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

It's possible change this way or going on Storyboard and change background on options in right side.

HashMap - getting First Key value

To get the "first" value:

map.values().toArray()[0]

To get the value of the "first" key:

map.get(map.keySet().toArray()[0])

Note: Above code tested and works.

I say "first" because HashMap entries are not ordered.

However, a LinkedHashMap iterates its entries in the same order as they were inserted - you could use that for your map implementation if insertion order is important.

Import Excel Data into PostgreSQL 9.3

You can also use psql console to execute \copy without need to send file to Postgresql server machine. The command is the same:

\copy mytable [ ( column_list ) ] FROM '/path/to/csv/file' WITH CSV HEADER

How can I do GUI programming in C?

Use win APIs in your main function:

  1. RegisterClassEx() note: you have to provide a pointer to a function (usually called WndProc) which handles windows messages such as WM_CREATE, WM_COMMAND etc
  2. CreateWindowEx()
  3. ShowWindow()
  4. UpdateWindow()

Then write another function which handles win's messages (mentioned in #1). When you receive the message WM_CREATE you have to call CreateWindow(). The class is what control is that window, for example "edit" is a text box and "button" is a.. button :). You have to specify an ID for each control (of your choice but unique among all). CreateWindow() returns a handle to that control, which needs to be memorized. When the user clicks on a control you receive the WM_COMMAND message with the ID of that control. Here you can handle that event. You might find useful SetWindowText() and GetWindowText() which allows you to set/get the text of any control.
You will need only the win32 SDK. You can get it here.

App.Config change value

In addition to the answer by fenix2222 (which worked for me) I had to modify the last line to:

config.Save(ConfigurationSaveMode.Modified);

Without this, the new value was still being written to the config file but the old value was retrieved when debugging.

How to use ternary operator in razor (specifically on HTML attributes)?

I have a field named IsActive in table rows that's True when an item has been deleted. This code applies a CSS class named strikethrough only to deleted items. You can see how it uses the C# Ternary Operator:

<tr class="@(@businesstypes.IsActive ? "" : "strikethrough")">

Check if a JavaScript string is a URL

A related question with an answer:

Javascript regex URL matching

Or this Regexp from Devshed:

function validURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
    '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return !!pattern.test(str);
}

REACT - toggle class onclick

Just wanted to add my approach. Using hooks and context provider.

Nav.js

function NavBar() {
  const filterDispatch = useDispatchFilter()
  const {filter} = useStateFilter()
  const activeRef = useRef(null)
  const completeRef = useRef(null)
  const cancelRef = useRef(null)

  useEffect(() => {
    let activeClass = '';
    let completeClass = '';
    let cancelClass = '';
    if(filter === ACTIVE_ORDERS){
      activeClass='is-active'
    }else if ( filter === COMPLETE_ORDERS ){
      completeClass='is-active'
    }else if(filter === CANCEL_ORDERS ) {
      cancelClass='is-active'
    }
    activeRef.current.className = activeClass
    completeRef.current.className = completeClass
    cancelRef.current.className = cancelClass
  }, [filter])

  return (
    <div className="tabs is-centered">
      <ul>
        <li ref={activeRef}>
          <button
            className="button-base"
            onClick={() => filterDispatch({type: 'FILTER_ACTIVE'})}
          >
            Active
          </button>
        </li>

        <li ref={completeRef}>
          <button
            className="button-base"
            onClick={() => filterDispatch({type: 'FILTER_COMPLETE'})}
          >
            Complete
          </button>
        </li>
        <li ref={cancelRef}>
          <button
            className={'button-base'}
            onClick={() => filterDispatch({type: 'FILTER_CANCEL'})}
          >
            Cancel
          </button>
        </li>
      </ul>
    </div>
  )
}

export default NavBar

filterContext.js

export const ACTIVE_ORDERS = [
  "pending",
  "assigned",
  "pickup",
  "warning",
  "arrived",
]
export const COMPLETE_ORDERS = ["complete"]
export const CANCEL_ORDERS = ["cancel"]

const FilterStateContext = createContext()
const FilterDispatchContext = createContext()

export const FilterProvider = ({ children }) => {
  const [state, dispatch] = useReducer(FilterReducer, { filter: ACTIVE_ORDERS })
  return (
    <FilterStateContext.Provider value={state}>
      <FilterDispatchContext.Provider value={dispatch}>
        {children}
      </FilterDispatchContext.Provider>
    </FilterStateContext.Provider>
  )
}
export const useStateFilter = () => {
  const context = useContext(FilterStateContext)
  if (context === undefined) {
    throw new Error("place useStateMap within FilterProvider")
  }
  return context
}
export const useDispatchFilter = () => {
  const context = useContext(FilterDispatchContext)
  if (context === undefined) {
    throw new Error("place useDispatchMap within FilterProvider")
  }
  return context
}


export const FilterReducer = (state, action) => {
  switch (action.type) {
    case "FILTER_ACTIVE":
      return {
        ...state,
        filter: ACTIVE_ORDERS,
      }
    case "FILTER_COMPLETE":
      return {
        ...state,
        filter: COMPLETE_ORDERS,
      }
    case "FILTER_CANCEL":
      return {
        ...state,
        filter: CANCEL_ORDERS,
      }
  }
  return state
}

Works fast, and replaces redux.

Asyncio.gather vs asyncio.wait

asyncio.wait is more low level than asyncio.gather.

As the name suggests, asyncio.gather mainly focuses on gathering the results. It waits on a bunch of futures and returns their results in a given order.

asyncio.wait just waits on the futures. And instead of giving you the results directly, it gives done and pending tasks. You have to manually collect the values.

Moreover, you could specify to wait for all futures to finish or just the first one with wait.

How to use LINQ Distinct() with multiple fields

Answering the headline of the question (what attracted people here) and ignoring that the example used anonymous types....

This solution will also work for non-anonymous types. It should not be needed for anonymous types.

Helper class:

/// <summary>
/// Allow IEqualityComparer to be configured within a lambda expression.
/// From https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer
/// </summary>
/// <typeparam name="T"></typeparam>
public class LambdaEqualityComparer<T> : IEqualityComparer<T>
{
    readonly Func<T, T, bool> _comparer;
    readonly Func<T, int> _hash;

    /// <summary>
    /// Simplest constructor, provide a conversion to string for type T to use as a comparison key (GetHashCode() and Equals().
    /// https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer, user "orip"
    /// </summary>
    /// <param name="toString"></param>
    public LambdaEqualityComparer(Func<T, string> toString)
        : this((t1, t2) => toString(t1) == toString(t2), t => toString(t).GetHashCode())
    {
    }

    /// <summary>
    /// Constructor.  Assumes T.GetHashCode() is accurate.
    /// </summary>
    /// <param name="comparer"></param>
    public LambdaEqualityComparer(Func<T, T, bool> comparer)
        : this(comparer, t => t.GetHashCode())
    {
    }

    /// <summary>
    /// Constructor, provide a equality comparer and a hash.
    /// </summary>
    /// <param name="comparer"></param>
    /// <param name="hash"></param>
    public LambdaEqualityComparer(Func<T, T, bool> comparer, Func<T, int> hash)
    {
        _comparer = comparer;
        _hash = hash;
    }

    public bool Equals(T x, T y)
    {
        return _comparer(x, y);
    }

    public int GetHashCode(T obj)
    {
        return _hash(obj);
    }    
}

Simplest usage:

List<Product> products = duplicatedProducts.Distinct(
    new LambdaEqualityComparer<Product>(p =>
        String.Format("{0}{1}{2}{3}",
            p.ProductId,
            p.ProductName,
            p.CategoryId,
            p.CategoryName))
        ).ToList();

The simplest (but not that efficient) usage is to map to a string representation so that custom hashing is avoided. Equal strings already have equal hash codes.

Reference:
Wrap a delegate in an IEqualityComparer

Find and replace strings in vim on multiple lines

The :&& command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):

:6,10s/<search_string>/<replace_string>/g | 14,18&&

If you have many ranges though, I'd rather use a loop:

:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor

Cannot open include file with Visual Studio

I found this post because I was having the same error in Microsoft Visual C++. (Though it seems it's cause was a little different, than the above posted question.)

I had placed the file, I was trying to include, in the same directory, but it still could not be found.

My include looked like this: #include <ftdi.h>

But When I changed it to this: #include "ftdi.h" then it found it.

How to clear Flutter's Build cache?

I tried flutter clean and that didn't work for me. Then I went to wipe the emulator's data and voila, the cached issue was gone. If you have Android Studio you can launch the AVD Manager by following this Create and Manage virtual machine. Otherwise you can wipe the emulator's data using the emulator.exe command line that's included in the android SDK. Simply follow this instructions here Start the emulator from the command line.

set pythonpath before import statements

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

run: python loop.py &

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

A note on importing

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

"Unable to locate tools.jar" when running ant

There are two directories that looks like JDK.

  C:\Program Files\Java\jdk1.7.0_02
  C:\Program Files (x86)\Java\jdk1.7.0_02\

This may be due to both 64 bit and 32 bit JDK installed? What ever may be the case, the java.exe seen by ant.bat should from the JDK. If the JRE's java.exe comes first in the path, that will be used to guess the JDK location.

Put 'C:\Program Files (x86)\Java\jdk1.7.0_02\bin' or 'C:\Program Files\Java\jdk1.7.0_02' as the first argument in the path.

Further steps:

You can take output of ant -diagnostics and look for interesting keys. (assuming Sun/Oracle JDK).

 java.class.path 
 java.library.path
 sun.boot.library.path

(in my case tools.jar appears in java.class.path)

A better way to check if a path exists or not in PowerShell

Add the following aliases. I think these should be made available in PowerShell by default:

function not-exist { -not (Test-Path $args) }
Set-Alias !exist not-exist -Option "Constant, AllScope"
Set-Alias exist Test-Path -Option "Constant, AllScope"

With that, the conditional statements will change to:

if (exist $path) { ... }

and

if (not-exist $path) { ... }
if (!exist $path) { ... }

Android sqlite how to check if a record exists

Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:

  public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
    String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
    return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
  }

How to change the project in GCP using CLI commands

For what its worth if you have a more than a handful of projects, which I do, use:

gcloud init

This will list all your projects and give you the option to change current project settings, add a new project configuration or switch:

Pick configuration to use:
 [1] Re-initialize this configuration [esqimo-preprod] with new settings
 [2] Create a new configuration
 [3] Switch to and re-initialize existing configuration: [default]
 [4] Switch to and re-initialize existing configuration: [project 1]
 [5] Switch to and re-initialize existing configuration: [project 2]
Please enter your numeric choice:

It will always ask you to login and display options for different google accounts that you may have.

Given that I manage multiple organisations and projects this approach lets' me to simply switch between them.

What is the difference between a framework and a library?

A library performs specific, well-defined operations.

A framework is a skeleton where the application defines the "meat" of the operation by filling out the skeleton. The skeleton still has code to link up the parts but the most important work is done by the application.

Examples of libraries: Network protocols, compression, image manipulation, string utilities, regular expression evaluation, math. Operations are self-contained.

Examples of frameworks: Web application system, Plug-in manager, GUI system. The framework defines the concept but the application defines the fundamental functionality that end-users care about.

check all socket opened in linux OS

You can use netstat command

netstat --listen

To display open ports and established TCP connections,

netstat -vatn

To display only open UDP ports try the following command:

netstat -vaun

jQuery: How to get the event object in an event handler function without passing it as an argument?

Write your event handler declaration like this:

<a href="#" onclick="myFunc(event,1,2,3)">click</a>

Then your "myFunc()" function can access the event.

The string value of the "onclick" attribute is converted to a function in a way that's almost exactly the same as the browser (internally) calling the Function constructor:

theAnchor.onclick = new Function("event", theOnclickString);

(except in IE). However, because "event" is a global in IE (it's a window attribute), you'll be able to pass it to the function that way in any browser.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

For anyone using MySQL:

If you head into your PHPMYADMIN webpage and navigate to the table that has the foreign key you want to update, all you have to do is click the Relational view located in the Structure tab and change the On delete select menu option to Cascade.

Image shown below:

enter image description here

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:

void testAbc(){
     myClass.myObj = myInteface;
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

although it would be a wiser choice to extract all initialization code into @Before

@Before
void setUp(){
     myClass = new myClass();
     myClass.myObj = myInteface;
}

@Test
void testAbc(){
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

How do I encode/decode HTML entities in Ruby?

I think Nokogiri gem is also a good choice. It is very stable and has a huge contributing community.

Samples:

a = Nokogiri::HTML.parse "foo&nbsp;b&auml;r"    
a.text 
=> "foo bär"

or

a = Nokogiri::HTML.parse "&iexcl;I&#39;m highly&nbsp;annoyed with character references!"
a.text
=> "¡I'm highly annoyed with character references!"

Remove duplicates in the list using linq

This is how I was able to group by with Linq. Hope it helps.

var query = collection.GroupBy(x => x.title).Select(y => y.FirstOrDefault());

How to use if-else option in JSTL

Yes, but it's clunky as hell, e.g.

<c:choose>
  <c:when test="${condition1}">
    ...
  </c:when>
  <c:when test="${condition2}">
    ...
  </c:when>
  <c:otherwise>
    ...
  </c:otherwise>
</c:choose>

Copy an entire worksheet to a new worksheet in Excel 2010

' Assume that the code name the worksheet is Sheet1

' Copy the sheet using code name and put in the end.
' Note: Using the code name lets the user rename the worksheet without breaking the VBA code
Sheet1.Copy After:=Sheets(Sheets.Count)

' Rename the copied sheet keeping the same name and appending a string " copied"
ActiveSheet.Name = Sheet1.Name & " copied"

What does += mean in Python?

Google 'python += operator' leads you to http://docs.python.org/library/operator.html

Search for += once the page loads up for a more detailed answer.

How to use Ajax.ActionLink?

@Ajax.ActionLink requires jQuery AJAX Unobtrusive library. You can download it via nuget:

Install-Package Microsoft.jQuery.Unobtrusive.Ajax

Then add this code to your View:

@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

I solved this problem by using the following,

@await Html.PartialAsync("_ValidationScriptsPartial")

How to launch jQuery Fancybox on page load?

You can also use the native JavaScript function setTimeout() to delay the display of the box after the DOM is ready.

<a id="reference-first" href="#reference-first-message">Test the Popup</a>

<div style="display: none;">
    <div id="reference-first-message" style="width:400px;height:100px;overflow:auto;">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam quis mi eu elit tempor facilisis id et neque. Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare. Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum, vehicula non pretium varius, cursus ac tortor. Vivamus fringilla congue laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in. Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc aliquet tempus sem, id aliquam diam varius ac. Maecenas nisl nunc, molestie vitae eleifend vel, iaculis sed magna. Aenean tempus lacus vitae orci posuere porttitor eget non felis. Donec lectus elit, aliquam nec eleifend sit amet, vestibulum sed nunc.
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function() {
        $("#reference-first").fancybox({
            'titlePosition'         : 'inside',
            'transitionIn'          : 'fade',
            'transitionOut'         : 'fade',
            'overlayColor'          : '#333',
            'overlayOpacity'        : 0.9
        }).trigger("click");

        //launch on load after 5 second delay
        window.setTimeout('$("#reference-first")', 5000);
    });
</script>

Do copyright dates need to be updated?

Copyright should be up to the date of publish.

So, if it's a static content (such as the Times article you linked to), it should probably be statically copyrighted.

If it's dynamically generated content, it should be copyrighted to the current year

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

You are allowed to use IDs that start with a digit in your HTML5 documents:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

But querySelector method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Use a value like b22 for the ID attribute and your code will work.

Since you want to select an element by ID you can also use .getElementById method:

document.getElementById('22')

Validating file types by regular expression

Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots):

^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$

You can use a tool like Expresso to test your regular expressions.

Viewing unpushed Git commits

There is tool named unpushed that scans all Git, Mercurial and Subversion repos in specified working directory and shows list of ucommited files and unpushed commits. Installation is simple under Linux:

$ easy_install --user unpushed

or

$ sudo easy_install unpushed

to install system-wide.

Usage is simple too:

$ unpushed ~/workspace
* /home/nailgun/workspace/unpushed uncommitted (Git)
* /home/nailgun/workspace/unpushed:master unpushed (Git)
* /home/nailgun/workspace/python:new-syntax unpushed (Git)

See unpushed --help or official description for more information. It also has a cronjob script unpushed-notify for on-screen notification of uncommited and unpushed changes.

Could not reserve enough space for object heap to start JVM

According to this post this error message means:

Heap size is larger than your computer's physical memory.

Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.

Why not downsize other memory settings to free up space for the heap?

Reading PDF documents in .Net

You could look into this: http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx It's not completely free, but it looks very nice.

Alex

Is it possible to change the content HTML5 alert messages?

You can use customValidity

$(function(){     var elements = document.getElementsByTagName("input");     for (var i = 0; i < elements.length; i++) {         elements[i].oninvalid = function(e) {             e.target.setCustomValidity("This can't be left blank!");         };     } }); 

I think that will work on at least Chrome and FF, I'm not sure about other browsers

Change hash without reload in jQuery

You can set your hash directly to URL too.

window.location.hash = "YourHash";

The result : http://url#YourHash

Should I use JSLint or JSHint JavaScript validation?

There is also an another actively developed alternative - JSCS — JavaScript Code Style:

JSCS is a code style linter for programmatically enforcing your style guide. You can configure JSCS for your project in detail using over 150 validation rules, including presets from popular style guides like jQuery, Airbnb, Google, and more.

It comes with multiple presets that you can choose from by simply specifying the preset in the .jscsrc configuration file and customize it - override, enable or disable any rules:

{
    "preset": "jquery",
    "requireCurlyBraces": null
}

There are also plugins and extensions built for popular editors.

Also see:

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

I got the same issue and did following to fix it.

  1. Settings > Storage > Clear Cached Data
  2. Settings > Apps > Uninstall the apps showing there. I had uninstalled my apps but it was showing there.
  3. Restart and then everything went fine.

Translating touch events from Javascript to jQuery

jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent (see the Special Properties subheading on this page).

Get current date in Swift 3?

You say in a comment you want to get "15.09.2016".

For this, use Date and DateFormatter:

let date = Date()
let formatter = DateFormatter()

Give the format you want to the formatter:

formatter.dateFormat = "dd.MM.yyyy"

Get the result string:

let result = formatter.string(from: date)

Set your label:

label.text = result

Result:

15.09.2016

Android Studio - Device is connected but 'offline'

To fix this, use USB2 instead of USB3

High-precision clock in Python

The comment left by tiho on Mar 27 '14 at 17:21 deserves to be its own answer:

In order to avoid platform-specific code, use timeit.default_timer()

MySQL - force not to use cache for testing speed of query

Any reference to current date/time will disable the query cache for that selection:

SELECT *,NOW() FROM TABLE

See "Prerequisites and Notes for MySQL Query Cache Use" @ http://dev.mysql.com/tech-resources/articles/mysql-query-cache.html

Not able to start Genymotion device

I've had this issue and none of the suggestions I found anywhere helped, unfortunately. The good news, however, is that the latest versions work without any hacks! I'm referring to Windows 7 host here.

genymotion-2.5.4.exe

VirtualBox-5.0.5-102814-Win.exe (download from test builds)

Edit: This stopped working again after updates so I gave up on Genymotion. The new Android emulator in SDK performs just as well, has great functionaly, and works without hiccups.

How to get first item from a java.util.Set?

Vector has some handy features:

Vector<String> siteIdVector = new Vector<>(siteIdSet);
String first = siteIdVector.firstElement();
String last = siteIdVector.lastElement();

But I do agree - this may have unintended consequences, since the underling set is not guaranteed to be ordered.

What is the difference between aggregation, composition and dependency?

An object associated with a composition relationship will not exist outside the containing object. Examples are an Appointment and the owner (a Person) or a Calendar; a TestResult and a Patient.

On the other hand, an object that is aggregated by a containing object can exist outside that containing object. Examples are a Door and a House; an Employee and a Department.

A dependency relates to collaboration or delegation, where an object requests services from another object and is therefor dependent on that object. As the client of the service, you want the service interface to remain constant, even if future services are offered.

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

What size should apple-touch-icon.png be for iPad and iPhone?

TL;DR: use one PNG icon at 180 x 180 px @ 150 ppi and then link to it like this:

<link rel="apple-touch-icon" href="path/to/apple-touch-icon.png">

Details on the Approach

As of 2020-04, the canonical response from Apple is reflected in their documentation on iOS.

Officially, the spec says:

  • iPhone 180px × 180px (60pt × 60pt @3x)
  • iPhone 120px × 120px (60pt × 60pt @2x)
  • iPad Pro 167px × 167px (83.5pt × 83.5pt @2x)
  • iPad, iPad mini 152px × 152px (76pt × 76pt @2x)

In reality, these sizing differences are tiny, so the performance savings will really only matter on very high traffic sites.

For lower traffic sites, I typically use one PNG icon at 180 x 180 px @ 150 ppi and get very good results on all devices, even the plus sized ones.

How do you use the Immediate Window in Visual Studio?

One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.

For example, if you had a static method that returns the sum of two numbers such as:

private static int GetSum(int a, int b)
{
    return a + b;
}

Then in the Immediate Window you can type the following:

? GetSum(2, 4)
6

As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.

For example, let’s say this is what your class looks like:

private class Foo
{
    public string GetMessage()
    {
        return "hello";
    }
}

If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):

? foo.GetMessage(); // object ‘foo’ already exists
"hello"

In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:

? Foo foo = new Foo(); // new instance of ‘Foo’
{temp.Program.Foo}
? foo.GetMessage()
"hello"

You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:

? string msg = foo.GetMessage();
"hello"
? msg + " there!"
"hello there!"

Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:

? new Foo().GetMessage()
"hello" 

A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.

Along with inspecting methods, you can do simple math equations:

? 5 * 6
30

or compare values:

? 5==6
false
? 6==6
true

The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.

Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.

Unfortunately, another drawback of the Immediate Window is that it does not support loops.

Add IIS 7 AppPool Identities as SQL Server Logons

You can solve like this,

  1. Open "Applications Pools",
  2. You should right click that you have choosed application pool. Then choose "Advanced Settings".
  3. Click three point on the Identity tab then you should choose "LocalSystem" from field of "Built-in-account"

If you do this way, you don't need to create a user in database.

How to delete selected text in the vi editor

If you want to delete using line numbers you can use:

:startingline, last line d

Example:

:7,20 d

This example will delete line 7 to 20.

How to stop a setTimeout loop?

You need to use a variable to track "doneness" and then test it on every iteration of the loop. If done == true then return.

var done = false;

function setBgPosition() {
    if ( done ) return;
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        if ( done ) return;
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length)
        {
            setTimeout(run, 200);
        }else
        {
            setBgPosition();
        }
    }
    setTimeout(run, 200);
}

setBgPosition(); // start the loop

setTimeout( function(){ done = true; }, 5000 ); // external event to stop loop

Create a table without a header in Markdown

$ cat foo.md
Key 1 | Value 1
Key 2 | Value 2
$ kramdown foo.md
<table>
  <tbody>
    <tr>
      <td>Key 1</td>
      <td>Value 1</td>
    </tr>
    <tr>
      <td>Key 2</td>
      <td>Value 2</td>
    </tr>
  </tbody>
</table>

Converting dictionary to JSON

Defining r as a dictionary should do the trick:

>>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
>>> print(r['rating'])
3.5
>>> type(r)
<class 'dict'>

jquery input select all on focus

This would do the work and avoid the issue that you can no longer select part of the text by mouse.

$("input[type=text]").click(function() {
    if(!$(this).hasClass("selected")) {
        $(this).select();
        $(this).addClass("selected");
    }
});
$("input[type=text]").blur(function() {
    if($(this).hasClass("selected")) {
        $(this).removeClass("selected");
    }
});

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

There is no sentence caps option in CSS. The other answers suggesting text-transform: capitalize are incorrect as that option capitalizes each word.

Here's a crude way to accomplish it if you only want the first letter of each element to be uppercase, but it's definitely nowhere near actual sentence caps:

p {
    text-transform: lowercase;
}

p:first-letter {
    text-transform: uppercase;
}
<p>THIS IS AN EXAMPLE SENTENCE.</p>
<p>THIS IS ANOTHER EXAMPLE SENTENCE.
   AND THIS IS ANOTHER, BUT IT WILL BE ENTIRELY LOWERCASE.</p>

Check file extension in upload form in PHP

Not sure if this would have a faster computational time, but another option...

$acceptedFormats = array('gif', 'png', 'jpg');

if(!in_array(pathinfo($filename, PATHINFO_EXTENSION), $acceptedFormats))) {
    echo 'error';
}

concatenate char array in C

You can concatenate strings by using the sprintf() function. In your case, for example:

char file[80];
sprintf(file,"%s%s",name,extension);

And you'll end having the concatenated string in "file".

RecyclerView onClick

here my way

in activity class:

    public class MyActivity extends AppCompatActivity implements EmployeeAdapter.ClickListener {
    ...
    @Override
    public void onClick(int position) { ... }
    ...
    }

in adapter class:

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    ...
    @Override
    public void onBindViewHolder(){
         holder.textView1.setOnClickListener(v -> clickListener.onClick(position));
    }
    ...
    public interface ClickListener {
        void onClick(int position);
    }
    ...
    }

What are public, private and protected in object oriented programming?

All the three are access modifiers and keywords which are used in a class. Anything declared in public can be used by any object within the class or outside the class,variables in private can only be used by the objects within the class and could not be changed through direct access(as it can change through functions like friend function).Anything defined under protected section can be used by the class and their just derived class.

Using python map and other functional tools

How about this:

foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]

def maptest(foo, bar):
    print foo, bar

map(maptest, foos, [bars]*len(foos))

OAuth: how to test with local URLs?

I found xip.io which automatically converts a fixed url to a embedded localhost domain.

For example lets say your localhost server is running on 127.0.0.1:8000 You can go to http://www.127.0.0.1.xip.io:5555/ to access this server. You can then add this address to Oauth configuration for Facebook or Google.

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

I would suggest that you use the fyiReporting (Forked and Moved Now Current as of 2012) tool if you are looking to replace Crystal Reports. I have used both fyiReporting and Crystal and would have to say that I prefer fyiReporting(though their website is ghetto).

Reasons for choosing fyiReporting

  1. If you want to replace Crystal then you are used to having a Report designer. FyiReporting has its own GUI just like Crystal Reports for creating and running reports(You could just create and distribute reports without building an application).

  2. FyiReports allows you to export the Report as PDF, excel and mht(static web page) just to mention a few.

  3. FyiReports are xml based so the report definition can be saved in a database and altered at anytime.

  4. If you are using .Net FyiReporting has a Web and Windows Forms control for embedding the report in your applications(much like crystal reports). I am not so sure about Java as I am a .Net guy.

Anyway give FyiReports a try.

How to create a horizontal loading progress bar?

Just add a STYLE line and your progress becomes horizontal:

<ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progress"
        android:layout_centerHorizontal="true"      
        android:layout_centerVertical="true"      
        android:max="100" 
        android:progress="45"/>

Check orientation on Android phone

It's also worth noting that nowadays, there's less good reason to check for explicit orientation with getResources().getConfiguration().orientation if you're doing so for layout reasons, as Multi-Window Support introduced in Android 7 / API 24+ could mess with your layouts quite a bit in either orientation. Better to consider using <ConstraintLayout>, and alternative layouts dependent on available width or height, along with other tricks for determining which layout is being used, e.g. the presence or not of certain Fragments being attached to your Activity.

Importing .py files in Google Colab

It's Jun 2019. Make sure in the Python package's __init__.py all related files are imported in order. Push the code to Git or use this code.

for e.g,

from .Boxes import *
from .Circles import *
from .Rectangles import *
...

Don't use Package name in __init__.py file for importing the files.

in Google colab,

! rm -rf SorghumHeadDetection
! git clone https://github.com/user/amazing-repo-name/

How to iterate through SparseArray?

For removing all the elements from SparseArray using the above looping leads to Exception.

To avoid this Follow the below code to remove all the elements from SparseArray using normal loops

private void getValues(){      
    for(int i=0; i<sparseArray.size(); i++){
          int key = sparseArray.keyAt(i);
          Log.d("Element at "+key, " is "+sparseArray.get(key));
          sparseArray.remove(key);
          i=-1;
    }
}

iPhone App Icons - Exact Radius?

Update (as of Jan. 2018) for App Icon requirements:


https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/app-icon/

Keep icon corners square. The system applies a mask that rounds icon corners automatically.

Keep the background simple and avoid transparency. Make sure your icon is opaque, and don’t clutter the background. Give it a simple background so it doesn’t overpower other app icons nearby. You don’t need to fill the entire icon with content.

Synchronous Requests in Node.js

You can use retus to make cross-platform synchronous HTTP requests:

const retus = require("retus");

const { body } = retus("https://google.com");
//=> "<!doctype html>..."

That's it!

EL access a map value by Integer key

Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter. In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.

One way to get around this is to do something like this.

<c:set var="longKey" value="${param.selectedIndex + 0}"/>

This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.

Then, continue as usual with something like

${map[longKey]}

Javascript extends class

   extend = function(destination, source) {   
          for (var property in source) {
            destination[property] = source[property];
          }
          return destination;
    };

Extending JavaScript

You could also add filters into the for loop.

How to load a resource bundle from a file resource in Java?

As long as you name your resource bundle files correctly (with a .properties extension), then this works:

File file = new File("C:\\temp");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("myResource", Locale.getDefault(), loader);

where "c:\temp" is the external folder (NOT on the classpath) holding the property files, and "myResource" relates to myResource.properties, myResource_fr_FR.properties, etc.

Credit to http://www.coderanch.com/t/432762/java/java/absolute-path-bundle-file

Only allow Numbers in input Tag without Javascript

Though it's probably suggested to get some heavier validation via JS or on the server, HTML5 does support this via the pattern attribute.

<input type= "text" name= "name" pattern= "[0-9]"  title= "Title"/>

extract date only from given timestamp in oracle sql

In Oracle 11g, To get the complete date from the Timestamp, use this-

Select TRUNC(timestamp) FROM TABLE_NAME;

To get the Year from the Timestamp, use this-

Select EXTRACT(YEAR FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Month from the Timestamp, use this-

Select EXTRACT(MONTH FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Day from the Timestamp, use this-

Select EXTRACT(DAY FROM TRUNC(timestamp)) from TABLE_NAME;

C# how to use enum with switch

No need to convert. You can apply conditions on Enums inside a switch. Like so,

public enum Operator
{ 
    PLUS,
    MINUS,
    MULTIPLY,
    DIVIDE
}

public double Calculate(int left, int right, Operator op)
{
    switch (op)
    {
        case Operator.PLUS: return left + right; 
        case Operator.MINUS: return left - right; 
        case Operator.MULTIPLY: return left * right;
        case Operator.DIVIDE: return left / right;
        default: return 0.0; 
    }
}

Then, call it like this:

Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, Operator.PLUS));

Use Toast inside Fragment

user2564789 said it right
But you can also use this in the place of getActivity()
which will make your toast look like this


     Toast.makeText(this,"Message",Toast.LENGTH_SHORT).show();
    

Use .corr to get the correlation between two columns

It works like this:

Top15['Citable docs per Capita']=np.float64(Top15['Citable docs per Capita'])

Top15['Energy Supply per Capita']=np.float64(Top15['Energy Supply per Capita'])

Top15['Energy Supply per Capita'].corr(Top15['Citable docs per Capita'])

How can I change the date format in Java?

To Change the format of Date you have Require both format look below.

 String stringdate1 = "28/04/2010";  

 try {

     SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
     Date date1 = format1.parse()
     SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");

     String stringdate2 = format2.format(date1);
    } catch (ParseException e) {
   e.printStackTrace();
}

here stringdate2 have date format of yyyy/MM/dd. and it contain 2010/04/28.

How to change dataframe column names in pyspark?

You can use the following function to rename all the columns of your dataframe.

def df_col_rename(X, to_rename, replace_with):
    """
    :param X: spark dataframe
    :param to_rename: list of original names
    :param replace_with: list of new names
    :return: dataframe with updated names
    """
    import pyspark.sql.functions as F
    mapping = dict(zip(to_rename, replace_with))
    X = X.select([F.col(c).alias(mapping.get(c, c)) for c in to_rename])
    return X

In case you need to update only a few columns' names, you can use the same column name in the replace_with list

To rename all columns

df_col_rename(X,['a', 'b', 'c'], ['x', 'y', 'z'])

To rename a some columns

df_col_rename(X,['a', 'b', 'c'], ['a', 'y', 'z'])

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

Find which commit is currently checked out in Git

If you want to extract just a simple piece of information, you can get that using git show with the --format=<string> option...and ask it not to give you the diff with --no-patch. This means you can get a printf-style output of whatever you want, which might often be a single field.

For instance, to get just the shortened hash (%h) you could say:

$ git show --format="%h" --no-patch
4b703eb

If you're looking to save that into an environment variable in bash (a likely thing for people to want to do) you can use the $() syntax:

$ GIT_COMMIT="$(git show --format="%h" --no-patch)"

$ echo $GIT_COMMIT
4b703eb

The full list of what you can do is in git show --help. But here's an abbreviated list of properties that might be useful:

  • %H commit hash
  • %h abbreviated commit hash
  • %T tree hash
  • %t abbreviated tree hash
  • %P parent hashes
  • %p abbreviated parent hashes
  • %an author name
  • %ae author email
  • %at author date, UNIX timestamp
  • %aI author date, strict ISO 8601 format
  • %cn committer name
  • %ce committer email
  • %ct committer date, UNIX timestamp
  • %cI committer date, strict ISO 8601 format
  • %s subject
  • %f sanitized subject line, suitable for a filename
  • %gD reflog selector, e.g., refs/stash@{1}
  • %gd shortened reflog selector, e.g., stash@{1}

Python, HTTPS GET with basic authentication

Based on the @AndrewCox 's answer with some minor improvements:

from http.client import HTTPSConnection
from base64 import b64encode


client = HTTPSConnection("www.google.com")
user = "user_name"
password = "password"
headers = {
    "Authorization": "Basic {}".format(
        b64encode(bytes(f"{user}:{password}", "utf-8")).decode("ascii")
    )
}
client.request('GET', '/', headers=headers)
res = client.getresponse()
data = res.read()

Note, you should set encoding if you use bytes function instead of b"".

How long will my session last?

You're searching for gc_maxlifetime, see http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime for a description.

Your session will last 1440 seconds which is 24 minutes (default).

Inserting string at position x of another string

Maybe it's even better if you determine position using indexOf() like this:

function insertString(a, b, at)
{
    var position = a.indexOf(at); 

    if (position !== -1)
    {
        return a.substr(0, position) + b + a.substr(position);    
    }  

    return "substring not found";
}

then call the function like this:

insertString("I want apple", "an ", "apple");

Note, that I put a space after the "an " in the function call, rather than in the return statement.

How to run code after some delay in Flutter?

(Adding response on old q as this is the top result on google)

I tried yielding a new state in the callback within a bloc, and it didn't work. Tried with Timer and Future.delayed.

However, what did work was...

await Future.delayed(const Duration(milliseconds: 500));

yield newState;

Awaiting an empty future then running the function afterwards.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

From Gradle Plugin User Guide:

When instrumentation tests are run, both the main APK and test APK share the same classpath. Gradle build will fail if the main APK and the test APK use the same library (e.g. Guava) but in different versions. If gradle didn't catch that, your app could behave differently during tests and during normal run (including crashing in one of the cases).

To make the build succeed, just make sure both APKs use the same version. If the error is about an indirect dependency (a library you didn't mention in your build.gradle), just add a dependency for the newer version to the configuration

Add this line to your build.gradle dependencies to use newer version for both APKs:

compile('com.google.code.findbugs:jsr305:2.0.1')

For future reference, you can check your Gradle Console and it will provide a helpful link next to the error to help with any gradle build errors.

Border Radius of Table is not working

A note to this old question:

My reset.css had set border-spacing: 0, causing the corners to get cut off. I had to set it to 3px for my radius to work properly (value will depend on the radius in question).

How to pass argument to Makefile from command line?

Here is a generic working solution based on @Beta's

I'm using GNU Make 4.1 with SHELL=/bin/bash atop my Makefile, so YMMV!

This allows us to accept extra arguments (by doing nothing when we get a job that doesn't match, rather than throwing an error).

%:
    @:

And this is a macro which gets the args for us:

args = `arg="$(filter-out $@,$(MAKECMDGOALS))" && echo $${arg:-${1}}`

Here is a job which might call this one:

test:
    @echo $(call args,defaultstring)

The result would be:

$ make test
defaultstring
$ make test hi
hi

Note! You might be better off using a "Taskfile", which is a bash pattern that works similarly to make, only without the nuances of Maketools. See https://github.com/adriancooney/Taskfile

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

What does "control reaches end of non-void function" mean?

Compiler by itself would not know that the conditions you have given are optimum .. meaning of this is you have covered all cases .. So therefore it always wants a return statement ... So either you can change last else if with else or just write return 0 after last else if ;`int binary(int val, int sorted[], int low, int high) { int mid = (low+high)/2;

if(high < low)
    return -1;

if(val < sorted[mid])
    return binary(val, sorted, low, mid-1);

else if(val > sorted[mid])
    return binary(val, sorted, mid+1, high);

else if(val == sorted[mid])
    return mid;
return 0; }`

How to round a Double to the nearest Int in swift?

Swift 3 & 4 - making use of the rounded(_:) method as blueprinted in the FloatingPoint protocol

The FloatingPoint protocol (to which e.g. Double and Float conforms) blueprints the rounded(_:) method

func rounded(_ rule: FloatingPointRoundingRule) -> Self

Where FloatingPointRoundingRule is an enum enumerating a number of different rounding rules:

case awayFromZero

Round to the closest allowed value whose magnitude is greater than or equal to that of the source.

case down

Round to the closest allowed value that is less than or equal to the source.

case toNearestOrAwayFromZero

Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.

case toNearestOrEven

Round to the closest allowed value; if two values are equally close, the even one is chosen.

case towardZero

Round to the closest allowed value whose magnitude is less than or equal to that of the source.

case up

Round to the closest allowed value that is greater than or equal to the source.

We make use of similar examples to the ones from @Suragch's excellent answer to show these different rounding options in practice.

.awayFromZero

Round to the closest allowed value whose magnitude is greater than or equal to that of the source; no direct equivalent among the C functions, as this uses, conditionally on sign of self, ceil or floor, for positive and negative values of self, respectively.

3.000.rounded(.awayFromZero) // 3.0
3.001.rounded(.awayFromZero) // 4.0
3.999.rounded(.awayFromZero) // 4.0

(-3.000).rounded(.awayFromZero) // -3.0
(-3.001).rounded(.awayFromZero) // -4.0
(-3.999).rounded(.awayFromZero) // -4.0

.down

Equivalent to the C floor function.

3.000.rounded(.down) // 3.0
3.001.rounded(.down) // 3.0
3.999.rounded(.down) // 3.0

(-3.000).rounded(.down) // -3.0
(-3.001).rounded(.down) // -4.0
(-3.999).rounded(.down) // -4.0

.toNearestOrAwayFromZero

Equivalent to the C round function.

3.000.rounded(.toNearestOrAwayFromZero) // 3.0
3.001.rounded(.toNearestOrAwayFromZero) // 3.0
3.499.rounded(.toNearestOrAwayFromZero) // 3.0
3.500.rounded(.toNearestOrAwayFromZero) // 4.0
3.999.rounded(.toNearestOrAwayFromZero) // 4.0

(-3.000).rounded(.toNearestOrAwayFromZero) // -3.0
(-3.001).rounded(.toNearestOrAwayFromZero) // -3.0
(-3.499).rounded(.toNearestOrAwayFromZero) // -3.0
(-3.500).rounded(.toNearestOrAwayFromZero) // -4.0
(-3.999).rounded(.toNearestOrAwayFromZero) // -4.0

This rounding rule can also be accessed using the zero argument rounded() method.

3.000.rounded() // 3.0
// ...

(-3.000).rounded() // -3.0
// ...

.toNearestOrEven

Round to the closest allowed value; if two values are equally close, the even one is chosen; equivalent to the C rint (/very similar to nearbyint) function.

3.499.rounded(.toNearestOrEven) // 3.0
3.500.rounded(.toNearestOrEven) // 4.0 (up to even)
3.501.rounded(.toNearestOrEven) // 4.0

4.499.rounded(.toNearestOrEven) // 4.0
4.500.rounded(.toNearestOrEven) // 4.0 (down to even)
4.501.rounded(.toNearestOrEven) // 5.0 (up to nearest)

.towardZero

Equivalent to the C trunc function.

3.000.rounded(.towardZero) // 3.0
3.001.rounded(.towardZero) // 3.0
3.999.rounded(.towardZero) // 3.0

(-3.000).rounded(.towardZero) // 3.0
(-3.001).rounded(.towardZero) // 3.0
(-3.999).rounded(.towardZero) // 3.0

If the purpose of the rounding is to prepare to work with an integer (e.g. using Int by FloatPoint initialization after rounding), we might simply make use of the fact that when initializing an Int using a Double (or Float etc), the decimal part will be truncated away.

Int(3.000) // 3
Int(3.001) // 3
Int(3.999) // 3

Int(-3.000) // -3
Int(-3.001) // -3
Int(-3.999) // -3

.up

Equivalent to the C ceil function.

3.000.rounded(.up) // 3.0
3.001.rounded(.up) // 4.0
3.999.rounded(.up) // 4.0

(-3.000).rounded(.up) // 3.0
(-3.001).rounded(.up) // 3.0
(-3.999).rounded(.up) // 3.0

Addendum: visiting the source code for FloatingPoint to verify the C functions equivalence to the different FloatingPointRoundingRule rules

If we'd like, we can take a look at the source code for FloatingPoint protocol to directly see the C function equivalents to the public FloatingPointRoundingRule rules.

From swift/stdlib/public/core/FloatingPoint.swift.gyb we see that the default implementation of the rounded(_:) method makes us of the mutating round(_:) method:

public func rounded(_ rule: FloatingPointRoundingRule) -> Self {
    var lhs = self
    lhs.round(rule)
    return lhs
}

From swift/stdlib/public/core/FloatingPointTypes.swift.gyb we find the default implementation of round(_:), in which the equivalence between the FloatingPointRoundingRule rules and the C rounding functions is apparent:

public mutating func round(_ rule: FloatingPointRoundingRule) {
    switch rule {
    case .toNearestOrAwayFromZero:
        _value = Builtin.int_round_FPIEEE${bits}(_value)
    case .toNearestOrEven:
        _value = Builtin.int_rint_FPIEEE${bits}(_value)
    case .towardZero:
        _value = Builtin.int_trunc_FPIEEE${bits}(_value)
    case .awayFromZero:
        if sign == .minus {
            _value = Builtin.int_floor_FPIEEE${bits}(_value)
        }
        else {
            _value = Builtin.int_ceil_FPIEEE${bits}(_value)
        }
    case .up:
        _value = Builtin.int_ceil_FPIEEE${bits}(_value)
    case .down:
        _value = Builtin.int_floor_FPIEEE${bits}(_value)
    }
}

How to concatenate multiple lines of output to one line?

Use tr '\n' ' ' to translate all newline characters to spaces:

$ grep pattern file | tr '\n' ' '

Note: grep reads files, cat concatenates files. Don't cat file | grep!

Edit:

tr can only handle single character translations. You could use awk to change the output record separator like:

$ grep pattern file | awk '{print}' ORS='" '

This would transform:

one
two 
three

to:

one" two" three" 

How do I seed a random class to avoid getting duplicate random values

this workes for me:

private int GetaRandom()
    {
        Thread.Sleep(1);
        return new Random(DateTime.Now.Millisecond).Next();
    }

How open PowerShell as administrator from the run window

The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":

[Windows 10/Windows 8 Power User menu with "Windows Powershell (Admin)

Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:

[Taskbar and Start Menu Properties: "Replace Command Prompt With Windows Powershell"

Gradle to execute Java class (without modifying build.gradle)

You just need to use the Gradle Application plugin:

apply plugin:'application'
mainClassName = "org.gradle.sample.Main"

And then simply gradle run.

As Teresa points out, you can also configure mainClassName as a system property and run with a command line argument.

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

TypeError: a bytes-like object is required, not 'str'

Whenever you encounter an error with this message use my_string.encode().

(where my_string is the string you're passing to a function/method).

The encode method of str objects returns the encoded version of the string as a bytes object which you can then use. In this specific instance, socket methods such as .send expect a bytes object as the data to be sent, not a string object.

Since you have an object of type str and you're passing it to a function/method that expects an object of type bytes, an error is raised that clearly explains that:

TypeError: a bytes-like object is required, not 'str'

So the encode method of strings is needed, applied on a str value and returning a bytes value:

>>> s = "Hello world"
>>> print(type(s))
<class 'str'>
>>> byte_s = s.encode()
>>> print(type(byte_s))
<class 'bytes'>
>>> print(byte_s)
b"Hello world"

Here the prefix b in b'Hello world' denotes that this is indeed a bytes object. You can then pass it to whatever function is expecting it in order for it to run smoothly.

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

  • groupByKey() is just to group your dataset based on a key. It will result in data shuffling when RDD is not already partitioned.
  • reduceByKey() is something like grouping + aggregation. We can say reduceBykey() equvelent to dataset.group(...).reduce(...). It will shuffle less data unlike groupByKey().
  • aggregateByKey() is logically same as reduceByKey() but it lets you return result in different type. In another words, it lets you have a input as type x and aggregate result as type y. For example (1,2),(1,4) as input and (1,"six") as output. It also takes zero-value that will be applied at the beginning of each key.

Note : One similarity is they all are wide operations.

Convert wchar_t to char

An easy way is :

        wstring your_wchar_in_ws(<your wchar>);
        string your_wchar_in_str(your_wchar_in_ws.begin(), your_wchar_in_ws.end());
        char* your_wchar_in_char =  your_wchar_in_str.c_str();

I'm using this method for years :)

Where is the itoa function in Linux?

Here is a much improved version of Archana's solution. It works for any radix 1-16, and numbers <= 0, and it shouldn't clobber memory.

static char _numberSystem[] = "0123456789ABCDEF";
static char _twosComp[] = "FEDCBA9876543210";

static void safestrrev(char *buffer, const int bufferSize, const int strlen)
{
    int len = strlen;
    if (len > bufferSize)
    {
        len = bufferSize;
    }
    for (int index = 0; index < (len / 2); index++)
    {
        char ch = buffer[index];
        buffer[index] = buffer[len - index - 1];
        buffer[len - index - 1] = ch;
    }
}

static int negateBuffer(char *buffer, const int bufferSize, const int strlen, const int radix)
{
    int len = strlen;
    if (len > bufferSize)
    {
        len = bufferSize;
    }
    if (radix == 10)
    {
        if (len < (bufferSize - 1))
        {
            buffer[len++] = '-';
            buffer[len] = '\0';
        }
    }
    else
    {
        int twosCompIndex = 0;
        for (int index = 0; index < len; index++)
        {
            if ((buffer[index] >= '0') && (buffer[index] <= '9'))
            {
                twosCompIndex = buffer[index] - '0';
            }
            else if ((buffer[index] >= 'A') && (buffer[index] <= 'F'))
            {
                twosCompIndex = buffer[index] - 'A' + 10;
            }
            else if ((buffer[index] >= 'a') && (buffer[index] <= 'f'))
            {
                twosCompIndex = buffer[index] - 'a' + 10;
            }
            twosCompIndex += (16 - radix);
            buffer[index] = _twosComp[twosCompIndex];
        }
        if (len < (bufferSize - 1))
        {
            buffer[len++] = _numberSystem[radix - 1];
            buffer[len] = 0;
        }
    }
    return len;
}

static int twosNegation(const int x, const int radix)
{
    int n = x;
    if (x < 0)
    {
        if (radix == 10)
        {
            n = -x;
        }
        else
        {
            n = ~x;
        }
    }
    return n;
}

static char *safeitoa(const int x, char *buffer, const int bufferSize, const int radix)
{
    int strlen = 0;
    int n = twosNegation(x, radix);
    int nuberSystemIndex = 0;

    if (radix <= 16)
    {
        do
        {
            if (strlen < (bufferSize - 1))
            {
                nuberSystemIndex = (n % radix);
                buffer[strlen++] = _numberSystem[nuberSystemIndex];
                buffer[strlen] = '\0';
                n = n / radix;
            }
            else
            {
                break;
            }
        } while (n != 0);
        if (x < 0)
        {
            strlen = negateBuffer(buffer, bufferSize, strlen, radix);
        }
        safestrrev(buffer, bufferSize, strlen);
        return buffer;
    }
    return NULL;
}

Gradle - Could not find or load main class

For Netbeans 11 users, this works for me:

apply plugin: 'java'
apply plugin: 'application'

// This comes out to package + '.' + mainClassName
mainClassName = 'com.hello.JavaApplication1'

Here generally is my tree:

C:\...\NETBEANSPROJECTS\JAVAAPPLICATION1
¦   build.gradle
+---src
¦   +---main
¦   ¦   +---java
¦   ¦       +---com
¦   ¦           +---hello
¦   ¦                   JavaApplication1.java
¦   ¦
¦   +---test
¦       +---java
+---test

Function to convert timestamp to human date in javascript

we need to create new function using JavaScript.

function unixTime(unixtime) {

    var u = new Date(unixtime*1000);

      return u.getUTCFullYear() +
        '-' + ('0' + u.getUTCMonth()).slice(-2) +
        '-' + ('0' + u.getUTCDate()).slice(-2) + 
        ' ' + ('0' + u.getUTCHours()).slice(-2) +
        ':' + ('0' + u.getUTCMinutes()).slice(-2) +
        ':' + ('0' + u.getUTCSeconds()).slice(-2) +
        '.' + (u.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) 
    };

console.log(unixTime(1370001284))

2016-04-30 08:36:26.000

What is logits, softmax and softmax_cross_entropy_with_logits?

Above answers have enough description for the asked question.

Adding to that, Tensorflow has optimised the operation of applying the activation function then calculating cost using its own activation followed by cost functions. Hence it is a good practice to use: tf.nn.softmax_cross_entropy() over tf.nn.softmax(); tf.nn.cross_entropy()

You can find prominent difference between them in a resource intensive model.

DECODE( ) function in SQL Server

Create a function in SQL Server as below and replace the DECODE with dbo.DECODE

CREATE FUNCTION DECODE(@CondField as nvarchar(100),@Criteria as nvarchar(100), 
                       @True Value as nvarchar(100), @FalseValue as nvarchar(100))
returns nvarchar(100)
begin
       return case when @CondField = @Criteria then @TrueValue 
                   else @FalseValue end
end

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

Java constructor/method with optional parameters?

Java doesn't support default parameters. You will need to have two constructors to do what you want.

An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.

e.g.

   public class Foo {
     private final String param1;
     private final String param2;

     private Foo(Builder builder) {
       this.param1 = builder.param1;
       this.param2 = builder.param2;
     }
     public static class Builder {
       private String param1 = "defaultForParam1";
       private String param2 = "defaultForParam2";

       public Builder param1(String param1) {
         this.param1 = param1;
         return this;
       }
       public Builder param2(String param1) {
         this.param2 = param2;
         return this;
       }
       public Foo build() {
         return new Foo(this);
       }
     }
   }

which allows you to say:

Foo myFoo = new Foo.Builder().param1("myvalue").build();

which will have a default value for param2.

Getting an option text/value with JavaScript

form.MySelect.options[form.MySelect.selectedIndex].value

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

How do I perform the SQL Join equivalent in MongoDB?

There is a specification that a lot of drivers support that's called DBRef.

DBRef is a more formal specification for creating references between documents. DBRefs (generally) include a collection name as well as an object id. Most developers only use DBRefs if the collection can change from one document to the next. If your referenced collection will always be the same, the manual references outlined above are more efficient.

Taken from MongoDB Documentation: Data Models > Data Model Reference > Database References

How to Update/Drop a Hive Partition?

You may also need to make database containing table active

use [dbname]

otherwise you may get error (even if you specify database i.e. dbname.table )

FAILED Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter partition. Unable to alter partitions because table or database does not exist.

Disable webkit's spin buttons on input type="number"?

Not sure if this is the best way to do it, but this makes the spinners disappear on Chrome 8.0.552.5 dev:

input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

Adding JPanel to JFrame

Instead of having your Test2 class contain a JPanel, you should have it subclass JPanel:

public class Test2 extends JPanel {

Test2(){

...

}

More details:

JPanel is a subclass of Component, so any method that takes a Component as an argument can also take a JPanel as an argument.

Older versions didn't let you add directly to a JFrame; you had to use JFrame.getContentPane().add(Component). If you're using an older version, this might also be an issue. Newer versions of Java do let you call JFrame.add(Component) directly.

How to overcome root domain CNAME restrictions?

CNAME'ing a root record is technically not against RFC, but does have limitations meaning it is a practice that is not recommended.

Normally your root record will have multiple entries. Say, 3 for your name servers and then one for an IP address.

Per RFC:

If a CNAME RR is present at a node, no other data should be present;

And Per IETF 'Common DNS Operational and Configuration Errors' Document:

This is often attempted by inexperienced administrators as an obvious way to allow your domain name to also be a host. However, DNS servers like BIND will see the CNAME and refuse to add any other resources for that name. Since no other records are allowed to coexist with a CNAME, the NS entries are ignored. Therefore all the hosts in the podunk.xx domain are ignored as well!

References:

Detecting scroll direction

Use this to find the scroll direction. This is only to find the direction of the Vertical Scroll. Supports all cross browsers.

var scrollableElement = document.body; //document.getElementById('scrollableElement');

scrollableElement.addEventListener('wheel', checkScrollDirection);

function checkScrollDirection(event) {
  if (checkScrollDirectionIsUp(event)) {
    console.log('UP');
  } else {
    console.log('Down');
  }
}

function checkScrollDirectionIsUp(event) {
  if (event.wheelDelta) {
    return event.wheelDelta > 0;
  }
  return event.deltaY < 0;
}

Example

Twitter bootstrap float div right

This does the trick, without the need to add an inline style

<div class="row-fluid">
    <div class="span6">
        <p>text left</p>
    </div>
    <div class="span6">
        <div class="pull-right">
            <p>text right</p>
        </div>
    </div>
</div>

The answer is in nesting another <div> with the "pull-right" class. Combining the two classes won't work.

How to remove padding around buttons in Android?

For me the problem turned out to be minHeight and minWidth on some of the Android themes.

On the Button element, add:

<Button android:minHeight="0dp" android:minWidth="0dp" ...

Or in your button's style:

<item name="android:minHeight">0dp</item>
<item name="android:minWidth">0dp</item>

display Java.util.Date in a specific format

It makes no sense, but:

System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))

SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String

json_encode(): Invalid UTF-8 sequence in argument

The problem is that this character is UTF8, but json_encode does not handle it correctly. To say more, there is a list of other characters (see Unicode characters list), that will trigger the same error, so stripping off this one (Å) will not correct an issue to the end.

What we have used is to convert these chars to html entities like this:

htmlentities( (string) $value, ENT_QUOTES, 'utf-8', FALSE);

Is an empty href valid?

The current HTML5 draft also allows ommitting the href attribute completely.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant.

To answer your question: Yes it's valid.

How do I use Docker environment variable in ENTRYPOINT array?

I tried to resolve with the suggested answer and still ran into some issues...

This was a solution to my problem:

ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}

# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh

# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]

Specifically targeting your problem:

RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

Adding minutes to date time in PHP

You can do this with native functions easily:

strtotime('+59 minutes', strtotime('2011-11-17 05:05'));

I'd recommend the DateTime class method though, just posted by Tim.

Not connecting to SQL Server over VPN

Try changing Server name with its IP for example

SERVERNAME//SQLSERVER -> 192.168.0.2//SQLSERVER

its work flawlessly with me using VPN

VHDL - How should I create a clock in a testbench?

My favoured technique:

signal clk : std_logic := '0'; -- make sure you initialise!
...
clk <= not clk after half_period;

I usually extend this with a finished signal to allow me to stop the clock:

clk <= not clk after half_period when finished /= '1' else '0';

Gotcha alert: Care needs to be taken if you calculate half_period from another constant by dividing by 2. The simulator has a "time resolution" setting, which often defaults to nanoseconds... In which case, 5 ns / 2 comes out to be 2 ns so you end up with a period of 4ns! Set the simulator to picoseconds and all will be well (until you need fractions of a picosecond to represent your clock time anyway!)

How to run Maven from another directory (without cd to project dir)?

I don't think maven supports this. If you're on Unix, and don't want to leave your current directory, you could use a small shell script, a shell function, or just a sub-shell:

user@host ~/project$ (cd ~/some/location; mvn install)
[ ... mvn build ... ]
user@host ~/project$

As a bash function (which you could add to your ~/.bashrc):

function mvn-there() {
  DIR="$1"
  shift
  (cd $DIR; mvn "$@")     
} 

user@host ~/project$ mvn-there ~/some/location install)
[ ... mvn build ... ]
user@host ~/project$

I realize this doesn't answer the specific question, but may provide you with what you're after. I'm not familiar with the Windows shell, though you should be able to reach a similar solution there as well.

Regards

Understanding the results of Execute Explain Plan in Oracle SQL Developer

Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300

Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.

Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.

Is Unit Testing worth the effort?

Occasionally either myself or one of my co-workers will spend a couple of hours getting to the bottom of slightly obscure bug and once the cause of the bug is found 90% of the time that code isn't unit tested. The unit test doesn't exist because the dev is cutting corners to save time, but then looses this and more debugging.

Taking the small amount of time to write a unit test can save hours of future debugging.

How to show what a commit did?

TL;DR

git show <commit>


Show

To show what a commit did with stats:

git show <commit> --stat

Log

To show commit log with differences introduced for each commit in a range:

git log -p <commit1> <commit2>

What is <commit>?

Each commit has a unique id we reference here as <commit>. The unique id is an SHA-1 hash – a checksum of the content you’re storing plus a header. #TMI

If you don't know your <commit>:

  1. git log to view the commit history

  2. Find the commit you care about.

MongoDB vs Firebase

Firebase is a suite of features .

  • Realtime Database
  • Hosting
  • Authentication
  • Storage
  • Cloud Messaging
  • Remote Config
  • Test Lab
  • Crash Reporting
  • Notifications
  • App Indexing
  • Dynamic Links
  • Invites
  • AdWords
  • AdMob

I believe you are trying to compare Firebase Realtime Database with Mongo DB . Firebase Realtime Database stores data as JSON format and syncs to all updates of the data to all clients listening to the data . It abstracts you from all complexity that is needed to setup and scale any database . I will not recommend firebase where you have lot of complex scenarios where aggregation of data is needed .(Queries that need SUM/AVERAGE kind of stuff ) . Though this is recently achievable using Firebase functions . Modeling data in Firebase is tricky . But it is the best way to get you started instantaneously . MongoDB is a database. This give you lot of powerful features. But MongoDB when installed in any platform you need to manage it by yourself .

When i try to choose between Firebase or MongoDB(or any DB ) . I try to answer the following .

  1. Are there many aggregation queries that gets executed .(Like in case of reporting tool or BI tool ) . If Yes dont go for Firebase
  2. Do i need to perform lot of transaction . (If yes then i would not like to go with firebase) (Tranactions are somewhat easy though after introduction of functions but that is also a overhead if lot of transactions needs to be maintained)
  3. What timeline do i have to get things up and running .(Firebase is very easy to setup and integrate ).
  4. Do i have expertise to scale up the DB and trouble shoot DB related stuffs . (Firebase is more like SAAS so no need to worry about scaleability)

Stop form from submitting , Using Jquery

Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.

Move the e.preventDefault(); as first line in the click handler.

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...

See below code,

I want it to be allowed HasJobInProgress == False

$(document).ready(function () {
    $("form").submit(function (e) {
        e.preventDefault(); //prevent default form submit
        $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data);
            },
            cache: false
        });
    });
});
$("#cancelButton").click(function () {
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
    $(this).select();
});
function showMsg(hasCurrentJob) {
    if (hasCurrentJob == "True") {
        alert("The current clients has a job in progress. No changes can be saved until current job completes");
        return false;
    } else {
       $("form").unbind('submit').submit();
    }
}

How to retrieve a single file from a specific revision in Git?

Using git show $REV:$FILE as it was already pointed out by others is probably the right answer. I'm posting another answer because when I tried this method, I sometimes got the following error from git:

fatal: path 'link/foo' exists on disk, but not in 'HEAD'

The problem occurs when parts of the path to the file are a symbolic link. In those cases, the git show $REV:$FILE method will not work. Steps to reproduce:

$ git init .
$ mkdir test
$ echo hello > test/foo
$ ln -s test link
$ git add .
$ git commit -m "initial commit"
$ cat link/foo
hello
$ git show HEAD:link/foo
fatal: path 'link/foo' exists on disk, but not in 'HEAD'

The problem is, that utilities like realpath don't help here, because the symlink might not exist in the current commit anymore. I don't know about a good general solution. In my case, I knew that the symlink could only exist in the first component of the path, so I solved the problem by using the git show $REV:$FILE method twice. This works, because when git show $REV:$FILE is used on a symlink, then its target gets printed:

$ git show HEAD:link
test

Whereas with directories, the command will output a header, followed by the directory content:

$ git show HEAD:test
tree HEAD:test

foo

So in my case, I just checked the output of the first call to git show $REV:$FILE and if it was only a single line, then I replaced the first component of my path with the result to resolve the symlink through git.

Update multiple rows using select statement

Run a select to make sure it is what you want

SELECT t1.value AS NEWVALUEFROMTABLE1,t2.value AS OLDVALUETABLE2,*
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Update

UPDATE Table2
SET Value = t1.Value
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Also, consider using BEGIN TRAN so you can roll it back if needed, but make sure you COMMIT it when you are satisfied.

How to disable compiler optimizations in gcc?

You can also control optimisations internally with #pragma GCC push_options

#pragma GCC push_options
/* #pragma GCC optimize ("unroll-loops") */     

.... code here .....

#pragma GCC pop_options

PHP multiline string with PHP

You cannot run PHP code within a string like that. It just doesn't work. As well, when you're "out" of PHP code (?>), any text outside of the PHP blocks is considered output anyway, so there's no need for the echo statement.

If you do need to do multiline output from with a chunk of PHP code, consider using a HEREDOC:

<?php

$var = 'Howdy';

echo <<<EOL
This is output
And this is a new line
blah blah blah and this following $var will actually say Howdy as well

and now the output ends
EOL;

Insert entire DataTable into database at once instead of row by row?

Since you have a DataTable already, and since I am assuming you are using SQL Server 2008 or better, this is probably the most straightforward way. First, in your database, create the following two objects:

CREATE TYPE dbo.MyDataTable -- you can be more speciifc here
AS TABLE
(
  col1 INT,
  col2 DATETIME
  -- etc etc. The columns you have in your data table.
);
GO

CREATE PROCEDURE dbo.InsertMyDataTable
  @dt AS dbo.MyDataTable READONLY
AS
BEGIN
  SET NOCOUNT ON;

  INSERT dbo.RealTable(column list) SELECT column list FROM @dt;
END
GO

Now in your C# code:

DataTable tvp = new DataTable();
// define / populate DataTable

using (connectionObject)
{
    SqlCommand cmd = new SqlCommand("dbo.InsertMyDataTable", connectionObject);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlParameter tvparam = cmd.Parameters.AddWithValue("@dt", tvp);
    tvparam.SqlDbType = SqlDbType.Structured;
    cmd.ExecuteNonQuery();
}

If you had given more specific details in your question, I would have given a more specific answer.

How to parse data in JSON format?

Can use either json or ast python modules:

Using json :
=============

import json
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_data = json.loads(jsonStr)
print(f"json_data: {json_data}")
print(f"json_data['two']: {json_data['two']}")

Output:
json_data: {'one': '1', 'two': '2', 'three': '3'}
json_data['two']: 2




Using ast:
==========

import ast
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_dict = ast.literal_eval(jsonStr)
print(f"json_dict: {json_dict}")
print(f"json_dict['two']: {json_dict['two']}")

Output:
json_dict: {'one': '1', 'two': '2', 'three': '3'}
json_dict['two']: 2

how to rename an index in a cluster?

As indicated in Elasticsearch reference for snapshot module,

The rename_pattern and rename_replacement options can be also used to rename index on restore using regular expression

Run PowerShell command from command prompt (no ps1 script)

Run it on a single command line like so:

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile 
  -WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath> 
  -Recurse -FileType <type>"

Specify JDK for Maven to use

I know its an old thread. But I was having some issues with something similar to this in Maven for Java 8 compiler source. I figured this out with a quick fix mentioned in this article thought I can put it here and maybe can help others:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

What is the purpose of a question mark after a type (for example: int? myVariable)?

To add on to the answers above, here is a code sample

struct Test
{
    int something;
}
struct NullableTest
{
    int something;
}
class Example
{
    public void Demo()
    {
        Test t = new Test();
        t = null;

        NullableTest? t2 = new NullableTest();
        t2 = null;
    }
}

This would give a compilation error:

Error 12 Cannot convert null to 'Test' because it is a non-nullable value type

Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)

How do I change the JAVA_HOME for ant?

When running ant from the shell, you don't need to export JAVA_HOME first, which would set that variable for your current shell and all future commands, instead use

user@host:~# JAVA_HOME=/path/to/jdk ant targets

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

Simple solution to consume the \n character:

import java.util.Scanner;
class string
{
    public static void main(String a[]){
        int a;
        String s;
        Scanner scan = new Scanner(System.in);

        System.out.println("enter a no");
        a = scan.nextInt();
        System.out.println("no is ="+a);

        scan.nextLine();
        System.out.println("enter a string");
        s = scan.nextLine();
        System.out.println("string is="+s);
    }
}

How can I scroll a div to be visible in ReactJS?

To build on @Michelle Tilley's answer, I sometimes want to scroll if the user's selection changes, so I trigger the scroll on componentDidUpdate. I also did some math to figure out how far to scroll and whether scrolling was needed, which for me looks like the following:

_x000D_
_x000D_
  componentDidUpdate() {_x000D_
    let panel, node;_x000D_
    if (this.refs.selectedSection && this.refs.selectedItem) {_x000D_
      // This is the container you want to scroll.          _x000D_
      panel = this.refs.listPanel;_x000D_
      // This is the element you want to make visible w/i the container_x000D_
      // Note: You can nest refs here if you want an item w/i the selected item          _x000D_
      node = ReactDOM.findDOMNode(this.refs.selectedItem);_x000D_
    }_x000D_
_x000D_
    if (panel && node &&_x000D_
      (node.offsetTop > panel.scrollTop + panel.offsetHeight || node.offsetTop < panel.scrollTop)) {_x000D_
      panel.scrollTop = node.offsetTop - panel.offsetTop;_x000D_
    }_x000D_
  }
_x000D_
_x000D_
_x000D_

Declare a dictionary inside a static class

OK - so I'm working in ASP 2.x (not my choice...but hey who's bitching?).

None of the initialize Dictionary examples would work. Then I came across this: http://kozmic.pl/archive/2008/03/13/framework-tips-viii-initializing-dictionaries-and-collections.aspx

...which hipped me to the fact that one can't use collections initialization in ASP 2.x.

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.

Example:

select
  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
  (
  select
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  from
    dual
  ) test_data

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

Remove all special characters except space from a string using JavaScript

_x000D_
_x000D_
const str = "abc's@thy#^g&test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
_x000D_
_x000D_
_x000D_

iPhone and WireShark

The tcpdump tool is available under gnu.

You can use it instead of wireshark.

How I can print to stderr in C?

If you don't want to modify current codes and just for debug usage.

Add this macro:

#define printf(args...) fprintf(stderr, ##args)
//under GCC
#define printf(args...) fprintf(stderr, __VA_ARGS__)
//under MSVC

Change stderr to stdout if you want to roll back.

It's helpful for debug, but it's not a good practice.

Where can I set environment variables that crontab will use?

Expanding on @carestad example, which I find easier, is to run the script with cron and have the environment in the script.

In crontab -e file:

SHELL=/bin/bash

*/1 * * * * $HOME/cron_job.sh

In cron_job.sh file:

#!/bin/bash
source $HOME/.bash_profile
some_other_cmd

Any command after the source of .bash_profile will have your environment as if you logged in.